Logos DX
    Preparing search index...

    Function createFetchContext

    • Creates a React context + hook pair bound to a specific FetchEngine instance. Returns a [Provider, useHook] tuple — rename to whatever fits your domain.

      Setup:

      import { FetchEngine } from '@logosdx/fetch';
      import { createFetchContext } from '@logosdx/react';
      
      const api = new FetchEngine({ baseUrl: 'https://api.example.com' });
      
      export const [ApiFetch, useApiFetch] = createFetchContext(api);
      

      Wrap your app:

      <ApiFetch>
          <App />
      </ApiFetch>
      

      Queries — auto-fetch on mount, re-fetch when path/options change:

      Returns { data, loading, error, response, refetch, cancel }. data is the unwrapped T. response provides full FetchResponse access (status, headers). error is a FetchError with .status, .isCancelled(), .isTimeout(), etc.

      function UserList() {
      
          const { get } = useApiFetch();
      
          const { data, loading, error, refetch } = get<User[]>('/users');
      
          // Full response access for headers/status
          const { response } = get<Post, { 'x-total': string }>('/posts');
          // response?.headers['x-total'] is typed
      
          if (loading) return <Spinner />;
          if (error) return <Error message={error.message} status={error.status} />;
      
          return <ul>{data?.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
      }
      

      Mutations — fire on demand, track loading/result/error:

      Returns { data, loading, error, response, mutate, reset, cancel, called }. Starts idle (loading: false, called: false) until mutate() is called. mutate() returns Promise<T> so you can await the result.

      function CreateComment() {
      
          const { post, del } = useApiFetch();
      
          const { mutate: submit, loading: isSubmitting, data: result, error: submitErr } =
              post<Comment>('/comments');
          const { mutate: remove, loading: isRemoving, error: removeErr } =
              del<void>('/comments/123');
      
          return (
              <form onSubmit={() => submit({ text: 'Hello' })}>
                  <button disabled={isSubmitting}>
                      {isSubmitting ? 'Sending...' : 'Submit'}
                  </button>
                  {result && <p>Comment created: {result.id}</p>}
                  {submitErr && <p>Failed ({submitErr.status}): {submitErr.message}</p>}
              </form>
          );
      }
      

      Escape hatch — instance gives raw access to the FetchEngine:

      const { instance } = useApiFetch();
      // For imperative one-off requests in event handlers
      const handleExport = async () => {
          const [res, err] = await attempt(() => instance.get('/export'));
      };
      

      Rules: get, post, put, del, and patch call React hooks internally, so they follow the same rules — call them at the top level of your component, never conditionally or in loops.

      Type Parameters

      Parameters

      • instance: F

        The FetchEngine to bind to

      Returns readonly [
          (props: ProviderProps) => FunctionComponentElement<ProviderProps<F>>,
          () => {
              del: <Res = unknown, RH = InstanceResponseHeaders>(
                  path: string,
                  options?: CallConfig<H, P, InstanceState>,
              ) => FetchContextMutationResult<Res, RH>;
              get: <Res = unknown, RH = InstanceResponseHeaders>(
                  path: string,
                  options?: CallConfig<H, P, InstanceState>,
              ) => FetchContextQueryResult<Res, RH>;
              instance: F;
              patch: <Res = unknown, RH = InstanceResponseHeaders>(
                  path: string,
                  options?: CallConfig<H, P, InstanceState>,
              ) => FetchContextMutationResult<Res, RH>;
              post: <Res = unknown, RH = InstanceResponseHeaders>(
                  path: string,
                  options?: CallConfig<H, P, InstanceState>,
              ) => FetchContextMutationResult<Res, RH>;
              put: <Res = unknown, RH = InstanceResponseHeaders>(
                  path: string,
                  options?: CallConfig<H, P, InstanceState>,
              ) => FetchContextMutationResult<Res, RH>;
          },
      ]

      [Provider, useHook] tuple