0

I am just getting started with react useContext and have run into a problem i could not find solution. When the context created is called in another file it returns undefined. I have tried to research multiple answers like this and others but could not find one that fix the error.

I tried to create the CartStatusContext here and set some initial state

cartstatuscontext.jsx

import React, { useState } from "react";

const CartStatusContext = React.createContext();

function CartStatusContextProvider({ children }) {
 
    const cartDict = {
        'in_session': "false",
        'battery-level': '8' // level is 1 to 10 
        
    }  
    
    const [cartstatus, setcartstatus] = useState(cartDict);
  
    return ( 
    
        <CartStatusContext.Provider value={{ cartstatus, setcartstatus }}>
            {children}
        </CartStatusContext.Provider>
    );
}

export default CartStatusContextProvider
export {CartStatusContext}

I then tried to import and call the context in this file but it's crashing the app and i was able to confirm with a console.log print out that the CartStatusContext is coming out as undefine.

my index.jsx

import CartStatusContextProvider , { CartStatusContext } from "../components/cartstatuscontext"

 // Electron related imports
const electron = window.require('electron');
const { ipcRenderer } = electron;
const loadBalancer = window.require('electron-load-balancer');


function MainPage(){
  
 
     const [cartstatus, setcartstatus] = useContext(CartStatusContext);


}

what am I doing wrong and how can I fix the undefine error and get the CartStatusContext value?

e.iluf
  • 1,389
  • 5
  • 27
  • 69

2 Answers2

1

This

function MainPage(){
  const [cartstatus, setcartstatus] = useContext(CartStatusContext);
}

Should be changed to

function MainPage(){
  const { cartstatus, setcartstatus } = useContext(CartStatusContext);
}

Because that's how it is passed as a value to the context:

<CartStatusContext.Provider value={{ cartstatus, setcartstatus }}>
Anthony Garcia-Labiad
  • 3,531
  • 1
  • 26
  • 30
0

You’re storing an object in CarStatsContext, try storing them in an array and the code should probably work

Jad Al-Hamwi
  • 159
  • 1
  • 6