When trying to use the spread operator to add an object to an array it returns the following error :
TypeError: Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.
Here is the relevant code in the component:
const Component = () => {
const object = useObject()
const {allObjects, setAllObjects} = useAllObjects();
useEffect(()=> {
if(object){
setAllObjects([...allObjects, object])
}
}, [object])
}
Code from the context provider
export type AllObjectsContextType = {
allObjects: any;
setAllObjects: (allObjects : any) => void;
}
export const AllObjectsContext = createContext<AllObjectsContextType>({ allObjects: [], setAllObjects: allObjects => console.warn('no allObjects provider')});
export const useAllObjects = () => useContext(AllObjectsContext);
How can I push objects/items to an array using TypeScript and SetState?