reactjsasynchronousasync-awaitreact-hooksreact-async

React-Async call run later with GET request on useFetch


I am trying to run a fetch request later by using useFetch from the React-Async library. I would like to run it in an effect hook.

import React, {useEffect} from 'react';
import { useFetch } from "react-async"

const Example = (props) => {
  const headers = { Accept: "application/json" }
  const { data, error, isPending, run } = useFetch("http://www.mocky.io/v2/5eac28e4330000a215dfe24d",{ method: "POST", headers });

  useEffect(() => {
    // token = await retrieveToken;
    run(init => ({
      ...init,
      headers: {
        ...init.headers,
        Authentication: "thetoken",
      },
    }))
  },[]);


  if (isPending) return <div>Loading</div>
  if (error) return <div>`Something went wrong: ${error.message}`</div>
  if (data)
    return (
      <div>
        {JSON.stringify(data)}
      </div>
    );
  else {
    return <div>Loading</div>
  }
}
export default Example;

The fetch call is run right away and not in the effect. When I change the method to POST, the fetch call is made from the effect as expected.

How can I make it work for the GET request?


Solution

  • react-async useFetch takes in the options object as the third param. This options object takes in a defer param which defers the execution if set to true. By default it is determined by the request method

    AS per the documentation

    defer Enables the use of deferFn if true, or enables the use of promiseFn if false. By default this is automatically chosen based on the request method (deferFn for POST / PUT / PATCH / DELETE, promiseFn otherwise).

    Use your useFetch method like

    const { data, error, isPending, run } = useFetch("http://www.mocky.io/v2/5eac28e4330000a215dfe24d",
                                            { method: "GET", headers }, 
                                            {defer: true}
                                           );