N
N
n1ksON2020-10-04 19:22:27
React
n1ksON, 2020-10-04 19:22:27

What's wrong with the state change function?

Hello!
There are three objects corresponding to three buttons. When you click on any of them, the state should be updated. There are 3 states in total.
But the changeState function works through one place, more precisely, it doesn’t work properly. I wanted the function to take the state of the button that I clicked on and increase it by 1 (if it is 2, then reset it to zero).
The function only works once, then the error is:Cannot read property 'map' of undefined

const [states, setStates] = useState([
    { id: 1, state: 0 },
    { id: 2, state: 0 },
    { id: 3, state: 0 }
  ])

const changeState = ({ id }) => {
    setStates(prev => {
      prev.map(data => {
        if (data.id === Number(id)) {
          (data.state === 2) ? data.state = 0 : ++data.state
        }
      })
    })
  }

Tell me what's wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
i1yas, 2020-10-04
@n1ksON

setStates(prev => {
      prev.map(data => {
        if (data.id === Number(id)) {
          (data.state === 2) ? data.state = 0 : ++data.state
        }
      })
    })

The function passed to setStates does not return anything, it just makes a map and forgets the result, respectively, undefined is placed in the state, which does not have a .map method, which is what the error says
. You need to add:
return prev.map...
In map you make a similar mistake, plus for some reason you mutate the data .
if (data.id === Number(id)) {
          (data.state === 2) ? data.state = 0 : ++data.state
        }

Everything that does not fall under this condition will become undefined, i.e. you will have an array of such a structure. [,,,{},]
Inside the map, you need to rewrite it like this:
data => {
        if (data.id === Number(id)) {
          return (data.state === 2) ? {...data, state: 0} : {...data, state: data.state + 1}          
        }
        return data
}

Look at the syntax of arrow functions if you don't know.
Without curly brackets () => expression
With curly brackets () => { return expression }
Returning an object() => ({ someObjectField: ... })

L
Loli E1ON, 2020-10-04
@E1ON

callback in setStates must return the new state

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question