Updating Object State
This example demonstrates how to properly update an object state in React.
When updating an object, using setState with just a single property (e.g., setUser({ name: e.target.value })) will replace the entire object, removing other properties.
Instead, you should spread the existing object properties (...user) and only update the specific property you want.
This ensures that the other properties remain unchanged. Alternatively, you can use a callback function with setState to achieve the same result while ensuring that you are working with the most recent state.
import { useState } from "react";
const Third = () => {
// how to update an object state
const [user, setUser] = useState({ name: "", city: "", age: 50 });
const handleChange = (e) => {
// setUser(user.name = e.target.value); // this kind of update doesn't work
// setUser({ name: e.target.value }); // this works, but it removes city and age
setUser({
...user,
name: e.target.value,
}); // this is the correct way to update the data
// you can also do it using a callback
/*
setUser((prev) => {
return {
...prev,
name: e.target.value,
};
});
*/
};
console.log(user);
return (
<>
<form>
<input
onChange={handleChange}
type="text"
placeholder="Type your name here"
/>
</form>
{user.name !== "" ? (
<p>
Your name is: {user.name} | Your city is: {user.city} | Your age is:{" "}
{user.age}
</p>
) : (
""
)}
</>
);
};
export default Third;