I need help with understanding state in my React app

So, after watching React tutorials from Net Ninja, I decided to create my own app where I will apply everything new I learn. I was feeling ambitious and decided to create a template/UI for an online shop.

PS He didn’t finish tutorial series yet, I’m probably going too far here :slight_smile:

  1. At start, I had 3 components. APP, one that handles states for all the content and one for product card that includes product picture and info.
  2. Then, my next goal was to create a shopping cart. That was trickier but I did manage to add/remove items from a shopping cart and display/hide it on click.
  3. My next goal was to add quantity for every product but I left that to first block adding the same product again to the cart. That seemed really easy but it didn’t work well.

Then, I discovered this.

NOTE: You will need to see the code in Content-container component, functions are addItem and deleteItem

Github: https://github.com/msimicshauma/online-shop

Now, the thing I noticed is in mentioned functions. I was doing what I learned, creating copies because we cannot mutate the state directly. So, because new stuff I tried to add didn’t work properly, I decided to console.log the copy of state (array) and the state of shopping cart after setState.

Can anyone explain why this happens? Look at the console on screenshot. I was just adding and deleting products.
I believe it has to do something with updating the state but I have no idea what. It works but it doesn’t seem right.

I know that looking and understanding someones code is hard, probably my naming sucks too. I apologize in advance. If you need something else explained, I will try.

Thank you!

I wonder if you know that setState is running in an asynchronous manner so logging may not show the real state (depending on how you’re doing it).
I got that information myself here on the forum some days ago…

1 Like

That’s why my new functions didn’t work, UI was updated but state object wasn’t. It’s kinda stupid but I’ll get used to it. That’s what you get when you first coded in C. :slight_smile:
Thanks for the info! I didn’t know about it being async.

Solved all the problems now, pushed to github. You can try it if you want. It’s nothing special, just practicing. :slight_smile: