Home > OS >  Unable to empty the state after submit (React js state)
Unable to empty the state after submit (React js state)

Time:11-01

I am facing issue whenever I want to deselect the selected options after submit. My state is:

    const [weekdays, setWeekdays] = useState([{
    day: 'S',
    fullName: 'Sunday',
    select: false
},
{
    day: 'M',
    fullName: 'Monday',
    select: false
},
{
    day: 'T',
    fullName: 'Tuesday',
    select: false
},
{
    day: 'W',
    fullName: 'Wednesday',
    select: false
},
{
    day: 'T',
    fullName: 'Thursday',
    select: false
},
{
    day: 'F',
    fullName: 'Friday',
    select: false
},
{
    day: 'S',
    fullName: 'Saturday',
    select: false
}])

I want to deselect the selected options after sumbit data.

enter image description here

I am trying in this way.My submit function is,

  const onSubmit = async () => {
    let valid = weekdays.every(item => item.select === false)
    if (!valid) {
       const weekdayfltr=weekdays.filter((item) => (item.select ? item!=='' : ''))
        setDays(weekdayfltr.map(item=>item.fullName))
        close()

        // const emptyDialogBox = weekdays.map((ele) => ele.select === true ?
        //     (ele.select = false)
        //     :
        //     ele
        // )
    }
    else {
        toast.error('Select atleast one day !', {
            position: toast.POSITION.BOTTOM_LEFT
        })
        setDays(...weekdays)

    }
};

How to achive this....

Thanks in advance....

CodePudding user response:

you can make an object(clearSelected) and make the selected fields to false and then set it as below:

let clearSelected = weekdays.map((item)=>{return{ ... item, select:false}})
        setWeekdays(clearSelected)
  • Related