Search code examples
javascriptecmascript-6template-literals

Conditional statement within template literal concatenation?


I am making an API call like this:

posts: (ppp, page) =>
    requests.get(`/wp-json/wp/v2/posts?per_page=${ppp}&page=${page}`)

I am not always going to be passing in posts per page or page though, so I would like to only concatenate those variables if they exist. I tried below but I can't seem to get the formatting down:

requests.get(`/wp-json/wp/v2/posts?`${ppp ? `'per_page='${ppp} : `''` `${page} ? `'&page=' ${page}` :''`)

Solution

  • Besides that your second solution contains syntax errors, it also isn't the most readable way to do that...

    But why are you trying to reinvent the wheel?

    You can use the URL API which is available both on the client-side and in Node.js:

    posts: (ppp, page) => {
      const url = new URL('/wp-json/wp/v2/posts')
      if(ppp) url.searchParams.append('per_page', ppp)
      if(page) url.searchParams.append('page', page)
      return requests.get(url.href)
    }  
    

    However, if you can't use the above solution for some reason, you can still implement a similar algorithm that works like the above solution. For example, you can use an array:

    posts: (ppp, page) => {
      const urlParams = []
      if(ppp) urlParams.push(`per_page=${ppp}`)
      if(page) urlParams.push(`page=${page}`)
      return requests.get(`/wp-json/wp/v2/posts?${ urlParams.join('&') }`)
    }  
    

    Or an even more flexible solution:

    posts: (ppp, page) => {
      const urlParams = {
        per_page: ppp, //per_page=ppp
        page,          //page=page
                       //Add more here if you want
      }
      return requests.get(`/wp-json/wp/v2/posts?${ 
        Object
          .entries(urlParams)
          .filter(([k, v]) => v) //If value is truthy
          .map(e => e.join('=')) //Concatenate key and value with =
          .join('&') //Concatenate key-value pairs with &
      }`)
    }  
    

    But, if you want to stick to you version, here's a fixed example of it:

    requests.get(`/wp-json/wp/v2/posts?${ppp ? `per_page=${ppp}` : ''}${(ppp && page) ? '&' : ''}${page ? `page=${page}` : ''}`)