PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 12, 2022

[FIXED] How to add a param as optional on GET request Axios

 October 12, 2022     axios, get, javascript, rest     No comments   

Issue

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

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
}



Answered By - Mina
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing