I'm using react/redux to fetch data etc.
const dates = useSelector((state) => state.holidays.holidays);
const [newDates, setNewDates] = useState(null);
useEffect(() => {
dispatch(getAllHolidays());
}, []);
useEffect(() => {
if (dates) {
setNewDates([...dates]);
}
}, [dates]);
So I'm using the "useSelector" to get the data from my Redux/state component.
Then i'm using a "useState" to keep a COPY of the dates in there.
The first "useEffect" will get the data I need on component mount/start.
The second "useEffect" will fill in the COPY of dates, every time dates changes (in state).
Anyway, whenever I change "newDates" value now, and do a console.log of the "dates" array, everything's changed as well... I thought using the spreader operator would create a new array (so no previous reference to the "dates"-array, and then fill it with all objects of the "dates"-array. But seemingly it's not the case?
For example, here's how I use it:
const handleDateDescriptionChange = (id, event) => {
let newDatesArray = [...newDates];
newDatesArray.find(date => date.id === id).description = event.target.value;
console.log(dates.find(x => x.id === id).description);
setNewDates([...newDatesArray]);
}
const deleteDateChanges = (id) => {
newDates.find(x => x.id === id).description = dates.find(x => x.id === id).description;
console.log(newDates.find(x => x.id === id).description);
console.log(dates.find(x => x.id === id).description);
setNewDates([...newDates]);
}
In the first function, I want to change the value of the object (with corresponding ID) to set it's value of it's "description" to whatever the user typed in in a TextField. So just to be sure, I create a new array copy (no reference to previous) locally, then find the object I need (based on id), then change it's "description" value.
Then I console.log the original "dates" array, and it's modified too!!
In the second function I'm trying to reset the modified "description" value to the original value from the "dates"-array, but it's not possible because the "dates"-array was changed also and the values are the same, so the second function does nothing now, functionally.
Am I missing something here?!