Answers for "can't perform a react state update on an unmounted component + setloading"

1

react warning can't perform a react state update on an unmounted component

componentWillUnmount() {
    // fix Warning: Can't perform a React state update on an unmounted component
    this.setState = (state,callback)=>{
        return;
    };
}
Posted by: Guest on October-15-2020
0

Can't perform a React state update on an unmounted component

export default function MyComponent() {
    const [loading, setLoading] = useState(false);
    const [someData, setSomeData] = useState({});
    let componentMounted = true; // (3) component is mounted
    // ...
    useEffect(() => {
        setLoading(true);
        someResponse = await doVeryLongRequest(); // it needs some time
        // When request is finished:
        if (componentMounted){ // (5) is component still mounted?
            setSomeData(someResponse.data); // (1) write data to state
            setLoading(false); // (2) write some value to state
        }
        return () => { // This code runs when component is unmounted
            componentMounted = false; // (4) set it to false if we leave the page
        }
    }, []);

    return (
        <div className={loading ? "loading" : ""}>
            {someData}
            <a href="SOME_LOCAL_LINK">Go away from here!</a>
        </div>
    );
}
Posted by: Guest on July-02-2021

Code answers related to "can't perform a react state update on an unmounted component + setloading"

Code answers related to "TypeScript"

Browse Popular Code Answers by Language