Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 895
Omar Kamel Mostafa Avatar asked Dec 06 '25 14:12

Omar Kamel Mostafa


1 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]); 
}
like image 62
dave Avatar answered Dec 08 '25 06:12

dave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!