Home > front end >  How to add a param as optional on GET request Axios
How to add a param as optional on GET request Axios

Time:09-28

I need param "similarText" to be optional ¿How can I do that? If I add value? I get warnings from linter.

export const getProducts = async (
  value: string,
  apiKey: string | undefined
) => {
  const products = await axios
    .get(`${VITE_BACKEND_URI}/products?param1=match_token&param2=match_token`, {
       params: {
       similarText: value,
       },
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'Content-Type',
      },
    })
    .then((response) => {
      return response.data
    })
    .catch((error) => {
      return error
    })
  return products
}

CodePudding user response:

For optionally adding the params, you can use spread operator, for example ...value ?? { similarText: value }.

export const getProducts = async (
  value: string,
  apiKey: string | undefined
) => {
  const products = await axios
    .get(`${VITE_BACKEND_URI}/products?param1=match_token&param2=match_token`, {
       params: {
         ...value ?? { similarText: value },
       },
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'Content-Type',
      },
    })
    .then((response) => {
      return response.data
    })
    .catch((error) => {
      return error
    })
  return products
}

  • Related