Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a param as optional on GET request Axios

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
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading