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
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);
});
}
Source:stackexchange.com