ReactJS component won't update after first API call
The second parameter of useEffect
(the Array
) has an important role: the items in that array trigger the useEffect
to re-run.
Some cases:
-
useEffect(() => {}, [])
: runs once, after the component is mounted -
useEffect(() => {}, [var1, var2,..., varn])
: runs whenvar1
orvar2
orvarn
is updated -
useEffect(() => {})
: runs on every completed re-render (default behavior)
More on useEffect
: useEffect hook
So, your code works as expected:
useEffect(() => {
client.get('items').then((result) => {
setItems(result.data);
});
}, []); // -> runs once, when component is mounted
useEffect(() => {
client.get('items').then((result) => {
setItems(result.data);
});
}, [item]); // -> runs when the variable named item changes
you need to organize your code in such a way, that this useEffect
hook can run on the update of the variable whose change you want to watch.