So I got this component:
export default function () {
const [todos, setTodos] = useState([]);
useEffect(() => {
function populateTodos () {
axios.get(`http://localhost:8000/api/all-todos`)
.then(res => setTodos(res.data))
.catch(err => console.log(err));
}
populateTodos();
}, []);
console.log(todos);
return (
<div>
...
</div>
);
}
I am using the useEffect
hook to fetch all the todos from the database, and it works fine. The problem is that I don't know how to use useEffect
to trigger a rerender anytime I make a modification to the todos array, like adding or deleting or updating. If I supply the useEffect
's dependency array with the todos
variable I get an infinite loop logging in the console.
How can I use useEffect
to trigger a rerender anytime the todos
array gets updated?