D
D
Dmitry2020-10-25 16:56:03
typescript
Dmitry, 2020-10-25 16:56:03

React.StrictMode breaking app?

The usual todo application . There is a function that, when clicked, puts a label on an completedelement from the list

const toggleHandler = (id) => {
    setTodos(prevState => {
        return prevState.map(todo => { // проблема тут
            if (todo.id === id) todo.completed = !todo.completed
            return todo
        })
    })
}

The problem is that in strict mode setTodosit is called twice, putting down first completed: trueand then completed: falseand it looks like nothing is happening.
As a solution, you can abandon the callback and update the state through spread.
But how to fix this problem using a callback with the previous state and without turning off strict mode?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
i1yas, 2020-10-25
@dmitry-l

Inside map do this

if (todo.id === id) todo.completed = !todo.completed
return todo

Indeed, what could go wrong.
Strict Mode , in particular:
Strict mode can't automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following methods:
...
setState updater functions (the first argument)
...

Here is the expression:
if (todo.id === id) todo.completed = !todo.completed
it's a side effect.
Should be:
if (todo.id === id) return { ...todo, completed: !todo.completed }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question