Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
Error writing to input e.target.value in array

There is an array of inputs in two forms: 1. Empty when created. 2. With the created values from the server after creation and saving. My code for adding a value for each of the inputs in the array doesn't work in the second case and I don't understand what could be wrong. In the first case, the values are written normally, and in the second, nothing happens.

<input
  defaultValue={sectionValue[i].text}
  value={sectionValue[i].text}
  onChange={(e: React.ChangeEvent<HTMLInputElement>): void => {
    sectionValue[i].text = e.target.value;
    setSectionValue([...sectionValue]);
  }}
/>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There are two issues:

  1. Any time you're changing state based on existing state, you're best off using the callback form of your state setter, because it's really easy for the handler to close over a stale copy of the state (sectionValue in your case).

  2. You're breaking one of the rules of state: don't directly modify state. You're directly modifying the sectionValue[i] object. So it's the same object, but with a different text property. Later you're copying the array, but you need to copy the object as well. Sometimes it'll happen to render correctly when you do this, but other times — often — it won't.

To fix both, change:

sectionValue[i].text = e.target.value;
setSectionValue([...sectionValue]);

to

setSectionValue(oldSectionValue => {
    const newSectionValue = [...oldSectionValue];
    newSectionValue[i] = {
        ...oldSectionValue[i],
        text: e.target.value
    };
    return newSectionValue;
});

There's more than one way to do that, but the basic things are: 1. Use the callback, and 2. Copy both the object and the array.


Side note: Since sectionValue is an array, I'd suggest using the plural for it (sectionValues).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!