Reputation: 117
I'm using React ContextApi to manage the state components.
I have some files in my data.js
, which has refused to display on the Details.js
page.
I know something's wrong but it's not showing me any error code and its not displaying instead its writing "Cannot read property 'id' of undefined"
import React, { Component } from 'react';
import { storeProducts, detailProduct } from './data';
const BookContext = React.createContext()
class BookProvider extends Component {
state = {
products: [...storeProducts],
details: detailProduct
};
componentDidMount() {
this.setProducts();
}
setProducts = () => {
let products = [];
storeProducts.forEach(item => {
const singleItem = {...item};
products = [...products, singleItem];
});
this.setState(() => {
return {products}
});
};
handleDetail = () => {
console.log("Hello from detail")
};
addToCart = () => {
console.log("Hello from add to cart")
};
render() {
return (
<BookContext.Provider value={{
// products: this.state.products,
// details: this.state.details,
// Destructuring all the values that is in the state property
...this.state,
handleDetail: this.handleDetail,
addToCart: this.addToCart
}}>
{this.props.children}
</BookContext.Provider>
)
}
};
const BookConsumer = BookContext.Consumer;
export { BookProvider, BookConsumer };
This is the Details.js file on the project
import React, { Component } from 'react';
import { BookConsumer } from '../context';
import { Link } from 'react-router-dom';
import { ButtonContainer } from './Button';
class Details extends Component {
render() {
return (
<BookConsumer>
{(value) => {
const {id, company, img, price, title, info, inCart} =
value.detailProduct;
return (
<div className="container py-5">
{/* TITLE */}
<div className="row">
<div className="col-10 mx-auto text-center
text-slanted text-blue my-5">
<h1>{title}</h1>
</div>
</div>
</div>
)
}}
</BookConsumer>
);
}
}
export default Details;
Upvotes: 0
Views: 568
Reputation: 11
It seems that value
argument doesn't have a property detailProduct
set. Check it first.
Upvotes: 1
Reputation: 1569
You are destructuring value.detailProduct
instead of value.details
.
Indeed in context.js
,
value={{
...this.state,
handleDetail: this.handleDetail,
addToCart: this.addToCart
}}
and state
has no detailProduct
key.
Upvotes: 1