I have the useState varible. I want to concat the value with new object.
const [dates,setDates] = useState(["Mon","Sun"])
rules: 1.If the date exist with isSelected flag then make as false
[{day:"mon",isSelected:false}]
otherwise, make as,
[{day:"mon",isSelected:true}]
my function below,
const handleDay = (day) => { setDates((x) => { x.map((v) => { if (day === v.day && v.isSelected) { v.isSelected = true; return { v, }; } else { return { day, isSelected: true, }; } }); }); }; handleDay('mon');
expected output
[{day:"mon",isSelected:true}, 'Sun']
but I got this,
[{ "day": "Mon", "isSelected": true }, { "day": "Mon", "isSelected": true }]
Advertisement
Answer
Replace your map
code with this
arr.map(v => { if (day === v.day || day === v) { return { day: v.day ? v.day : v, isSelected: !v.isSelected }; } else { return v } });
let arr = ["Mon", "Sun"] const handleDay = day => { let arr2 = arr.map(v => { if (day === v.day || day === v) { return { day: v.day ? v.day : v, isSelected: !v.isSelected }; } else { return v } }); return arr2; }; console.log(handleDay('Mon')); arr = handleDay('Mon'); console.log(handleDay('Mon'));