I am making changes to a set of data and the data is held in a parent components state I pass that data to a 2nd component but when I make changes to the data in the 2nd component it is changing the data in the first. Ive tried setting a variable to the value of the state in an effort to make a copy of it / also creating a new state in the 2nd component that is set from the initial data from the first. But For some reason I am still changing the initial data. Can anyone explain whats going on here?
Parent Component:
const [data, setData] = useState([]);
const [editing, setEditing] = useState(null);
{!!editing && (
<EditInsurance state={editing} data={data} setEditing={setEditing} />
)}
2nd Component:
const [update, setUpdate] = useState([]);
const [List, setList] = useState([]);
//sets the data onLoad
useEffect(() => {
setList(data);
}, []);
//edits the data
const handleClick = (item) => {
let list = List;
list.forEach((el) => {
if (el.payerName === item.payerName) {
el.state.push(state.value);
if (!el.isActive) {
el.isActive = true;
}
}
});
//update is an array containing only edited objects.
setUpdate([...update, item]);
};
When handleClick is fired and I console the data value in the parent component it has been updated. And I dont want to change that data until the user clicks save. How can I have a copy of the data exclusive to the 2nd component that doesn't manipulate the data in the Parent?
from Changing the data in a child component without changing it in the parent
No comments:
Post a Comment