I have a context file and state file for Products. when I try to use that context in products component it is returning undefined values
productContext.js
import { createContext } from "react";
const ProductContext = createContext();
export default ProductContext;
ProductState.js
import ProductContext from './productContext';
import { useState } from 'react';
const ProductState = (props) => {
const productsInitial = [
{
"_id": "63a4cc857f40d0063116be5f",
"user": "63a4cbfd7f40d0063116be5d",
"title": "Cassava",
"description": "On-demand sand castle construction expertise.",
"imgURL": "null",
"price": "30",
"__v": 0
},
{
"_id": "63a4ccad7f40d0063116be69",
"user": "63a4cbfd7f40d0063116be5d",
"title": "Soyabeans",
"description": "On-demand sand castle construction expertise.",
"imgURL": "null",
"price": "30",
"__v": 0
}
]
const [products, setProducts] = useState(productsInitial);
// console.log(products);
return (
<>
<ProductContext.Provider value={{ products, setProducts }}>
{props.children}
</ProductContext.Provider>
</>
)
}
export default ProductState;
ProductComponent.js (react component)
import React, { useContext } from 'react';
import ProductContext from '../context/products/productContext';
import ProductItems from './ProductItems';
console.log(ProductContext);
const ProductComponent = () => {
const context = useContext(ProductContext);
const { products, setProducts } = context;
return (
<>
<div className="col-lg-4 ">
{products.map((product) => {
return <ProductItems product={products} />
})}
</div>
</>
)
}
export default ProductComponent;
the line
const context = useContext(ProductContext);
in Products.js Component is returning undefined value because ProductContext is returning undefined
CodePudding user response:
Component that use the context must be wrapped using ProductState
component
If you don't know where to add ProductState
you can add in your entry point file.
root.render((
<ProductState>
<App />
</ProductState>
))
You can simplify the object destructuring
const { products, setProducts } = useContext(ProductContext);
CodePudding user response:
Okay, so we have to give a default value to createContext() function, like createContext(defaultValue)
so i just replaced
const ProductContext = createContext();
with
const ProductContext = React.createContext(productsInitial);
and to have that productInitials
in the productContext.js
I merged it with the productState.js