import { useCallback, useEffect, useState } from 'react'; import type { ISeoSettings } from '../../service/seo/seo.interface'; import { fetchSeoSettings } from '../../service/seo/seo.service'; /** * The SEO settings payload every SEO page starts from: loaded once on * mount, replaced by whatever a save returns. */ export const useSeoSettings = (): { settings: ISeoSettings | null; setSettings: (settings: ISeoSettings) => void; error: string | null; reload: () => Promise; } => { const [settings, setSettings] = useState(null); const [error, setError] = useState(null); const reload = useCallback( (): Promise => fetchSeoSettings() .then(data => { setSettings(data); setError(null); }) .catch((reason: Error) => setError(reason.message)), [] ); useEffect(() => { void reload(); }, [reload]); return { settings, setSettings, error, reload }; }; /** The dotted path of the first field with an error, for jumping to it. */ export const firstErrorPath = (errors: object, prefix = ''): string | null => { for (const [key, value] of Object.entries(errors)) { if (!value || typeof value !== 'object') { continue; } if ('message' in value && typeof value.message === 'string') { return `${prefix}${key}`; } const nested = firstErrorPath(value, `${prefix}${key}.`); if (nested) { return nested; } } return null; };