New to React / State / Arrays.
Why does this come up with "is not iterable"
const myVar = {
'2022-11-22': { selected: true, textColor: 'blue', activeOpacity: 0}
};
const [myMarkedDates, setMarkedDates] = useState(myVar);
const newVar = {
'2022-12-17': {selected: true, textColor: 'red', activeOpacity: 0}
};
const newVars = [newVar, ...myMarkedDates];
setMarkedDates(newVars);
CodePudding user response:
You are mixing and array with an object here.
The spread notation using ...myMarkedDates
returns the properties of the object:
'2022-11-22': { selected: true, textColor: 'blue', activeOpacity: 0}
This can be a property of another object, but NOT an element inside the array.
This would be a valid syntax for you:
const newVars = [newVar, {...myVar}];
Here newVars
will be an array containing the objects newVar
and myVar
:
[
{
'2022-12-17': { selected: true, textColor: 'red', activeOpacity: 0 }
},
{
'2022-11-22': { selected: true, textColor: 'blue', activeOpacity: 0 }
}
]
Depending on what you are trying to achieve this might be preferred:
const newVars = {...newVar, ...myVar};
In the code above newVars
will be an object with the properties of newVar
and myVar
combined:
{
'2022-12-17': { selected: true, textColor: 'red', activeOpacity: 0 },
'2022-11-22': { selected: true, textColor: 'blue', activeOpacity: 0 }
}