Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 858
hans Avatar asked Oct 29 '25 13:10

hans


2 Answers

When using the useContext hook, the returned value is a single object, not an array. Therefore, the correct syntax to destructure the context value would use curly braces instead of square brackets.

In TaskList.jsx change the following statement.

const [state, setState] = useStateContext();

To

const {state, setState} = useStateContext();
like image 158
Ihsan_buneri Avatar answered Oct 31 '25 05:10

Ihsan_buneri


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...

like image 31
Harsh Mangalam Avatar answered Oct 31 '25 05:10

Harsh Mangalam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!