0

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?

skyboyer
  • 15,149
  • 4
  • 41
  • 56
Kinston
  • 35
  • 2
  • 5
  • 2
    can you put console.log(allObjects); before the spread to check its value ? – somallg May 24 '21 at 04:20
  • The console.log(allObjects) returns "undefined", if it is inserted before the spread – Kinston May 24 '21 at 04:22
  • 2
    i think you got the answer now, make sure you setup Context Provider correctly, `` and/or set default value for allObjects like this `const {allObjects = [], setAllObjects} = useAllObjects();` – somallg May 24 '21 at 04:26
  • Possibly duplicate to https://stackoverflow.com/questions/57245568/invalid-attempt-to-spread-non-iterable-instance-on-an-object – Nihal Chandwani May 24 '21 at 04:29
  • @somallg Thanks so much, it works. Such a simple solution – Kinston May 24 '21 at 04:29

0 Answers0