Hello everyone, I am having an issue with React.
I am passing a state as props called “CartAmount” from my app.js down to another component. When it passes and the console.log() is called, it correctly displays 0.
I am trying to write a function where it adds 1 to the CartAmount state. but however I try and write this function it tells me that “Cannot read property ‘state’ of undefined”
this.state = {
CartAmount: {},
propdata: {},
};
}
componentDidMount() {
console.log(this.props.CartAmount)
}
render() {
//The function that is the problem child
function addtocart(CartAmount) {
CartAmount.setState({ CartAmount: this.state.CartAmount + 1 })
}
React has one way data flow, you can’t update the state of the parent from a child component. However you can do this is by passing an updater function to the child component that updates the state in the parent component itself. like this,
Thank you for the reply!
So I will try your solution I just wanted to address the issues.
I have CartAmount: {} as an empty object because I have it passing from my app.js. When I do console.log(this.props.cartamount) it says 0, so I figured it wasn’t an issue.
What should I set it to? 0? null?
2.
Will do!
this.props.cartAmount = 0 // passed from parent component
this.state.cartAmount = {} // local state of child component
the second one is the local state of the child component and not the value passed down as prop. So you are trying to add
cartAmount = {} + 1
So you should set it as 0 instead of {}.
But this will only update the local state of the child component. the parent component will still have the value 0.
You need to use the mehtod i posted to solve your issue.
I couldn’t ask for better help. I read though your notes and your code quite thoroughly, then I incorporated in into my code.
I am still getting one error, I feel like it’s a small one.
The function of updateCart() is not being passed to my services component, it’s returning undefined.
My code is here on codesandbox :
I think the problem is in using React-router in my app.js
You are using font awesome and bootstrap the wrong way, you need to install the npm packages for it. there are a lof of missing dependencies in your code sandbox.
I just dumped the code there so you could see. I am not using that to develop, I am just using my VS code editor.
So I wouldn’t worry about those. There’s a couple of import statements left over from some previously tried things too.