Search code examples
reactjsreact-context

TypeError: Object is not iterable when working with react context


Im new to react and im trying to make a little project and ran into react context because i find it annoying passing down the props. I'm running into a problem with the useContext() hook.

My Context file

export function BoardProvider(props){

const [ board, setBoard ] = useState({
    id: null,
    name:  null,
    longterm: false,
    code: null,
    teacher: null,
    periodStart: null,
    periodEnd: null,
    totalDuration: null,
    phases: [],
    students: []

})
return (
    <BoardContext.Provider value={[board, setBoard]}>
        {props.children}
    </BoardContext.Provider>
)

}

And I'm trying to save the object from the context into this one like so:

const [ board, setBoard ]  = useContext(BoardContext);

I'm importing the Context like this:

import { BoardProvider } from '../../contexts/BoardContext'

The error says the object is not iterable so I assume that i declare somewhere that board is an array? If that is so where exactly and how can I fix the error?

Thanks for everyone helping in advance:)


Solution

  • I got behind some tutorials again and found my mistake. I had my .Provider tag in the wrong file. It's supposed to be in the App where the Router is, where you call all the components so they all have access to the context.

    function RouterApp() {
    
        const [ board, setBoard ] = useState(null);
    
        const value = useMemo(() => ({ board, setBoard}), [ board, setBoard])
    
        return (
            <Router>
                <div className="App">
                    <BoardContext.Provider value={value}>
                        <Switch>
                            <Route path="/" exact component={BoardName} />
                            <Route path="/createboard/:name" exact component={TimePeriod} />
                            <Route path="/createboard:name/phases" exact component={PhaseForm} />
                        </Switch>
                    </BoardContext.Provider>
    
                </div>
            </Router>
        );
    }
    
    export default RouterApp;
    
    

    Here's my router function, where im passing the context to the components to BoardName, TimePeriod and PhaseForm.

    Thanks for everyone helping me.