Justin Oberle
Justin Oberle

Reputation: 570

React.js useEffect with nested async functions

I have the common warning displaying upon loading of my web app but never again...

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

EDIT**** It is caused by this chunk of code. I have narrowed it down to one function. It blows up when I try to setMoisture state. I am not sure why.

function getData (){
    Axios.get("http://localhost:3001/api/get-value").then((response) => {
        const recievedData = response.data;
        const dataValue = recievedData.map((val) => {
            return [val.value]
        })
        if (loading === true){
            setLoading(false);
        }
        return parseInt(dataValue);
    }).then((resp)=>setMoisture(resp))
}

React.useEffect(() => {
    if (moisture === "initialState"){
        getData();
    }
}, []); 

Upvotes: 0

Views: 1036

Answers (1)

Andy Refuerzo
Andy Refuerzo

Reputation: 3332

Posting the answer here (based from the comments) for completeness.

Basically, use local variables and cleanup function towards the end of useEffect(). Using this as reference:

Similar situation here

Upvotes: 1

Related Questions