import { useCallback, useEffect, useState } from 'react'; import { api } from '../config'; const API_URL = `${api.root}/mailpoet/v1/automation`; export const request = ( path: string, init?: RequestInit, ): ReturnType => fetch(`${API_URL}/${path}`, init); type Error = { response?: Response; data?: T; }; type State = { data?: T; loading: boolean; error?: Error; }; type Result = [(init?: RequestInit) => Promise, State]; // eslint-disable-next-line @typescript-eslint/no-explicit-any type Data = Record; export const useMutation = ( path: string, config?: RequestInit, ): Result => { const [state, setState] = useState>({ data: undefined, loading: false, error: undefined, }); const mutation = useCallback( async (init?: RequestInit) => { setState((prevState) => ({ ...prevState, loading: true })); const response = await request(path, { ...config, ...init, headers: { 'content-type': 'application/json', ...(init?.headers ?? {}), 'x-wp-nonce': api.nonce, }, }); try { const data = await response.json(); const error = response.ok ? null : { ...response, data }; setState((prevState) => ({ ...prevState, data, error })); } catch (_) { const error = { response }; setState((prevState) => ({ ...prevState, error })); } finally { setState((prevState) => ({ ...prevState, loading: false })); } }, [config, path], ); return [mutation, state]; }; export const useQuery = ( path: string, init?: RequestInit, ): State => { const [mutation, result] = useMutation(path, init); useEffect( () => { void mutation(); }, [] /* eslint-disable-line react-hooks/exhaustive-deps -- request only on initial load */, ); return result; };