0

I have this useFetch custom hook

export function useFetch(initialState, url, header) {
  const [value, setValue] = useState(initialState);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const FetchURL = async () => {
      try {
        const res = await fetch(url, {
          headers: header,
        });
        if (!res.ok)
          throw new Error("There was and error getting data from API");
        const data = await res.json();
        setValue(data.record);
      } catch (error) {
        setError(error.message);
        console.error(error);
      } finally {
        setIsLoading(false);
      }
    };
    FetchURL();
  }, [header, url]);
  return [error, isLoading, value, setError];
}

and i'm using it like this

  const [error, isLoading, tabsArr, setError] = useFetch([], url, header);
  return (
      {error && <ErrorMessage onClick={()=> setError(false)}/> }
)

I want the code to be fetched on mount and then if there is an Error i'm giving an error message with a button, I want it to try to fetch again on click of the button.

1 Answers1

0

Instead of passing setError, you could try making the FetchURL a callback function and passing that function outside of the hook. Then you can call that function on clicking the button to retry the fetch.

export function useFetch(initialState, url, header) {
    const [value, setValue] = useState(initialState);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);
    const FetchURL = useCallback(async () => {
        setError(null);
        try {
            const res = await fetch(url, {
                headers: header
            });
            if (!res.ok) throw new Error('There was and error getting data from API');
            const data = await res.json();
            setValue(data.record);
        } catch (error) {
            setError(error.message);
            console.error(error);
        } finally {
            setIsLoading(false);
        }
    }, [header, url]);

    useEffect(() => {
        FetchURL();
    }, [FetchURL]);
    return [error, isLoading, value, FetchURL];
}
const [error, isLoading, tabsArr, retry] = useFetch([], url, header);
return (
  {error && <ErrorMessage onClick={retry}/> }
);
Hao Wu
  • 17,573
  • 6
  • 28
  • 60