useContext with no context

Viewed 309

I have defined a context using createContext that wraps some of my components like

import MyContext from './mycontext.js'
import A from 'a.js';
import B from b.js';
<MyContext>
    <A/>
    <B/>
</MyContext>

where A is defined something like

import C from './c.js'
const A = () => {
    return (<C/>);
}

And C is define something like

import MyContext from 'mycontext.js';

const C = () => {
    const { value, setValue } = useContext(MyContext);
    return (<div>`This is the value - ${!!value ? value : 'UNK'}`</div>)
}

Finally the context is created like

const MyContext = createContext({value: '', setValue: () => {}});

The problem is that I get a runtime error

TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))

From the component C.

I want to make provision for calling C outside of the provider. Not as a wrapped child of the provider. Where does this error come from and how do I work around it?

1 Answers

From only what I can tell from the code snippets it appears you're not rendering any context provider and not providing a context value.

Instead of trying to use the MyContext context as a React component, render the Provider component.

<MyContext.Provider value={{ value: 42, setValue: console.log }}>
  <A />
  <B />
</MyContext.Provider>

Edit usecontext-with-no-context

enter image description here

Related