0

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.

2 Answers 2

2

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)
})
Sign up to request clarification or add additional context in comments.

1 Comment

This is one of the cleanest solutions to this problem I have come across - nice work.
0

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]

1 Comment

I feel like this should work, but it doesn't. I've tried a couple of variations of this as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.