Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.useContext() keeps returning undefined? [closed]

I'm using Next.js and React, using react hooks + context to manage state. However, I've run into this issue, where React.useContext() returns undefined even though I'm passing in my context object (or so I think, anyway). Am I missing something really obvious? What's happening?

I've created the context in a const called CartContext, and then in my provider component, I have created the value object and passed it as a prop to CartContext.Provider (see below, in _app.js). I made sure the context provider was wrapping my components by adding an <h1> element just to make sure.

The problem seems to occur in index.js. I've imported the CartContext from ./_app.js and then passed it as the argument to useContext() which is supposedly what I should do, but it keeps throwing this error:

"TypeError: Cannot destructure property 'firstSample' of 'react__WEBPACK_IMPORTED_MODULE_0___default.a.useContext(...)' as it is undefined"

which from what I have gathered tells me that useContext() is returning undefined.

_app.js (wraps all pages)

import React from 'react'
import '../styles/global.css';
import theme from '../components/customTheme';
import { ThemeProvider } from '@material-ui/core/styles';

const MyApp = props => {
  const { Component, pageProps, store } = props

  return (
    <ContextProvider>
      <ThemeProvider theme={theme}>
        <Component {...pageProps} />
      </ThemeProvider>
    </ContextProvider>
  )
}

// Context 

export const CartContext = React.createContext()

function ContextProvider({ children }) {
  const value = {
    firstSample: "Test",
    exampleFunction: () => {alert("Hello World")},
  }

  return (
    <CartContext.Provider value={value}>
      <h1>The provider works</h1>
      {children}
    </CartContext.Provider>
  )
}


export default MyApp;

index.js

import Nav from '../components/nav';
import Footer from '../components/footer';
import Product from '../components/product';
import { makeStyles } from '@material-ui/core/styles';
import CartContext from './_app';
import {
    Typography,
    Button
} from '@material-ui/core';

const useStyles = makeStyles({
    body: {
        margin: '13vh 0 3vh',
        backgroundColor: ' white',
        textAlign: 'left'
    },
    earnWrapper: {
        display: 'block',
        textAlign: 'left',
        backgroundColor: 'white',
        width: 'calc(100% - 4vh)',
        margin: '5% 2vh 12%',
        borderRadius: '25px',
        transition: '0.3s',
        boxShadow: '0px 5px 20px #dedede'
    },
    earnContent: {
        padding: '7%',
        textAlign: 'left',
        display: 'inline-block'
    },
    earntCaption: {
        color: 'grey',
    },
    earntAmount: {
        margin: '0.5vh  0 1.5vh'
    },
    withdraw: {
        width: '130px',
        height: '40px'
    },
    shareInfo: {
        margin: '5%  2vh',
        textAlign: 'left'
    }, 
    products: {
        textAlign: 'center ',
        width: '100%'
    }
});

export default function Home(props) {
    const styles = useStyles();

    // Grab data from parent context
   const { firstSample } = React.useContext(
       CartContext
   )

    return (
        <div>

            <DefaultHead
            title="Oorigin | Home"
            />

            <Nav isLoggedIn={true} />

            <div className={styles.body}>
                <div className={styles.earnWrapper}>
                    <div className={styles.earnContent}>
                        <Typography className={styles.earntCaption} variant="caption">You've earned</Typography>
                        <Typography className={styles.earntAmount} variant="h4">S$18.50</Typography>
                        <Button className={styles.withdraw} disableElevation variant="contained" color="primary">Withdraw</Button>
                    </div>
                </div>
                <div className={styles.shareInfo}>
                    <Typography><b>Shop, Share, Earn</b></Typography>
                    <Typography><br/>Shop products you like, share products you love, and earn up to 10% commission on every qualifying sale you refer</Typography>
                </div>
                <div className={styles.products}>
                    <Product
                    imgURL="../TestItem1.svg"
                    imgAlt="Test Product"
                    title="Disinfecting Air Purifying Solution"
                    price={(22.80).toFixed(2)}
                    link="/products/staticProduct"
                    />
                    <Product
                    imgURL="../TestItem2.svg"
                    imgAlt="Test Product"
                    title="Disinfecting Air Purifying Solution"
                    price={(22.80).toFixed(2)}
                    />
                    <Product
                    imgURL="../TestItem3.svg"
                    imgAlt="Test Product"
                    title="Disinfecting Air Purifying Solution"
                    price={(22.80).toFixed(2)}
                    />
                    <Product
                    imgURL="../TestItem4.svg"
                    imgAlt="Test Product"
                    title="Disinfecting Air Purifying Solution"
                    price={(22.80).toFixed(2)}
                    />
                </div>
            </div>

            <Footer/>

            <h1>{firstSample}</h1>
        </div>
    );
}
like image 905
jnm Avatar asked Oct 15 '25 07:10

jnm


1 Answers

Ok so it was a really simple mistake, I imported CartContext in index.js as import cartContex from _app.js, when it should be with curley brackets because it is not the default export. So the corrected (functional) code is simply: import { cartContext } from _app.js

like image 93
jnm Avatar answered Oct 16 '25 21:10

jnm



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!