Stamatis Deliyannis
Stamatis Deliyannis

Reputation: 61

Toggle Boolean property inside Object in Array of Objects in state

I have an array of Objects in state, like so:

this.state = {
  week: [
    {
      en: 'Mon',
      morn: false,
      night: false,
    },
//... the rest of the days...

I can successfully toggle the morn and night Booleans, like so:

this.setState(prevState => {
      prevState.week.map(day => {
        if (target.includes(day.en)) {
          if (target.includes('morn')) {
            day.morn = !day.morn;
          //^ right here
          }
          if (target.includes('night')) {
            day.night = !day.night;
          //^ and here
          }
        }
        return day;
      });
    });

eslint complains: Assignment to property of function parameter 'day'.

Upvotes: 0

Views: 1076

Answers (1)

Chris
Chris

Reputation: 59511

You are getting this because your linter has the following rule enabled: https://eslint.org/docs/rules/no-param-reassign

Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, as modifying function parameters will also mutate the arguments object. Often, assignment to function parameters is unintended and indicative of a mistake or programmer error.

This rule can be also configured to fail when function parameters are modified. Side effects on parameters can cause counter-intuitive execution flow and make errors difficult to track down.


Do solve this, you could create a copy of your day object, which you can modify and return that instead:

this.setState(prevState => {
  prevState.week.map(day => {
    const tempDay = {...day};
    if (target.includes(day.en)) {
      if (target.includes('morn')) {
        tempDay.morn = !day.morn;
      }
      if (target.includes('night')) {
        tempDay.night = !day.night;
      }
    }
    return tempDay;
  });
});

Upvotes: 1

Related Questions