I got some cart synchronization issues, what would you do?

Issue #1: Cart synchronization on the front end. Scenario: A user opens a tab where a cart is displayed but already has a product page opened in another tab, the user decides to add the item to the cart and now the cart tab is stale (Major UX issue). Intended behaviour: Every instance of the cart on the web is up-to-date Potential solution: 1. Set state to loading 2. Establish a WebSocket connection to the server 3. Load data from the db once the connection is open 4. Populate the state with the items and stop loading 5. If the WebSocket connection closes, go back to step 1. (Also, possibly incorporate a timestamp that is checked on the DB to see if it is up to date on checkout) Issue #2 DB synchronization with the CMS The DB stores items on the cart, identified by their UUID/SKU An admin can delete an item from the collection of items which results. Which means the cart has an item that no longer exists. Intended behaviour: the item is removed from the array in the DB Potential solution: Set up a webhook within the CMS that hits the Next.JS API that removes the product from the table of products causing cascading delete which removes it from the array. Also, here’s the diagram I drew on Excalidraw that got me thinking about this mess
4 Replies
abcdef
abcdef17mo ago
@Otar Websocket seems overkill for this. Another solution could be to keep the state in local storage and listen for the window storage event. https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event 1. Save cart data to localStorage when a user adds or removes an item from the cart. 2. Read cart data from localStorage when the cart component mounts or when the cart is updated. 3. Use the storage event to listen for localStorage changes and update the cart state accordingly.
sheng2808
sheng280817mo ago
i just do a invalidate for mine
thescotsmav
thescotsmav17mo ago
For the add-to-cart sync, I'd possibly fetch the data with useQuery. By default it would refetch the data when the second tab came back into focus. So the cart would be stale while the tab isn't in focus, but is re-validated once as it's back in focus. I assume for the second part (getCartItems or something) the server is looking up each item by UUID and returning an array of products (titles, prices, number in cart etc.), rather than returning the ID array and having the client walk through the array and fetch the product data? At this point, if the server found something wasn't there anymore, marked as disabled/deleted would do the cascading delete and probably invalidate any cached pages.
Otar ✞
Otar ✞17mo ago
Makes sense. Thank you guys!
Want results from more Discord servers?
Add your server