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/>
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);