Home > Software design >  Update state if response is ok
Update state if response is ok

Time:08-26

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?

CodePudding user response:

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.

  • Related