'Check updated state of GET request in useEffect Hook

When I create an item and click save, I would like when I return to the page it automatically updates with what I just created. So that my useEffect detects the changes that have just arrived at the level of the GET request.

But I tried everything, I tried to put the variable garden in the array of useEffect but it makes an infinite loop of GET request, I also tried to put setGarden it does not make an infinite loop but it does not update automatically, I have to reload the page...

Here is the code :

const [garden, setGarden] = useState([]);
const [plot, setPlot] = useState([]);
const [loading, setLoading] = useState(false);
const navigation = useNavigation();

  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) {
        navigation.navigate('LogScreen');
        setGarden(response.data);
        setLoading(false);
        try {
          const plotResponse = await axios.get(
            `http://127.0.0.1/api/plots?garden=${response.data[0].id}`,
            {
              headers: {
                Authorization: `Token ${parsedUserData.token}`,
              },
            },
          );
          if (plotResponse.status === 200) {
            setPlot(plotResponse.data);
          }
        } catch (e) {
          alert(e);
        }
      }
    } catch (e) {
      console.log('Erreur ' + e);
      setLoading(false);
    }
  };

  useEffect(() => {
    gardenData();
  }, []);

Thanks for the help !



Solution 1:[1]

You can just simply use an indication to make sure the gardenData function in ran once. Either you can initialize one of your state or even you can use a complete new state This is only run the code once.

    const [garden, setGarden] = useState([]);
    const [plot, setPlot] = useState([]);
    const [loading, setLoading] = useState(false);
    const [FirstRun, setFirstRun] = useState(true);
    const navigation = useNavigation();

      const gardenData = async () => {
        if(!FirstRun) return;
        setFirstRun(false);
        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) {
            navigation.navigate('LogScreen');
            setGarden(response.data);
            setLoading(false);
            try {
              const plotResponse = await axios.get(
                `http://127.0.0.1/api/plots?garden=${response.data[0].id}`,
                {
                  headers: {
                    Authorization: `Token ${parsedUserData.token}`,
                  },
                },
              );
              if (plotResponse.status === 200) {
                setPlot(plotResponse.data);
              }
            } catch (e) {
              alert(e);
            }
          }
        } catch (e) {
          console.log('Erreur ' + e);
          setLoading(false);
        }
      };

      useEffect(() => {
if(FirstRun)
{
        gardenData();
}
// your code here

}, [garden]);

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 Immortal