patternjavascriptreactCritical
Correct way to push into state array
Viewed 0 times
waycorrectintostatepusharray
Problem
I seem to be having issues pushing data into a state array.
I am trying to achieve it this way:
But I believe this is incorrect way and causes issues with mutability?
I am trying to achieve it this way:
this.setState({ myArray: this.state.myArray.push('new value') })But I believe this is incorrect way and causes issues with mutability?
Solution
Functional Components & React Hooks
Push value at the end:
Push value at the start:
const [array,setArray] = useState([]);Push value at the end:
setArray(oldArray => [...oldArray,newValue] );Push value at the start:
setArray(oldArray => [newValue,...oldArray] );Code Snippets
const [array,setArray] = useState([]);setArray(oldArray => [...oldArray,newValue] );setArray(oldArray => [newValue,...oldArray] );Context
Stack Overflow Q#37435334, score: 246
Revisions (0)
No revisions yet.