Skip to content

7. useMonitoredFetch

Naveen Mathew edited this page Mar 6, 2024 · 2 revisions

useMonitoredFetch

useMonitoredFetch wraps is a hook provided for convenience which uses makeMonitoredFetch underneath to keep track of fetch status and whether there are any inflight network requests.

Result

useMonitoredFetch returns the following:

  • isFetching: true if there are any inflight network requests and false otherwise, it is a reactive value

  • monitor: monitor wraps a fetch function to monitor its fetch status

    • Note that in React, the call to monitor should be placed within a memo as each fetch function is assigned a unique id
    const { isFetching, monitor } = useMonitoredFetch();
    
    const getAll = React.useMemo(() => monitor(() => fetch(API)), []);
    const postSomething = React.useMemo(
      () => monitor(() => fetch(API, { method: "POST" })),
      []
    );
    const putSomething = React.useMemo(
      () => monitor(() => fetch(API, { method: "PUT" })),
      []
    );

    Now if any of the fetch functions getAll, postSomething or putSomething are inflight then isFetching will be true