'Update element on updating react state array

I am confused in updating element with React.useState() I am creating dynamic calculator, where you can add fields, so I cannot use one state per result of category, so I created an object contains results by Id of category, and categories can be added there. let [results, setResults] = React.useState({}); Then every time when user adds a product

for (const category of product.categories) {
  results[category.id] = 0;

When I am updating result for some category, it is gets updated:

setResults(newResults => {
  newResults[categoryId] = mult * sum * quantity;
  return newResults;
})

But my element in the table keeps showing zero (inital value)<TableCell align="right"><p>{results[category.id]}</p></TableCell>

Upd: here is the full code: https://pastebin.com/cbJzFC8t Page looks like this



Solution 1:[1]

You need to define a new variable

setResults(oldResults=> {
  let newResults = oldResults[categoryId]
  newResults = mult * sum * quantity;
  return newResults;
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ValenciaHQ