tkl
tkl

Reputation: 1

React Hooks State is only updating once Type:error not a function

I have attached screen shots of my code and the error I am getting.

Here is the overview; I am new to using hooks and am trying to get my to-do-list checkboxes to save in state to be equal to true when checked and false when unchecked. The first click on a checkbox works and updates in state, but every subsequent attempt to check or uncheck a box results in a TypeError: prevState.map is not a function (see image 2).

1 image 1 : checking the box and it works fine and updates state.

2 image 2: Attempted to click on a checkbox again resulting in the map error.

3 image 3: Main app code.

4 image 4: To-Do-list component code.

I am confused as to why my code will not work and am asking for help in fixing this error.

Thank you.

Upvotes: 0

Views: 36

Answers (1)

Rodrigo Amaral
Rodrigo Amaral

Reputation: 1382

When you pass a function to setList, you always have an up-to-date value of your state as the first parameter. After the first time you use it, you are returning an object { updatedTodos }. You should return the array updatedTodos. You don't even need to declare a variable in this case, just use the short arrow return:

setList(prevState => prevState.map(todo => {
    if (todo.id === id) {
        return {...todo, completed: !todo.completed}
    }
    return todo
}))

Upvotes: 1

Related Questions