0
votes

I tried running this code, but it's giving me a runtime error saying

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

here is the code.

import React, { useContext} from "react";
import { GlobalContext } from '../GlobalState';

const MediaCard = ({ songs, categotyTitle }) => {
  const [{}, dispatch] = useContext(GlobalContext);
  const setCurrentVideoSnippet = data => {
    dispatch({ type: "setCurrentVideoSnippet", snippet: data });
  };
export default MediaCard;

the error is pointing at this line of code const [{}, dispatch] = useContext(GlobalContext);

the GlobalState code

import React, { useReducer } from "react";

export const GlobalContext = React.createContext();

const initialState = {
  currentVideoSnippet: {}, 
};

const reducer = (state, action) => {
  switch (action.type) {
    case "setCurrentVideoSnippet":
      return {
        ...state,
        currentVideoSnippet: action.snippet
      };
 default:
      return state;
  }
};

export const GlobalState = props => {
  const globalState = useReducer(reducer, initialState);
  return (
    <GlobalContext.Provider value={globalState}>
      {props.children}
    </GlobalContext.Provider>
  );
};
3
You need to implement an iterator. Or you can use Object.keys, Object.values, or Object.entriesDom
I tried what you posted in a codeSandbox and there's no error. Maybe the problem lies in some code you haven't posted. https://codesandbox.io/s/infallible-hugle-6m4iv?file=/src/globalContext.jsEvanMorrison

3 Answers

1
votes

It looks like you forgot to wrap your component with provider you created as you currently use it:

<GlobalState>
  <MediaCard />
</GlobalState>
1
votes

I know this doesn't solve the OP's issue, but for those like me who wound up on this page with the same run time error message, my issue was caused because of the way I was importing the GlobalContext component.

Wrong Way: import GlobalContext from '../GlobalState';

Correct Way: import { GlobalContext } from '../GlobalState';

This fixed the issue I was running into with the same error message.

0
votes

Below is my code, it is just an example to show you why the error is occurring in your code.

The data layer you created is not been wrapped around the components of the whole web app therefore it's not able to be recognized by the MediaCard component... what you need to do is just go in your index.js and wrap the StateProvider around the main app

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import reducer, { initialState } from "./reducer";
import { StateProvider} from'./StateProvider';

ReactDOM.render(
  <React.StrictMode>
    <StateProvider initialState={ initialState } reducer={ reducer }>
    <App />
    </StateProvider>
  </React.StrictMode>,
  document.getElementById('root')
);