I am getting getSingleProduct function from context . and passing items id . This returns array of 1 object. Now I want to pass this item into this.state.singleItem above but I get this error.. I have also tried to store this data into context.js 's this.state but same error. If I create function above and execute this code. it says that contex is not defined .
export default withRouter(
class Details extends Component {
constructor(props) {
super(props);
this.state = {
id: this.props.router.params.id,
singleItem: [], // I want to store item here
};
//this.getItem();
}
static contextType = ProductContext;
getItem = (item) => {
if (this.state.singleItem.length === 0 && this.context) {
this.setState(() => {
return {
singleItem: item,
};
});
console.log("executed?");
}
};
render() {
const { getSingleProduct } = this.context;
const item = getSingleProduct(this.state.id);
if (this.state.singleItem.length === 0) {
this.getItem(item);
}
console.log(this.state.singleItem);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Doesn't seem correct to me to use this methods directly in the render method as you are invoking a this.setState. So probably that is your issue (hard to tell without a codesandbox).
So what you could try, is to wrap all of that state-handling-code and put it inside a componentDidMount or componentDidUpdate call as it corresponds with the react lifecycle for class components.
So it would end being something like this:
constructor(props) {
super(props);
this.state = {
id: this.props.router.params.id,
singleItem: [], // I want to store item here
};
/* Binding function to be able to handle state modifications from there */
this.getItem = this.getItem.bind(this);
}
componentDidMount() {
const { getSingleProduct } = this.context;
const item = getSingleProduct(this.state.id);
/* No need to validate this.state length because this method is called only before the first render */
this.getItem(item);
}
For more info about class components lifecycle you can check this link.