Cannot destructure property 'value' of 'Object(...)(...)' as it is undefined

Viewed 4120

I am getting an error Cannot destructure property 'value' of 'Object(...)(...)' as it is undefined. and I am not sure what went wrong. I have some code here that sets the context and using the context. Many thanks in advance and greatly appreciated.

userContext.js

import {createContext} from 'react'

export const UserContext = createContext()

App.js

import {UserContext} from './component/userContext'
import {useState} from 'react'

function App() {
   const [value, setValue] = useState("Guest")
  return (
    <div> 
      <Router>
         <UserContext.Provider value={{value, setValue}}>
            <BootstrapNavbar/>  
         </UserContext.Provider> 
      </Router>
     </div>

Signin.js

import React, {useState,useContext} from 'react'
import {UserContext} from './userContext'

const Signin = () => {
    const [visible, setVisible] = useState(false)
    const {value, setValue} = useContext(UserContext)
}

Error

    TypeError: Cannot destructure property 'value' of 'Object(...)(...)' as it is undefined.

    const {value, setValue} = useContext(UserContext)
3 Answers

Be sure to provide wrap your App.js
And you can take a look at this blog post

Export UserContext this way

const UserContext = React.createContext(); // Create a context object

export {
  UserContext // Export it so it can be used by other Components
};

Try this:

const value = useContext(UserContext)
Related