The below code which i’m using to add the data in the state the code is
JavaScript
x
8
1
this.setState((state) => ({
2
state,
3
frequency: {
4
state.frequency,
5
days: [state.frequency.days, parseInt(val)],
6
},
7
}));
8
my State is Given Below
JavaScript
1
5
1
this.state = {
2
frequency: {
3
days: [],
4
},}
5
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
JavaScript
1
10
10
1
let tempDays = this.state.frequency.days.includes(parseInt(val)) ? [this.state.frequency.days] : [this.state.frequency.days, parseInt(val)]
2
3
this.setState((state) => ({
4
state,
5
frequency: {
6
state.frequency,
7
days: tempDays ,
8
},
9
}));
10
for deletion
JavaScript
1
10
10
1
let tempDays = this.state.frequency.days.filter( day => day !== parseInt(val))
2
3
this.setState((state) => ({
4
state,
5
frequency: {
6
state.frequency,
7
days: [tempDays] ,
8
},
9
}));
10