1

I'm having trouble with the code given under. I want to add a new task object to my array, so firstly i try to find the max id in the tasks array and i give the maxId+1 to my new object as id. Then i try to append my new Task object at the end, but data is not updated after i call setTasks.

Any helps would be appreciated

  const[tasks,setTasks] = useState([
    {
        id:1,
        text:"Task1",
        day:"21.06.2021",
        reminder : true
    },
    {
        id:2,
        text:"Task2",
        day:"21.06.2021",
        reminder : false
    },
    {
        id:3,
        text:"Task3",
        day:"22.06.2021",
        reminder : true
    }

  ])

  const addTask = (task) => {
    var id = 0
    for (const t of tasks){
      if (t.id > id){
        id = t.id+1
      }
    }
    console.log("Before",tasks)
    const newTask = {id, ...task}
    setTasks([...tasks, newTask])
    console.log("After",tasks)
  }
Kerim Siper
  • 87
  • 10
  • 1
    Hi! That code to update it looks just fine, the problem must be elsewhere. Please update your question with a [mcve] demonstrating the problem, ideally a **runnable** one using Stack Snippets (the `[<>]` toolbar button). Stack Snippets support React, including JSX; [here's how to do one](http://meta.stackoverflow.com/questions/338537/). – T.J. Crowder Jun 21 '21 at 14:25
  • The code seems good. – Ish Jun 21 '21 at 14:26
  • Can you include a codesandbox link? The tasks state isn't going to have its updated value until the next render. – Chris Farmer Jun 21 '21 at 14:27
  • I think you need to read how the state works in general, you won't be able to observe the updated state just one line after setting it. – ilkerkaran Jun 21 '21 at 14:28
  • This will work, but as mentioned by @ilkerkaran, you won't see the change in your `console.log` as setting React state happens asynchronously and will not be complete before the `log` runs. – DBS Jun 21 '21 at 14:31

1 Answers1

1

That is the normal behaviour in React. When setTasks is triggered inside the handler, tasks yet has the old value, even after setTasks is triggered. But, when component is refreshed, if you use an useEffect, you see, now the value is refreshed. Bellow a simple example with update array and console.log print the state:

https://codesandbox.io/s/lively-fast-q2yxn?file=/src/App.js

import React, { useEffect, useState } from "react";

export default function App() {
  /**
   * component state:
   */
  const [array, setArray] = useState([]);
  const [count, setCount] = useState(0);
  /**
   * handler:
   */
  const addItemToArray = () => {
    setArray((a) => [...a, count]);
    setCount((c) => c + 1);
    console.log("inside handler: ", array);
  };
  /**
   * useEffect:
   */
  useEffect(() => {
    console.log("inside useEffect: ", array);
  }, [array]);

  return (
    <div className="App">
      <button onClick={addItemToArray}>Add Item to Array</button>
    </div>
  );
}
Cássio Lacerda
  • 1,554
  • 1
  • 12
  • 14
  • 1
    If this is the answer, then it's an obvious duplicate of [this often-asked question](https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state). – T.J. Crowder Jun 21 '21 at 14:58