Hooks with Infinite Loop

Asked

Viewed 211 times

0

My Hooks is in infinite loop, charging all the time, what I intend to do is to search the api when start the screen and when there are changes of status of the tasks reload, but it keeps reloading all the time even without changes in the state

const [tarefas, setTarefas] = useState([]);
const [isLoading, setIsLoading] = useState(false);


  useEffect(() => {
setIsLoading(true)
    async function loadTarefas() {
      const response = await api.get('/tarefas');

      setTarefas(response.data);
    }

    loadTarefas();
setIsLoading(false)
  }, [tarefas]);
  • Could put the complete code of your component?

  • Other than that, as I understand it, you never change the status of the loading after it becomes true. It wouldn’t be the case to add setIsLoading(false) after the setTarefas(response.data);?

  • setIsLoading(false) ta being passed there after calling function

  • That one of yours useEffect doesn’t make much sense, because whenever task is changed, you will try to access your api. Ideally only charge when the component is mounted, no?

  • I use the useEffect for initial loading of tasks on the screen, and step the tasks parameter so that every time a task is added it recharges again.

  • To add a new task I use another screen that adds the task and the intention to use the useEffect to upgrade would be for when I close the task add screen on the task start screen it already load again by pulling the new added task

  • 1

    But do you agree that if you load tasks every time they are changed and the loading is a change of tasks, it will generate an infinite loop? The ideal would be for you to load the tasks the first time and change them without reloading them. In case you need to reload the tasks when there is a change, the ideal would be to have a status for tasks locally and, when that state is changed in a "definitive" way, you would update task with it and reload.

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.