Jeff Goes
Jeff Goes

Reputation: 555

How do I change a property from an array of objects when setting React state?

I am having a dumb question and would appreciate if someone could help. I have an array of objects:

weekDays: [
    {label: 'Sun', checked: false},
    {label: 'Mon', checked: false}, 
    {label: 'Tue', checked: false},
    {label: 'Wed', checked: false},
    {label: 'Thu', checked: false},
    {label: 'Fri', checked: false},
    {label: 'Sat', checked: false}]

and they will be check boxes. Once a checkbox is clicked I have to check the value that was given to that input and change the checked value.

This is what I came up with:

handleCheckBox = (e) => {
    console.log(e.target.value); //show value just right
    this.setState((previousState) => ({
      weekDays: previousState.weekDays.map(item => item.label === e.target.value 
        ? Object.assign(item, {checked: !item.checked}) 
        : item)
    }));

however this error shows up: Cannot read property 'value' of null. even though when I console.log this value it shows the value just right.

Does anyone know how to get by this?

Upvotes: 1

Views: 962

Answers (1)

Nik
Nik

Reputation: 2272

In case you are using setState with function as a first argument, you can cache the value that you need:

handleCheckBox = (e) => {
console.log(e.target.value); //show value just right
const value = e.target.value; // our cache

this.setState((previousState) => ({
  // now we'll use cached value
  weekDays: previousState.weekDays.map(item => item.label === value 
    ? Object.assign(item, {checked: !item.checked}) 
    : item)
}));

Upvotes: 1

Related Questions