Kex
Kex

Reputation: 8599

React, how do I update just one property in an object that uses the useState hook?

In my code I currently have a state like so:

const [caclulatorObj, setCalculatorObj] = useState({
  total: '0',
  next: null,
  operator: null
});

function clickHandler(isOperator, value) {
  setCalculatorObj(calculate(caclulatorObj, value));
}

The calculate function returns an object as described above. My question is do I always have to set a complete object when updating the state? For example, in my calculate function maybe I only update the next variable:

return {
  total: calculatorObj.total,
  next: someNewValue,
  operator: calculatorObj.operator
}

Can I just return this instead?:

return { next: someNewValue };

Or do I always need to return the full object?

Upvotes: 0

Views: 1265

Answers (1)

Carlos Saiz Orteu
Carlos Saiz Orteu

Reputation: 1805

You would need to set the state like this:

function clickHandler(isOperator, key, value) {
  setCalculatorObj(calculate(caclulatorObj, { ...calculatorObj, [key]: value}));
}

And when you call it pass the key you want to modify:

onClick={(e) => clickHandler(false, 'next', e.target.value )}

Upvotes: 1

Related Questions