Mike Phelps
Mike Phelps

Reputation: 21

react useEffect with Dependency Array still looping

I am trying to wrap my head around the useEffect hook. To my knowledge, if a dependency array is included in the hook, the effect will only run if that particular piece of state changes, however I cannot get it to work. Every time I add a dependency array, it loops infinately.


    useEffect(() => {

      axiosWithAuth()
        .get(`/api/parent/children/${id}`)
        .then(response => {
          // console.log('API response: ', response);
          // console.log('childs data: ',response.data);
          setData(response.data)
          // console.log('new data: ', data);
        });
      .catch(err => console.log(err));
    }, [data]);

if I pull data out of the dependency array, it works fine, no looping. The premise is, if a user clicks on a child's name, it brings up the data for that child (this is a chore-tracker that I'm working on) so I would ASSUME (and I could be wrong) that...

I think I may have answered this on my own, but I would like some confirmation:

I need to set a slice of state for the child, and if THAT state changes, then the effect runs.. so.. something like this..


    const {data, setData} = useState([]);
    const {child, setChild} = useState('');

      useEffect(() => {

        axiosWithAuth()
          .get(`/api/parent/children/${id}`)
          .then(response => {
            // console.log('child list response: ', response);
            // console.log('childs data length',response.data.length);
            // console.log('childs data',response.data);
            setData(response.data)

            // console.log('new data: ', data);
          });
          .catch(err => console.log(err));
      }, [child]);

Is my thinking right in that I need to do it that way instead of the way I had it?

Upvotes: 0

Views: 119

Answers (1)

shahabvshahabi
shahabvshahabi

Reputation: 955

Yes you are doing fine . But the better answer for these kind of problem is :

useEffect(() => {
        axiosWithAuth()
          .get(`/api/parent/children/${id}`)
          .then(response => {
            // console.log('child list response: ', response);
            // console.log('childs data length',response.data.length);
            // console.log('childs data',response.data);
            setData(response.data)

            // console.log('new data: ', data);
          });
          .catch(err => console.log(err));
} , []})

When you pass an empty array to useEffect it only runs once

Upvotes: 1

Related Questions