useEffect continuously fires GET requests

Viewed 199

I'm learning React and trying to make a small project by myself for the first time, but I'm having trouble with useEffect.

I'm trying to autofill a form with information from my backend. I can get it to autofill, but it continuously sends GET requests. This is what I have:

  useEffect(() => {
      axios
        .get('/admin/edit-product' + location.search)
        .then((res) => {
          const updatedControls = {
            ...controlsState,
            title: {
              ...controlsState.title,
              value: res.data.title,
            },
            image: {
              ...controlsState.image,
              value: res.data.image,
            },
            price: {
              ...controlsState.price,
              value: res.data.price,
            },
            description: {
              ...controlsState.description,
              value: res.data.description,
            },
          };
          setControlsState(updatedControls);
        })
        .catch((err) => console.error(err));
  }, [controlsState, location.search]);

I thought that the dependency array was supposed to stop it from running continuously, but I guess I'm missing something else.

Not sure if it's needed, but this is what my original state looks like:

  const [controlsState, setControlsState] = useState({
    title: {
      elementType: 'input',
      elementConfig: {
        type: 'text',
      },
      label: 'Product Title: ',
      value: '',
    },
    image: {
      elementType: 'input',
      elementConfig: {
        type: 'url',
      },
      label: 'Image URL: ',
      value: '',
    },
    price: {
      elementType: 'input',
      elementConfig: {
        type: 'number',
      },
      label: 'Price: ',
      value: '',
    },
    description: {
      elementType: 'textarea',
      elementConfig: {
        name: 'description',
        htmlFor: 'description',
      },
      label: 'Description: ',
      value: '',
    },
  });

and location is from react-router-dom useLocation

1 Answers

You have given controlsState as a dependency for useEffect. But inside your useEffect you are using setControlsState which changes the value of controlsState. And since you have given controlsState as a dependency, useEffect will occur everytime any of its dependency changes. Hence it is repeatedly happening

If you want useEffect to run only once, give [] as second parameter:

useEffect(() => { 
    ...your code... 
}, [])
Related