Without Spead operator
- When you try to correct the age, it doesnt preserve the name
- It updates the age, but we loose the name
- Now how to correct it??
- We need to use spread operator to preserve the data between renders
import React, { useState } from "react";
const UseStateObject = () => {
const [cricketData, SetCricketData] = useState({
name: "Sachin",
age: 48,
});
const changeCricketerData = (age) => {
console.log("Data is wrong ,we have to increase the age by 1 to correct it");
SetCricketData({ age: age + 1 });
};
return (
<>
- {cricketData.name}
- {cricketData.age}
>
);
};
export default UseStateObject;
With Spead operator
- SetCricketData({ …cricketData, age: age + 1 });
- Spread operator to preserve the data between render
- Highlighted line – 11
import React, { useState } from "react";
const UseStateObject = () => {
const [cricketData, SetCricketData] = useState({
name: "Sachin",
age: 48,
});
const changeCricketerData = (age) => {
console.log("Data is wrong ,we have to increase the age by 1 to correct it");
SetCricketData({ ...cricketData, age: age + 1 });
};
return (
<>
- {cricketData.name}
- {cricketData.age}
>
);
};
export default UseStateObject;