'Infinite loop with a useEffect in React native [duplicate]
I have a problem, on the two functions below, when I check the debug of my request, there is an infinite loop of my GET request and I don't understand why my useEffect is re-triggering each time.
Here is my code :
const gardenData = async () => {
setLoading(true);
const user = await AsyncStorage.getItem('user');
const parsedUserData = JSON.parse(user);
try {
const response = await axios.get(
`http://127.0.0.1/api/garden?user=${parsedUserData.user.id}`,
{
headers: {
Authorization: `Token ${parsedUserData.token}`,
},
},
);
if (response.status === 200) {
setGarden(response.data);
setLoading(false);
}
} catch (e) {
console.log('Erreur ' + e);
setLoading(false);
}
};
const getPlotData = async () => {
const user = await AsyncStorage.getItem('user');
const parsedUserData = JSON.parse(user);
const id = garden.map(g => g.id);
alert(id);
try {
const response = await axios.get(
`http://127.0.0.1/api/plots?garden=${id}`,
{
headers: {
Authorization: `Token ${parsedUserData.token}`,
},
},
);
if (response.status === 200) {
setPlot(response.data);
}
} catch (e) {
alert(e);
}
};
useEffect(() => {
gardenData();
getPlotData();
}, [setGarden, setPlot]);
Thanks for the help provided
Solution 1:[1]
If setGarden and setPlot are the state, I think you are watching on two vars who changes in the functions that you call. Just put empty array in the useEffect's watcher
Solution 2:[2]
The array you pass in to the second parameter for useEffect should contain the state variables to watch that when changed will cause the useEffect to run again, because you are passing it [setGarden, setPlot], when you are using these methods to setPlot(response.data) then useEffect runs again, causing an infinite loop
If you want this to run just once pass useEffect an empty array like this:
useEffect(() => {
gardenData();
getPlotData();
}, []);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sandex |
Solution 2 |