Search code examples
javascriptreactjsuse-state

React object of arrays how to set specific index


I have a useState() object that looks like this:

  const [financeSummary, setFinanceSummary] = useState({
        discountRate: 10,
        financeRate: 10,
        reinvestRate: 10,
        inflationRate: 3,
        singleInvestment: new Array(11).fill(0),
        phasedInvestment: new Array(11).fill(0),
        financedInvestment: new Array(11).fill(0),
        outflowSubtotal: new Array(11).fill(0),
        outflowRebates: new Array(11).fill(0),
        energySavings: new Array(11).fill(0),
        maintenanceSavings: new Array(11).fill(0),
        inflowRebates: new Array(11).fill(0)
    })

I am rendering some of these arrays as a table of inputs:

<tr>
   <td>Single Investment</td>
   {financeSummary.singleInvestment.map((item, i) => (
   <td><input type='number' value={item} onChange={(e) => 
       setFinanceSummary({ ...financeSummary, singleInvestment[i]: e.target.valueAsNumber})} />
   </td>
))}
</tr>

I am unable to use 'singleInvestment[i]' (',' expected.) in order to target a specific index. Is there a way to accomplish this without using a helper function to create a new array?

Thanks all.


Solution

  • You can build a new array by mapping over the old one and picking out the correct index to modify:

    setFinanceSummary({ 
      ...financeSummary, 
      singleInvestment: financeSummary.singleInvestment.map((el, index) => index === i ? e.target.valueAsNumber : el)
    })