1

I'm learning react.js and doing a little todo list. Now i'm implementing the part where I store in localStorage the todo list. My problem is that when I enter a text and add it to my todoList, I store it in localStorage but I don't have the current value yet in the list.

This is my code:

const [todoText, setTodoText] = useState('')
const [todoList, setTodoList] = useState([])

const addTodo = function(){
        if (todoText === "") { return }

        setTodoList([...todoList, todoText])
        setTodoText("")
        store.update("todoList", todoList)
    }

const update = function(key, value) {
    localStorage.setItem(key, value)
}

<form onSubmit={(e) => {e.preventDefault(); addTodo()}}>
   <input placeholder="What needs to be done?" 
   value={todoText} onChange={(e) => {setTodoText(e.target.value)}}></input>
</form>

the todo that I enter is stored in localStorage the second time I enter another todo

sebba23
  • 544
  • 7
  • 24
  • 1
    Setting state is async. Do `const newList = [...todoList, todoText];`, then pass `newList` to both setTodoList and store.update –  May 11 '20 at 15:29
  • 1
    Does this answer your question? [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) –  May 11 '20 at 15:29

1 Answers1

1

When you call setTodoList, the variable todoList isn't updated until next render.

There is a lot of ways to solve this, but one way is

let newTodo = [...todoList, todoText]

setTodoList(newTodo )
setTodoText("")
store.update("todoList", newTodo)

You can also use the previous state

setTodoList(prev => {
    let newTodo = [...prev, todoText]
    store.update("todoList", newTodo)
    return newTodo
})
setTodoText("")
Vencovsky
  • 28,550
  • 17
  • 109
  • 176