Search code examples
reactjsreact-hooksinfinite-loop

Making a request to back end and setting state with results creates infinite loop - react hooks useEffect


When a user goes to the edit page they will have the ID for the task they are editing. I need to make a request to the backend and set the state with the tasks text once.

What I have working:

let { id } = useParams();
const [task, setTask] = useState({ text: "", id: id });

useEffect(() => {
  axios
    .get(`/find/${id}`)
    .then((res) => {
      setTask({ ...task, text: res.data.text });
    })
    .catch((err) => console.log(err));
  // eslint-disable-next-line
  }, [])

If I remove the // eslint-disable-next-line I get an error telling me to add task and id as dependency, but when I do I get stuck in an infinite loop.

Is there a way I can make a request to the backend and set state once without having to hide eslint errors.


Solution

  • The reason the loop is infinite is because when you call setTask with the spread parameter, you are using the task from the useState.

    To prevent this, call setTask(task => ({ ...task, text: res.data.text })); inside the useEffect so that it uses the current task inside the scope to calculate the new task state. Then you will be able to have [task, id] as the hook dependency.