Search code examples
javascriptreactjstypescripteslintarrow-functions

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 }
})


Solution

  • 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
      )
    );