Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!