Search code examples
reactjsaxiosreact-hooksreact-context

useEffect not triggering in ContextProvider


I am using useEffect hook inside an Context Provider called DataProvider. In the useEffect hook I am sending a request to a endpoint using axios. But the thing is, the useEffect hook not triggering. What Should I do in this situation. Can anyone help me on this issue.

Context Provider code:

export const DataProvider = ({ children }) => {
    const [data, setData] = useState({});

    useEffect(() => {
        const options = {
            method: "GET",
            url: "https://corona-virus-world-and-india-data.p.rapidapi.com/api_india",
            headers: {
                "x-rapidapi-key": API_KEY,
                "x-rapidapi-host": API_HOST
            }
        };

        axios
            .request(options)
            .then(function(response) {
        console.log(response.data);
        setData(response.data);
            })
            .catch(function(error) {
                console.error(error);
            });
    }, []);

    if(data) {
        return (
            <DataContext.Provider value={[data, setData]}>
                {children}
            </DataContext.Provider>
        );
    } else {
        console.log("error");
    }
};

And below is the error image enter image description here

Please help me to fix this error 🙏.


Solution

  • React renders first and only after first render it executes the useEffect. You're trying to access a property that is not yet initialized.

    Just handle your data and render conditionally with if or do this in your card Container:

    <Cardcontainer caseNumber={numberWithCommas(data?.total_values?.deaths)}/>
    

    Make sure numberWithCommas knows how to handle an undefined parameter.