arga wirawan
arga wirawan

Reputation: 237

How to push new value to array state in react

Hey guys help me to done with this, I have an state like this :

this.state = {arr:[1,2,3]}

How to push a new value to that array of state, for example I want to push this value : addArr = [4,5,6]

Upvotes: 0

Views: 75

Answers (3)

Luhaib-j
Luhaib-j

Reputation: 99

using the useState() this should always work:

var [firstArray, setFirstArray] = useState([1, 2, 3]);
var secondArray = [4, 5, 6]
const fun = () => {
    setFirstArray((e) => [...e, ...secondArray])
}
fun()

as e representing the old value of firstArray

Upvotes: 0

marcopiii
marcopiii

Reputation: 888

You should never edit directly the state object as this.state.arr.push(...), instead you should you should replace entirely the state with this.setState(...) being a pure function.

In this case you can

this.setState({arr: [...state.arr, addArr]})

Upvotes: 1

Brandon Dyer
Brandon Dyer

Reputation: 1386

You can accomplish this with destructuring

this.setState(
  (state) => ({
    arr: [...state.arr, x]
  })
);

Upvotes: 2

Related Questions