如何在 React JS 中使用可选负载进行 api 调用

How to make api call with optional payload in React JS

我正在尝试使用 AXIOS 在 React JS 中调用 API。当 productID 具有值时,我需要将有效负载作为可选发送。

    This is my service.js file
    
fetchProducts: (payload) => put(`/products`, payload),
fetchProductsProductID: (params, payload) => put(`/products`, payload, { params }),

products.js

       useEffect(() => {
            if (productID) {
                CommonSrv.fetchProductsProductID(
                    { productID: productID },
                    {
                        data: data,
                    },
                )
                    .then((resp) => {
                       console.log(resp)
                    })
                    .catch((err) => {
                        console.log(err)                  
                      });
            } else {
                CommonSrv.fetchProducts({ data: data })
                .then((resp) => {
                    console.log(resp)
                 })
                 .catch((err) => {
                     console.log(err)                  
                   });
            }
        }, [])

在 then 和 catch 块中,我需要使用相同的条件。由于 productID,我重复了很多我的代码,我怎么能简化这段代码呢。

你可以尝试类似的东西!

(productID ? 
   CommonSrv.fetchProductsProductID(
      { productID: productID },
      {
         data: data,
       },
    )
    : 
    CommonSrv.fetchProducts({ data: data }))
).then(.....).catch(...)