I have the useState varible. I want to concat the value with new object.
JavaScript
x
2
1
const [dates,setDates] = useState(["Mon","Sun"])
2
rules: 1.If the date exist with isSelected flag then make as false
JavaScript
1
2
1
[{day:"mon",isSelected:false}]
2
otherwise, make as,
JavaScript
1
2
1
[{day:"mon",isSelected:true}]
2
my function below,
JavaScript
1
20
20
1
const handleDay = (day) => {
2
setDates((x) => {
3
x.map((v) => {
4
if (day === v.day && v.isSelected) {
5
v.isSelected = true;
6
return {
7
v,
8
};
9
} else {
10
return {
11
day,
12
isSelected: true,
13
};
14
}
15
});
16
});
17
};
18
19
handleDay('mon');
20
expected output
JavaScript
1
2
1
[{day:"mon",isSelected:true}, 'Sun']
2
but I got this,
JavaScript
1
8
1
[{
2
"day": "Mon",
3
"isSelected": true
4
}, {
5
"day": "Mon",
6
"isSelected": true
7
}]
8
Advertisement
Answer
Replace your map
code with this
JavaScript
1
11
11
1
arr.map(v => {
2
if (day === v.day || day === v) {
3
return {
4
day: v.day ? v.day : v,
5
isSelected: !v.isSelected
6
};
7
} else {
8
return v
9
}
10
});
11
JavaScript
1
21
21
1
let arr = ["Mon", "Sun"]
2
3
const handleDay = day => {
4
let arr2 =
5
arr.map(v => {
6
if (day === v.day || day === v) {
7
return {
8
day: v.day ? v.day : v,
9
isSelected: !v.isSelected
10
};
11
} else {
12
return v
13
}
14
});
15
16
return arr2;
17
};
18
19
console.log(handleDay('Mon'));
20
arr = handleDay('Mon');
21
console.log(handleDay('Mon'));