Issue
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
Solution
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 ofproduct
is taken as-is - Then, using the
...
spread-operator all ofprev
's props are spread - This is now followed with
[name]
which is a new prop being added withvalue
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 usingproduct
.
(NOTE: I am still very new to ReactJS & if this is incorrect kindly update appropriately).
Answered By - jsN00b
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.