0

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'.

1
  • your eslint don't like that you are mutate the day argument, and he has a point. you should return new object. Commented Apr 1, 2019 at 22:59

1 Answer 1

1

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

3 Comments

That almost did it, thanks! It was just const tempDay = day. Great!
@StamatisDeliyannis, glad it helped. Though you should do const tempDay = {...day} as that makes a copy whereas const tempDay = day only creates a new reference to the same object. Also, if this helped, please consider marking this answer as the accepted one and/or up-voting. Good luck
The final solution actually came by googling all eslint errors. I made the code better and readable by making a copy of the state object, manipulate it, and then replace the original with the new object.

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.