Retrieve data depending on the conditions set in the if statement

I am currently working on a demo app that retrieves data from the Chuck Norris jokes API. I have included a variable in the endpoint to specify 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 variable is used to capture the user's preferred joke category. If no category is chosen, a random joke is loaded. In such cases, the endpoint changes to -

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

Now, my question is how can I dynamically set the endpoint based on an if statement, similar to the following:

if(selectedCat) {
fetch(someAddress)
} else {
fetch(anotherAddress)
}

Answer №1

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

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

fetchJoke(url)

In order for the code to function properly, you must also include a url parameter in the fetchJoke function that will be used by the fetch function.

Answer №2

To improve efficiency, consider dynamically generating the URL rather than adding fetch in an if condition.


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(jsonObject => {
      this.joke = jsonObject.value;
    })
    .catch(error => {
      console.log(error);
    });
}

Alternatively, you can do:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How does the single-threaded nature of Node.js handle an abundance of concurrent requests?

I'm currently delving into the world of nodejs, trying to wrap my head around its single-threaded nature. Here's a pondering I have: Let's say I implement a non-blocking method and we have 20000 concurrent requests flowing in. If one request ...

underscore.js does not allow data to be manipulated outside of the _.each

Struggling to get my head around utilizing the underscore loop in jQuery's $.ajax function for retrieving a JSONp file... Within the success section, I have the following code snippet: success : function(response) { var dataResp = '' ...

Is it possible to restrict the movement of the dialog to stay within the boundaries of the window

html: <div id="dialog" title="Past Issues"> </div> Jquery: $( "#dialog" ).dialog({ height: 900, width:1200, modal: true, }); Currently facing an issue where the dialog can be dragged outside of the window are ...

Upgrade your development stack from angular 2 with webpack 1 to angular 6 with webpack 4

Recently, I have made the transition from Angular 2 and Webpack 1 to Angular 6 and Webpack 4. However, I am facing challenges finding the best dependencies for this new setup. Does anyone have any suggestions for the best dependencies to use with Angular ...

Tips for Navigating and Scrolling to an Element by its ID in a Next.js Page Enhanced with AnimatePresence

Currently, I am utilizing Framer Motion to add animations to the page transitions in a Next.js project. However, when implementing AnimatePresence, it seems to interfere with the navigation to specific elements using hash links (id). The seamless transitio ...

JavaScript: Locate web addresses within a block of text and convert them into clickable hyper

How can we convert the following PHP code to JavaScript in order to replace URL links inside text blobs with HTML links? A jsfiddle has been initiated. <?php // The Regular Expression filter $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a- ...

Using Selenium in JavaScript to upload an image is a straightforward process

I am trying to automate the process of uploading a picture using Selenium with the following script: driver.findElement(By.id(`avatar-upload`)).sendKeys(`/home/user/Desktop/smg935-0hero-0930.jpeg`) But I keep receiving this error: ElementNotInteractable ...

What is the best way to create a grid item that maximizes the available space in ReactJS Material-UI?

Currently, I am working with the material-ui grid system in a reactjs project. In a column grid container layout, my goal is to display two grid items and have a third item fill up the remaining space between them. Essentially, I want it to look like this: ...

The art of deciphering a returned object in jQuery

Recently, I've been working with this jQuery code snippet: $.ajax({ type: "POST", url: "/problems/vote.php", dataType: "json", data: dataString, success: function ...

How to create a Bootstrap panel that collapses on mobile devices and expands on desktop screens?

Is there a simple way to remove the "in" class from the div with id "panel-login" when the screen size is less than 1199px (Bootstrap's xs, sm, and md modes)? I believe JavaScript or JQuery could be used for this, but I'm not very proficient in e ...

automatically loading data using jquery

I am currently utilizing a windows service along with an html+j query page to interact with a web service. Whenever a Document is scanned on our device, I aim to display: name, country, and Passport number on our webpage. Although I have successfully a ...

Jasmine: Ways to invoke a function with a specific context parameter

Looking for guidance as a newbie to Jasmine on calling a method with context as a parameter. Example: function locationInit(context) { } Appreciate any help and advice! ...

What is the reason for the lack of arguments being passed to this Express middleware function?

I have been developing a middleware that requires the use of `bodyParser` to function, however I do not want to directly incorporate it as a dependency in my application. Instead, I aim to create a package that includes this requirement and exports a middl ...

Take users to another page upon form submission

I'm working on a React form using Typescript and Material-UI. Here's an example: import React, { useState } from "react"; import TextField from "@material-ui/core/TextField"; import { createStyles, makeStyles, Theme } from &qu ...

Illustrating an endless cycle in Vue for continuous updating loop

In our intricate system with deep nesting and extensive use of Vuex within Vue components, I frequently encounter the warning message, [Vue warn]: You may have an infinite update loop in a component render function. Finding these infinite loops can be quit ...

Obtaining the jqXHR object from a script request loaded within the <head> tag using the <script> tag

Is it possible to retrieve the jqXHR object when a script loaded from a script tag within the head tag? function loadScript(url){ const script = document.createElement("script"); script.src = url; // This line will load the script in the ...

JavaScript alert system

Seeking advice on a situation. Here's the scenario I'm facing: In a messaging platform, I have an array of users who are currently online. When a new user joins the chat, I want to notify the first user in the array. If there's no response w ...

Is the && operator being utilized as a conditional statement?

While following a tutorial, I came across this code snippet that uses the 'and' operator in an unusual way. Is this related to React? Can someone provide an explanation or share documentation that clarifies it? {basket?.length > 0 && ...

The Node API is unresponsive when using Postman or accessing through the browser, as it is not returning any status code. However, no errors are displayed when

I am currently working on developing a Node API for an employee department model. I have created various requests such as 'GET', 'PUSH', 'PATCH', and 'DELETE' for both the employee and department endpoints. This deve ...

Display a Bootstrap input button group addon, where the first button has rounded corners only after the second button has been hidden

I am working on a button group and need to hide the second button dynamically. However, I am facing an issue where the first button has a 90° border. How can I adjust the code below to display button 1 with a rounded border? If I decide to hide "button ...