React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render

Viewed 7686
export const FetchDailyData = () => {
  try {

    const [data, setData] = useState({ numbers: [], isFetching: false });

    useEffect(() => {
        const fetchData = async () => {
            setData({ ...data, isFetching: true });
            const response = await axios.get(`${apiURL}/daily`);
            setData({
                ...data,
                numbers: response.data.slice(0, 50),
                isFetching: false
            });
        };
        fetchData();
    }, [data]); 

    console.log(`data= ${data.numbers} isFetching= ${data.isFetching}`);

  } catch (error) {
    if (error) throw error;
    console.log(error);
    setData({ ...data, isFetching: false });
  }
}

Please can anyone help me fix this issue? I tried to fetch api data but this error I cannot handle.

2 Answers

You can't wrap useEffect in anything that might cause it not to run, including try/catch. Looking at what you are doing, this is probably a better option:

export const FetchDailyData = () => {
    const [data, setData] = useState({ numbers: [] });
    const [fetching, setFetching] = useState(false);
    useEffect(() => {
        const fetchData = async () => {
            const response = await axios.get(`${apiURL}/daily`);
            setData({
                ...data,
                numbers: response.data.slice(0, 50),
            });
        }
        try {
            setFetching(true);
            fetchData();
        } catch (error) {
            console.error(error);
        } finally {
            setFetching(false);
        }
    }, [data]); 
}

Because your useEffect call is inside a try/catch, it’s possible for the effect to not run on a given render. It’s predicated on whether something throws. Hooks must run in the same order in each render—I think it has to do with how React tracks them internally—and the try/catch makes it possible for that call to get skipped.

If you’re just worried about the fetch throwing, move the try/catch inside the hook instead of the other way around.

Related