Home > Back-end >  useContext is not a function or its return value is not iterable
useContext is not a function or its return value is not iterable

Time:01-10

I get the following error when using const [state, setState] = useContext(Context):

useContext is not a function or its return value is not iterable

Not sure why as I've done this multiple times before. This is my set up:

My State.jsx file:

import { createContext, useState } from "react";

export const Context = createContext()

const initialState = {
    tasks: {}
}

const State = ({children}) => {
    const [state, setState] = useState(initialState)

    return (
        <Context.Provider value={[state, setState]}>
            {children}
        </Context.Provider>
    )
}

export default State;

Used as a wrapper in App.jsx:


import State from './state'
import TaskList from './components/TaskList'

const App = () => {
  return (
    <State>
      <TaskList />
    </State>
  )
}

export default App;

Trying to access the state in TaskList.jsx:

import { useContext } from 'react';
import { Context } from '../State';

const TaskList = () => {
  const [state, setState] = useContext(Context)
  
  return (
    <>
      <h1>Task list</h1>
    </>
  )
}

export default TaskList

Which returns the error specified before, any ideas on what I'm doing wrong?

Error log

CodePudding user response:

const Context = createContext([initialState, () => {}])

Supply a dummy default value to createContext should fix the problem.

CodePudding user response:

State.jsx


import { createContext, useContext, useState } from "react";

 const Context = createContext();

const initialState = {
  tasks: {}
};

const State = ({ children }) => {
  const [state, setState] = useState(initialState);

  return (
    <Context.Provider value={[state, setState]}>{children}</Context.Provider>
  );
};

export default State;
export const useStateContext = () => useContext(Context);


TaskList.jsx


import { useStateContext } from "./State";

const TaskList = () => {
  const [state, setState] = useStateContext();

  return (
    <>
      <h1>Task list</h1>
      <pre>{JSON.stringify(state)}</pre>
    </>
  );
};

export default TaskList;



Wow working fine...

  • Related