I have some problems regarding React code. Inside my App.jsx
, I wrote the logic with and without the destructuring of an object I get from an jsx tag:
<input
name="fName"
placeholder="First Name"
onChange={handleChange}
value={fullName.fName}
/>
<input
name="lName"
placeholder="Last Name"
onChange={handleChange}
value={fullName.lName}
/>
Here is the code with destructuring way:
function handleChange(event) {
const { name, value } = event.target;
setFullName((preValue) => {
if (name === "fName") {
return {
fName: value,
lName: preValue.lName,
};
} else if (name === "lName") {
return {
fName: preValue.fName,
lName: value,
};
}
});
}
While this is the code without destructuring way
function handleChange(event) {
setFullName((preValue) => {
if (event.target.name === "fName") {
return {
fName: event.target.value,
lName: preValue.lName,
};
} else if (event.target.name === "lName") {
return {
fName: preValue.fName,
lName: event.target.value,
};
}
});
}
Note that I tried to write the code with the same logic. However, while the former does work, in the latter way, my code doesn’t work and starts to crash showing this error:
TypeError
Cannot read properties of null (reading 'name')
eval
/src/components/App.jsx:11:23
8 |
9 | function handleChange(event) {
10 | setFullName((preValue) => {
> 11 | if (event.target.name === "fName") {
| ^
12 | return {
13 | fName: event.target.value,
14 | lName: preValue.lName,
I expect it to work even when I do not use the destructuring
2
Answers
I figured out how my code does not work. It's because I'm working with React@16, and the mechanism behind event pooling is that it always refreshes the event every time the event handler is called. Here's the docs for reference: https://legacy.reactjs.org/docs/legacy-event-pooling.html
This has nothing to do with destructuring. It’s only important, when you access the object.
In the first snippet, the values
name
andvalue
are copied beforesetFullName
is called. In the second example, the objectevent
is accessed aftersetFullName
is called. The object is mutable and you get different behavior, if the object is modified before its values are read.Example:
You can achieve the same behavior with and without desctructuring.