DEV Community

loading...

Discussion on: React Shopping Cart Tutorial and Code

Collapse
andersjr1984 profile image
andersjr1984 Author • Edited

Yikes. There is no reason to use await when setting the state. That was a noob mistake by me. Whenever you use the this.setState function, that should trigger a re-render.

I think I was doing this because I had tried to use the state in a function directly after setting the state. The official React docs warn away from this use of state, noting that the state change is not instantaneous.

Edited to add: I have pushed a new version of the shopping cart that is much more robust, has fewer errors like the one described above, and includes the use of "Firestripe" payments. Feel free to check out the github link!

2nd edit: Text directly from the React docs on setState():
setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

Forem Open with the Forem app