The below code which i’m using to add the data in the state the code is
this.setState((state) => ({
...state,
frequency: {
...state.frequency,
days: [...state.frequency.days, parseInt(val)],
},
}));
my State is Given Below
this.state = {
frequency: {
days: [],
},}
im adding numeric value from 1 to 30 but when i try to add same number it adds to the array i should not add it again please give me solution
Advertisement
Answer
before updating the state perform an evaluation like then assign the days
let tempDays = this.state.frequency.days.includes(parseInt(val)) ? [...this.state.frequency.days] : [...this.state.frequency.days, parseInt(val)]
this.setState((state) => ({
...state,
frequency: {
...state.frequency,
days: tempDays ,
},
}));
for deletion
let tempDays = this.state.frequency.days.filter( day => day !== parseInt(val))
this.setState((state) => ({
...state,
frequency: {
...state.frequency,
days: [...tempDays] ,
},
}));