I want to update my object when the user clicks on the button, append to array element id. But when I adding data to array it overrides all object without saving previous data. I passed prevState callback but it doesn't work.
const [filteredObject, setFilter] = useState({destinations:[],season:[],difficulty:[],price:'',is_exclusive:'',duration:''});
if (e.currentTarget.name==='destinations') {
setFilter(prevState=>({...prevState, destinations:[ ...prevState.destinations, e.currentTarget.id]}))
}
When you do destinations:[ e.currentTarget.id]
, you are actually overriding the existing array.
You need to do this,
setFilter( prevState => ({
...prevState,
destinations:[ ...prevState.destinations, e.currentTarget.id ]
}))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.