简体   繁体   中英

I want to update my state values as soon as I am dispatching the actions

Hi I am trying to get my state values as soon as I am updating it. But cannot achieve this

My initial state looks like this:

filterData: {year: "2021", programId: "America"}

I have a handleDelete function that is deleting the values from the object.

const handleDeleteChips = (e, value) => {
    e.preventDefault();
    if (chipData[0].year == value) {
      dispatch(updateFilterYear(''));      
    } else {
      dispatch(updateFilterProgramId(''));      
    }
}

I want as soon as I am disptaching, the state values should be changed to this:

filterData: {year: "", programId: "America"}

So, I have a idea that in react this doesn't happens just after setting the state. The component has to re-render so for this i have implemented useEffect. In useEffect, to capture the value change and I have done this :

useEffect(()=>{
  dispatch(updateFilterYear(filterData.year));
}, [filterData.year])

But it is still not working as expected. I am able to update the state values but not immediately. So is my code inside useEffect correct?

 const handleDeleteChips = (e, value) => { e.preventDefault(); if (chipData[0].year == value) { dispatch(updateFilterYear('')); setFilterData: {...filterData,year: ""} } else { dispatch(updateFilterProgramId('')); setFilterData: {...filterData, programId:""} } }

Try this function ... Hope this solves your issue .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM