'How to automatically recover the data that has just been created?

I explain my problem: I have two functions, one to create a garden and another a plot. So it's POST requests to my API but when I click submit, I have another function (which is a GET request) that retrieves the garden and the plots, this function works but I have to reload the page for them to appear: it's not added automatically. How can I do this?

I tried putting in the array of useEffect (which repeats my function to retrieve data from the Garden and the plots) the variable garden and plot or setGarden and setPlot but it doesn't work.

Here is the code of the GET Request :

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

  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);
        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]

I am assuming that the mentioned code is a part of an existing component with a return. It would be great to see where you run the POST method.

The useEffect hook gets triggered only on the mount of the component (as defined with the second argument - [])

So you need to call the gardenData function after successfully performing the POST request. After that, the data will refresh and state will take care of the rest.

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 Ji?í Petera