简体   繁体   中英

How to reload the component when the state of another component changes React

I am making an e-commerce app with react and firebase the <cart /> component contains two child components

1- <BasketItem /> (this component will be duplicated as many Items as the user adds to the cart and it has the functionality to let user modify the quantity of the Item )

2- <OrderSummary /> (this component will show the user the the total price of his cart and the shipping fees)

of course all the data of the items and the total will be gotten from the database (I am using firestore) but but the issue is when the user update the quantity of the items from the <BasketItem /> component the total price from the <OrderSummary /> did not get updated as well because the database call will be done already and no way to recall the function that gets the data from the database because there is no parent- child relation between the two components and I can't pass props between them I have tried to use react-context-api for this but that did not solve the issue because the up to date is on the database and the only way to update the total value is to refresh the page and this is not a good user experience to have.

In any React all, all affected UI components should be updated when you update the cart information in the state (as they should all be observing that).

When using Firestore, you'll use a so-called CQRS pattern, where the updates sent to the database, are a separate stream from the listeners to the database. You'll typically add listeners when you create/mount the components, so that they're always listening while the component is visible to the user.

With that setup in place, the update flow becomes:

  1. Your code write a new value to the database through the Firebase SDK.
  2. This gets written to the database on the server at some point.
  3. The servers sends this information to all other clients, and a confirmation to the client who wrote the value.
  4. This triggers the listener that you registered before.
  5. The listener updates the data in the state of the app.
  6. And that then finally triggers a repaint of the affected components.

This is the general flow, but it applies to all cases I can think of.

Usually the best practice is to have the state stored on the front-end too in the form of context-api or redux-store or simply as component's state, they try syncing this state on the front-end with DB when user triggered submit/order action.

If you had to update your DB on every quantity change, then you have to update the same on front-end state/redux-store too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM