I am currently utilizing Zustand in a TypeScript Next.js application. Strangely, whenever I attempt to loop through my state object, I encounter a runtime error message.
The structure of the damaged zone object for my car is as follows:
const damagedZones = {
Left: {
front_door:[
{
id: 1,
picture1: 'picture 1 base64 string',
picture2: 'picture 2 base64 string',
comment: 'any comment'
},
{
id: 2,
picture1: 'picture 1 base64 string',
picture2: 'picture 2 base64 string',
comment: 'any comment'
}
],
back_door: [
],
Assuming I add a new element to my "front_door" array, here is the relevant zustand store and function: In the provided code snippet, the variable "zone" would correspond to the "Left" key in my damagedZones object, while "element" would represent the "front_door" key.
export const useDamagedZones = create<DamagedZonesProps>((set) => ({
damagedZones: damagedZones,
setDamagedZones: (elementItem: damagedItem, zone: string, element: string) => {
set(state => ({
damagedZones: {
...state.damagedZones,
[zone]: {
...state.damagedZones[zone],
[element]: [
...state.damagedZones[zone]?.[element],
elementItem
]
}
}
}))
},
}))
Upon triggering this function, I receive a runtime error that states:
TypeError: Invalid attempt to spread non-iterable instance. Non-array objects must have a Symbol.iterator method in order to be iterable.
I'm perplexed by this issue.... While using an object with ids as keys instead of arrays solves the problem, it's not as convenient. An array is more suitable in this scenario, yet it's not working as expected....