0

I get data from backend and set to my state in componentdidmount but value not set after log state

  const [tasks, setTasks] = useState([]);

  const getTasks = async () => {
    const getTodoInformation = {
      email: localStorage.getItem("tokenEmail"),
    };
    if (getTodoInformation.email) {
      const response = await axios.post(
        "http://localhost:9000/api/todo/get",
        getTodoInformation
      );
      setTasks(response.data.data);
    }
  };

  useEffect(() => {
    getTasks();
    console.log(tasks);
  }, []);

My tasks is empty when i log it

  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – JBallin Aug 04 '22 at 06:04

4 Answers4

1

So the title and the question itself are actually two questions.

React Hook useEffect has a missing dependency: 'tasks'. Either includes it or remove the dependency array

That's because you include a state (i.e. tasks) in the useEffect hook. And React is basically asking you, "Do you mean run console.log(tasks) every time tasks is updated?". Because what you are doing is run the useEffect hook once and only once.

And for your "actual" question

value not set after log state

In short, states are set in async manner in React. That means tasks is not necessary immediately updated right after you call setTasks. See @JBallin comment for details.

Matthew Kwong
  • 2,548
  • 2
  • 11
  • 22
1
 const [tasks, setTasks] = useState([]);     
   useEffect(() => {
   setTimeout(async () => {
  const getTodoInformation = {
      email: localStorage.getItem("tokenEmail"),
    };
    if (getTodoInformation.email) {
  const response = await axios.post(
    "http://localhost:9000/api/todo/get",
    getTodoInformation
  );
  setTasks(response.data.data);
}
  }, 1000);
console.log(tasks);
 }, []);
0

The main problem is that useEffect -> is a sync method, getTasks() is asynchronous, and useEffect only works once when your component mounts. Shortly speaking, you got your data from the backend after useEffect worked.

For example, if you will add one more useEffect

useEffect(() => {
  console.log(tasks);
}, [tasks]);

You will see log, after your data will have changed.

Yuri
  • 34
  • 7
0

You can use self-calling async function inside useEffect as shown here:

const [tasks, setTasks] = useState([]);

const getTasks = async () => {
  const getTodoInformation = {
    email: localStorage.getItem("tokenEmail"),
  };

  if (getTodoInformation.email) {
    const response = await axios.post(
      "http://localhost:9000/api/todo/get",
      getTodoInformation
    );

    return response.data.data;
  }
};

useEffect(() => {
  (async () => {
    const tasks = await getTasks();

    setTasks(tasks);
  })();

  console.log(tasks);
}, [tasks]);