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?

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();
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With