xxxxxxxxxx
// Using hooks
const [array, setArray] = useState([1, 2, 3])
setArray(prevArray => [prevArray, 4]); // -> [1, 2, 3, 4]
xxxxxxxxxx
this.setState(prevState => ({
myArray: [prevState.myArray, "new value"]
}))
xxxxxxxxxx
// Save search term state to React Hooks with spread operator and wrapper function
// Using .concat(), no wrapper function (not recommended)
setSearches(searches.concat(query))
// Using .concat(), wrapper function (recommended)
setSearches(searches => searches.concat(query))
// Spread operator, no wrapper function (not recommended)
setSearches([searches, query])
// Spread operator, wrapper function (recommended)
setSearches(searches => [searches, query])
xxxxxxxxxx
this.setState({ myArray: [this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [this.state.myArray, [1,2,3] ] }) //another array
xxxxxxxxxx
this.setState(prevState => ({
myArray: ["new value", prevState.myArray]
}))
xxxxxxxxxx
this.setState(prevState => ({
arrayvar: [prevState.arrayvar, newelement]
}))
xxxxxxxxxx
this.setState(prevState => ({
myArray: [prevState.myArray, {"name": "object"}]
}))
xxxxxxxxxx
this.setState(previousState => ({
myArray: [previousState.myArray, 'new value']
}));
xxxxxxxxxx
this.setState(prevState => ({
myArray: [ {"name": "object"}, prevState.myArray]
}))
xxxxxxxxxx
var joined = this.state.myArray.concat('new value');
this.setState({ myArray: joined })