Skip to content

Why am I getting undefined prop?

Below is my Header component in react:

import React from 'react'
import {AppBar} from '@material-ui/core'
import {Typography,Container,Toolbar,Select,MenuItem} from '@material-ui/core'
import {useNavigate} from 'react-router-dom'
import { CryptoState } from './CryptoContext'
const Header = () => {
 const navigate=useNavigate();
 const {currency,setCurrency}=CryptoState();
  return (
       <AppBar>
           <Container>
               <Toolbar>
                   <Typography onClick={()=>navigate('/')}>
                       CryptoTracker
                   </Typography>
                   <Select value={currency}
                   onClick={(e)=>setCurrency(e.target.value)}
                   >
                       <MenuItem value="USD">USD</MenuItem>
                       <MenuItem value="INR">INR</MenuItem>
                   </Select>
               </Toolbar>
           </Container>
       </AppBar>
  )
}

export default Header

I have used ContextAPI for efficient state Management.CryptoState is used for this purpose.I have imported the state in Header and getting the necessary props using object-destructuring.

Below is my Context-file:

import React from 'react'
import { useEffect } from 'react';
import { createContext ,useState,useContext } from 'react';
const CryptoContext = ({children}) => {
    const Crypto=createContext();
    const [currency,setCurrency]=useState("USD");
    const [symbol,setSymbol]=useState("$");

    useEffect(()=>{
      if(currency=="INR")
      setSymbol("₹") 
      else
      setSymbol("$") 
    })
  return (
    <Crypto.Provider value={{currency,symbol,setCurrency}}>
        {children}
    </Crypto.Provider>
  )
}

export default CryptoContext;
export const CryptoState=()=>{
    return useContext(Crypto);
}

I am getting this error in Header component:Header.js:8 Uncaught TypeError: Cannot destructure property 'currency' of '(0 , _CryptoContext__WEBPACK_IMPORTED_MODULE_1__.CryptoState)(...)' as it is undefined.

Answer

inside your CryptoState function, Crypto is not defined as it is initialized in CryptoContext.

Crypto context should be extracted from your CryptoContext component and declared as a const outside of any function to be available