Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
Infinite loop with a useEffect in React native

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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();
  }, []);
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!