1

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?

2

1 Answer 1

1

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)
}));
Sign up to request clarification or add additional context in comments.

3 Comments

thank you! it worked. Why did I have to cache first??
@JeffGoes See the event-pooling reference in the comments.
React uses synthetic events reactjs.org/docs/codebase-overview.html#event-system . By this reason your event after synchronous code will be cleared

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.