Reactjs Context returns undefined

Viewed 40

i need to make a global state for my application, i am trying to use react context, with class components, i have followed some videos but i cannot make it work as i need, i would like to know what i am doing wrong, and sorry if the question is not well structured, it is my first question.

My code:

/Context.jsx

import React, { Component } from "react";

const CartContext = React.createContext()

export class CartProvider extends Component{
state = {
    items:[],
    price:0
}    

render(){
    const {items,price} =this.state        
    return(
        <CartContext.Provider value={{items,price}}>
            {this.props.children}
        </CartContext.Provider>
    )
}
}

export default CartContext;

/CartScreen.jsx

import React, { Component } from "react";
import {Text} from "react-native";
import CartContext, {CartProvider} from "../context/Context";
class CartScreen extends Component {   
static contextType = CartContext
      render() {
        console.log("Context:")
        console.log(this.context)
        return (
            <CartProvider>
                <Text>CartScreen</Text>
            </CartProvider>
        );
    }
}   
export default CartScreen;

And this get from the console:

Context: undefined

however if I modify the default parameter when creating the context, the console returns the parameter

const CartContext = React.createContext("test")

Console returns:

Context: test

It's as if I'm always taking the default parameter no matter what I'm assigning to the value of the provider.

1 Answers

You have access to CartContext values from the components you pass to it as props.children.

So if you need access to context values inside CartScreen, you have to wrap it inside CartProvider.

return (<CartProvider>
          <CartScreen/>
        </CartProvider>)

And inside CartScreen you don't need to use CartProvider anymore:

class CartScreen extends Component {   
static contextType = CartContext
  render() {
    console.log("Context:")
    console.log(this.context)
    return (
             <Text>CartScreen</Text>
      );
   }
}   
Related