Yoseph Ahmed
Yoseph Ahmed

Reputation: 55

ReactJS es-lint: Return statement should not contain assignment

es-lint is failing for this case: Return statement should not contain assignment no-return-assign

I've looked into this thread but to no avail: Arrow function should not return assignment no-return-assign

What can I do here to satisfy es-lint?

My State Variable

const [monthlyIncidents, setMonthlyIncidents] = useState([
    // monthlyIncidents[0] -> January ... monthlyIncidents[11] -> December
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
  ])

How I'm Updating State

setMonthlyIncidents((prevIncidents) => {
   return { ...prevIncidents, [incidentMonth]: monthlyIncidents[incidentMonth] += 1 }
})

Upvotes: 2

Views: 1218

Answers (2)

HAK
HAK

Reputation: 458

TRY

setMonthlyIncidents( { ...prevIncidents, [incidentMonth]: prevIncidents[incidentMonth] + 1,

}).

you just need to not assign state while returning it.Plus, I really don't get why you are creating a whole new function to set the state? (what does the setStateVariable hook do?). You can also disable es-lint for that line.

Upvotes: 1

Drew Reese
Drew Reese

Reputation: 203542

My guess is it is seeing the += 1 as assignment (which coincidentally is also a state mutation).

You may be able to get by with just adding one to the current state. This likely converts your array to an object, so use caution.

setMonthlyIncidents((prevIncidents) => {
  return {
    ...prevIncidents,
    [incidentMonth]: prevIncidents[incidentMonth] + 1,
  }
})

Typically with a state update like this it is preferable to map the existing state to the next state and update the element. It looks like incidentMonth is simply an array index, so you can match the incident by index. This guarantees the state remains an array.

setMonthlyIncidents((prevIncidents) =>
  prevIncidents.map((incident, index) =>
    incident + index === incidentMonth ? 1 : 0
  )
);

Upvotes: 2

Related Questions