3

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
 }]
AsZik
  • 621
  • 1
  • 4
  • 20

4 Answers4

3

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'));
Apostolos
  • 10,033
  • 5
  • 24
  • 39
0

As far as I understan your requirements, handleDayshould look like this:

const handleDay = (day) => {
  setDates((x) => {
    return x.map((v) => {
      if (day === v.day && v.isSelected) {
        v.isSelected = false;
        return {
          v,
        };
      } else {
        return day
      }
    });
  });
};
piotrruss
  • 417
  • 3
  • 11
0

piotrruss had it almost correct.

const handleDay = (day) => {
  setDates((x) => {
    return x.map((v) => {
      if (day === v || day === v.day) {
        return {
          day,
          isSelected: !v.isSelected,
        };
      } else {
        return v;
      }
    });
  });
};
Stephen Collins
  • 3,523
  • 8
  • 40
  • 61
0

You can concat your object with spread operator also.

const handleDay = (day) => {
setDates((x) => {
    return x.map((v) => {
      if (day === v.day && v.isSelected) {
        v.isSelected = false;
        return {
          v,
        };
      } else {
        return day
      }
    });
  });
};