Search code examples
reactjsaxiosreact-functional-componentpayload

How to send request payload as optional to the api call in React JS Axios


I am trying to call API Using Axios in React JS. some times I will have a product ID and sometimes ill will not have a product ID. Currently, I am duplicating the code because of the product id.

This is API which is in common.js

fetchProducts: (payload) => put(`/products`, payload),

products.js

      if (productID) {
                        common.fetchProducts({
                            selectedItems: checkedItems,
                            productID: productID,
                        })
                            .then((resp) => {
                                console.log("Success",resp);
                            })
                            .catch((err) => {
                                   console.log("Failure",err);
                            });
                    } else {
                        common.fetchProducts({
                            selectedItems: checkedItems,
                        })
                            .then((resp) => {
                                console.log("Success",resp);
                            })
                            .catch((err) => {
                                   console.log("Failure",err);
                            });
                    }

and products.js component I am having few more API calls because of this Optional parameter I am duplicating the code a lot. How can I simplify this API call?


Solution

  • You can use conditional operator to reduce your code:

    common.fetchProducts(
      productID
        ? {
            selectedItems: checkedItems,
            productID: productID,
          }
        : { selectedItems: checkedItems }
    );