Home > Mobile >  React object of arrays how to set specific index
React object of arrays how to set specific index

Time:08-18

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.

CodePudding user response:

you have to wrap the index in [ ] :

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

and instead of singleInvestment[i] , you must just write [item]:e.target.valueAsNumber

since item = financeSummary.singleInvestment[i]

CodePudding user response:

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