// 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])
this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array
this.setState( prevState => ({
userFavorites: [...prevState.userFavourites, {id: 3, title: 'C'}]
}));
this.setState(prevState => ({
arrayvar: [...prevState.arrayvar, newelement]
}))
const handleAdd = (todo) => {
const newTodos = [...todos];
newTodos.push(todo);
setTodos(newTodos);
}
this.setState(prevState => ({
arrayvar: [...prevState.arrayvar, newelement]
}))
To push to the beginning of the array do it this way
this.setState( prevState => ({
userFavorites: [{id: 3, title: 'C'}, ...prevState.userFavourites]
}));
var joined = this.state.myArray.concat('new value');
this.setState({ myArray: joined })