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

147
Views
React TS universal hack for inputs with useState doesn't work as expected

I've seen typescript solution with universal handle change function, but in my case it works bad. Need help to understand why this happens.

When I add new product - it adds correctly, but when I try to clear Input manually - first rerender it also changes already added content.

Algorithm to see this mistake: fill inputs, add submit and remove one letter from title input - you'll see that it affects already added title in another state, but only on first rerender

Sandbox: https://codesandbox.io/s/restless-dream-do7bqh?file=/src/App.tsx

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The below code-sample may be a solution to achieve the desired objective:

In the handleChange method:

setProduct(prev => ({ ...prev, [name]: value }));

Explanation

  • The prev value of product is taken as-is
  • Then, using the ... spread-operator all of prev's props are spread
  • This is now followed with [name] which is a new prop being added with value as the corresponding value
  • Any existing prop will be replaced.

Suppose name variable has the value 'title' and value is 'Testing 123', then the product object becomes:

product = {
  id: previousValueOfId,
  price: previousValueOfPrice,
  title: 'Testing 123'
}

Here, previousValueOfId and previousValueOfPrice are supposed to be the values.

Why OP's code did not get the desired result

The code is:

setProduct((prev) => {
  (prev as any)[name] = value;
  const newValue = { ...prev };
  return newValue;
});
  • This takes the prev product, and changes it's [name] prop.
  • When prev is changed, it may impact UI elements which are rendered using product.

(NOTE: I am still very new to ReactJS & if this is incorrect kindly update appropriately).

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!