Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
Object null is not iterable when trying to import and use global state in component

I would like to create a globalState to track a few properties I would like to pass down to multiple components.

const initialState = {
    nickname: '',
    selectedRoom: null,
    rooms: [],
    createdRoomTopic: '',
    twilioToken: '',
    device: null
};

const RoomContext = createContext(null);

export const RoomContextProvider = ({ children }) => {
    const[state, setState] = useState(initialState);
    return (
        <RoomContext.Provider value={[state, setState]}>{children}</RoomContext.Provider>
    )
};

export const useGlobalState = () => {
    const value = useContext(RoomContext)
    if(value === undefined) throw new Error('Please add RoomContextProvider');
    return value;
}

However when I use this 'global state' in a component

import { useGlobalState } from '../../context/RoomContextProvider';
....
const [state, setState] = useGlobalState();

My page does not render and I get the error message:

Uncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))

UPDATE Here's an example of where I used useGlobalState

import { useGlobalState } from '../../context/RoomContextProvider';
...
<useGlobalState>
    <SignupForm/>
<useGlobalState/>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You have probably not wrapped the invocation of the context api via useGlobalState inside the context provider in a parent component, which it needs to be in order to access the context.

Update: in your updated question you are wrapping the hook as JSX element, which is incorrect. You have to do the wrapping with the provider and then the hook will work in any component that exists under the provider in the tree.

You can check this modified code that does the exactly that - https://stackblitz.com/edit/react-jfubkz?file=src%2FApp.js

You can read more about usage of React Context here - https://beta.reactjs.org/apis/usecontext

Also your attempt to handle

if (value === undefined) throw new Error('Please add RoomContextProvider');

does not work because value is null initaly as per initialization as below

const RoomContext = createContext(null);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda