Search code examples
reactjsreact-hooksmaterial-uicommercecommerce.js

Material ui Loading Button Loads all button onClick in React js loop (using map)


So, I was working on commerce.js API. But when I press add to cart, it takes a bit of time to update the cart items number (from API) so I thought I should add a loading button until the cart items load. I found LoadingButton from @mui/lab so I used it. but the problem is even though that button is inside the loop when pressing onClick all the other button also goes to the loading state. IDK am I missing something or is my coding false?. Please check below & help me. Thanks. :)
Here is the main problem.

material ui

Here is the app.js where you can see loading state & other API fetching
enter image description here

products component in app.js. you can see I passed down the products & loading props
enter image description here

products loop & props down to product component
enter image description here

finally the cart loading button in the product component with loading props. it works but all other buttons also loads at the same time.
enter image description here


Solution

  • What you can do is create a map in which you store the loading state for each cart. So cartLoading will have the following shape:

    {
      "product-one-id": true,
      "product-two-id": false,
    }
    

    So change the state to const [cartLoading, setCartLoading] = useState({});

    At handleAddToCart, change the two setCartLoading calls so that they update only one key of the state:

    setCartLoading(oldState => ({...oldState, [productId]: true}));
    ...
    setCartLoading(oldState => ({...oldState, [productId]: false}));
    

    Then, at the <Grid> inside the Products component, change cartLoading={cartLoading} to cartLoading={cartLoading[product.id] || false}

    This is just one way to do it though. You can also handle the state inside your Product component.