1

So I have kind of a different problem here. My react app has a reducer that updates the state of a cart when a product is added. As i works right now i send this updated state to an API endpoint so save it to the database.

  const addToCart = (item, quantity = 1) => {
    dispatch({
      type: 'ADD_ITEM',
      payload: { item: item, quantity: quantity },
    });
  };

My api endpoint is called by a useEffect on this function.

  useEffect(() => {
    updateCart(state);
  }, [removeFromCart, addToCart]);

So basically what I am doing is that I send the state to the db for removing and adding items to cart. But this comes with a problem. If a user adds many items to cart very rapidly the state and what is saved inn the database is out of sync.

Then I was thinking to revert the state if the response is not ok from the API endpoint. But a little unsure on how to do this. Anybody have any tips on how to solve this problem?

Nagween Jaffer
  • 180
  • 3
  • 13
  • Can we see the function definition of `updateCart` and also where `state` is defined and set. Your example code is too minimal to see help at the moment. – adsy Aug 25 '22 at 12:24
  • Its just a basic POST call to an api enpoint. The problem im having is that since i need to update the state before sending it to the database, there is no way for me to check if the response i get from the database is valid. So i need to update the state with the reducer and then send it to the database. This is why the database and state can be out of sync. –  Aug 25 '22 at 12:32
  • I am also wondering why you are using `useEffect` to accomplish this. But we need more information to provide you with a detail answer. – JnsBne Aug 25 '22 at 12:34
  • Why do you need to store this data in your state instead of sending it directly to your database? Why not send it directly with your POST request? POST calls are asynchronous so you can wrap them in `try-catch` blocks and when an error is thrown you can show some fallback UI for example. – JnsBne Aug 25 '22 at 12:37

1 Answers1

1

You should debounce the call to updateCart.

There's a lot of ways to implement a debounce on the useEffect. You can either use a library that already implements that hook or create a hook and manage the debounce yourself.

To get an overall ideia of what is debounce, you can look at this question. To understand how it works with react and useEffect, you can look at this question

A simple way is just using useDebounce from react-use and do:

useDebounce(() => {
  updateCart(state);
}, 1000, [removeFromCart, addToCart])

Where 1000 is the time for the debounce.

This way you remove the problem of having the user add and remove a lot of items and having the db out of sync and there's no need to check if the response is ok from the server.

Vencovsky
  • 28,550
  • 17
  • 109
  • 176