React: useContext hook - Invalid attempt to destructure non-iterable instance

Created on 5 Nov 2019  路  3Comments  路  Source: facebook/react

Randomly getting error "Invalid attempt to destructure non-iterable instance" on useContext.

console error -> https://prnt.sc/psvrcn
source file -> https://github.com/aedilyan/simple-react-app/blob/master/src/components/header/Header.js#L11

as a workaround I use conditional assignment e.g. Array.isArray(useContext(AuthContext)) ? useContext(AuthContext) : [{}, function(){}];

Please advice!

Most helpful comment

This question might be better suited for stackoverflow but in your case, you can add a default value to your createContext() call here so then it will have the default available before the value is set on the provider.

For example,

export const AuthContext = React.createContext([{}, function(){}]);

All 3 comments

This question might be better suited for stackoverflow but in your case, you can add a default value to your createContext() call here so then it will have the default available before the value is set on the provider.

For example,

export const AuthContext = React.createContext([{}, function(){}]);

A default value is a good option for this usecase, as is conditionally checking before destructuring.

OK - Thanks

Was this page helpful?
0 / 5 - 0 ratings