-2

I have some demo app that fetching data from chuck norris jokes api. I'm adding variable to the endpoint which represent the joke category -

fetchJoke: function() {
  fetch(
    `https://api.chucknorris.io/jokes/random?category=${this.selectedCat}`
  )
    .then(response => {
      return response.json();
    })
    .then(jsonOBj => {
      this.joke = jsonOBj.value;
    })
    .catch(error => {
      console.log(error);
    });
}

The selectedCat is a variable that get from the user the desired joke category, if the user don't choose a category they can load some random joke. In that case the endpoint is different -

https://api.chucknorris.io/jokes/random

The question is, how can I set the endpoint based on if statement, something like this:

if(selectedCat) {
fetch(someAddress)
} else {
fetch(anotherAddress)
}
Or Ben-Yossef
  • 399
  • 2
  • 17
  • You could use inline if statements, mentioned in this thread: https://stackoverflow.com/questions/10270351/how-to-write-an-inline-if-statement-in-javascript – whati001 Jan 24 '20 at 14:50

2 Answers2

2

let url = ''
let pageUrl = 'https://api.chucknorris.io/jokes/random'

if(selectedCat) {
  url = `{pageUrl}?category=${this.selectedCat}`
} else {
  url = pageUrl
}

fetchJoke(url)

To make it work you need also to add url parameter to fetchJoke func which will be passed to fetch func

Harion
  • 225
  • 1
  • 8
1

Instead of adding fetch in if condition, create the URL dynamically.


fetchJoke: function() {
  let url = `https://api.chucknorris.io/jokes/random`;

  if(this.selectedCat) {
    url = url + `?category=${this.selectedCat}`;
  } 

  fetch(url)
    .then(response => {
      return response.json();
    })
    .then(jsonOBj => {
      this.joke = jsonOBj.value;
    })
    .catch(error => {
      console.log(error);
    });
}

OR

fetchJoke: function() {
  fetch(`https://api.chucknorris.io/jokes/random${this.selectedCat ? '?category=' +this.selectedCat: ''}`)
    .then(response => {
      return response.json();
    })
    .then(jsonOBj => {
      this.joke = jsonOBj.value;
    })
    .catch(error => {
      console.log(error);
    });
}
Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42