V
V
Vladimir Golub2019-10-03 22:55:06
React
Vladimir Golub, 2019-10-03 22:55:06

How to update a 2D array in state?

Array like:

Trying to update:

this.setState(prevState => {
            return {
                arr: {
                    ...prevState.arr,
                    [posX]: [
                        ...prevState.arr[posX],
                        [posY] = 1
                    ]
                }
            }
        })

or make it easier
const arr = [...this.state.arr];

        arr[posX][posY] = 1;

        this.setState({
            arr: arr
        })

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-10-04
@RazerVG

return {
  arr: {

If arr is an array, why are you trying to turn it into an object?
this.setState(({ arr }) => ({
  arr: arr.map((n, i) => i === posX
    ? n.map((m, j) => j === posY ? 1 : m)
    : n
  ),
}));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question