score:2

Accepted answer
 export function useAPI<Q, R>(api: (query: Q) => Promise<R | never>) {
  const [state, setState] = useState<{ loading?: true, pending?: true, error?: string, errorCode?: number, result?: R }>({ pending: true });

  async function run(query: Q) {
    if(state.loading) return;
    setState({ loading: true });

    try {
        const result = await api(query);
        setState({ result });
    } catch(error) {
        if(error instanceof HTTPError) {
            console.error(`API Error: ${error.path}`, error);
            setState({ error: error.message, errorCode: error.code });
        } else {
            setState({ error: error.message, errorCode: NaN });
        }
    }
  }

  function reset() {
     setState({ pending: true });
  }

  return [state, run, reset] as const;

}

Related Query

More Query from same tag