DEV Community

Jason Cruz
Jason Cruz

Posted on

MAKING API CALLS without React Hooks

MAKING API CALLS

Without React Hooks


Something I wrote for my reference when not using react hooks.

// Making API calls
const [user, setUser] = useState();
const [error, setError] = useState();
useEffect(() => {
fetchUserData(userId)
.then(res => setUser(res.data.user))
.catch(err => setError(err.response.message));
});

// Manipulating the DOM
const [count, setCount] = useState();
useEffect(() => {
document.title =
Count is: ${count};
});

useEffect(() => {
console.log("The component has mounted.");
}, []);


Top comments (1)

Collapse
 
jwhenry3 profile image
Justin Henry

you will want to add a flag that is changed upon unmount to avoid setting the state after a component has unmounted

useEffect(() => {
    let isMounted = true;
    fetchUserData(userId)
        .then((res) => isMounted && setUser(res.data.user))
        .catch((err) => isMounted && setError(err.response.message));
    return () => isMounted = false;
}, []);
Enter fullscreen mode Exit fullscreen mode