I've read some good practices in reactjs using useEffect. I have a situation which I separated my function to fetch the data and call it on the useEffect hook. How could I make some cleanup functions in this situation. ?
I've seen some useEffect cleanup like these:
useEffect(() => {
let isActive = true;
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => response.json())
.then((data) => {
if (isActive) {
setTodo(data);
}
})
.catch((error) => console.log(error.message));
return () => {
isActive = false;
};
}, []);
From the example above, the fetch function is inside with useEffect, now how can I perform some cleanup if something like this situation:
const getTodos = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const todos = await response.json();
if(todos) {
setTodos(todos);
}
}catch(e) {
console.log(e);
}
}
useEffect(() => {
let mountedTodos = true;
getTodos();
return () => {
mountedTodos = false;
}
},[])
isActivein global scope or define thegetTodosinside the useEffect.