Mark James
Mark James

Reputation: 558

How to fix "no-param-reassign" eslint error?

How to fix error "no-param-reassign": [2, {"props": false}]"

This is example where I am getting the Eslint error:

 filtersList.forEach((filter) => {
      if (filter.title === 'Timeframe') {
        filter.options.forEach((obj) => {
          obj.selected = false;
        });
      }
    });

How to fix this?

Upvotes: 1

Views: 1327

Answers (2)

Clarity
Clarity

Reputation: 10873

Basically you're modifying your filterList in place with forEach, use map instead:


filtersList.map(filter => {
  if (filter.title === "Timeframe") {
    return {
      ...filter,
      options: filter.options.map(obj => ({ ...obj, selected: false }))
    };
  }
  return filter;
});

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370729

Your existing code mutates objects in the parameter array, which is causing the linter error. Either disable the linter rule for the line, or create new objects instead of mutating, eg:

const changedFilters = filtersList.map((filter) => {
  if (filter.title !== 'Timeframe') {
    // you can clone the object here too, if you want
    return filter;
  }
  return {
    ...filter,
    options: filter.options.map((obj) => ({
      ...obj,
      selected: false
    }))
  };
});

Then use the changedFilters variable later on in the code. This ensures that nothing is mutated.

Upvotes: 1

Related Questions