sebba23
sebba23

Reputation: 574

setItem after i setValue of my list not updated with current value

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

Upvotes: 1

Views: 51

Answers (1)

Vencovsky
Vencovsky

Reputation: 31605

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("")

Upvotes: 1

Related Questions