Multiple card displays not working with Javascript Fetch API

I wrote a script that retrieves data from a URL and then organizes it into tables for display to the user. Initially, the script functioned correctly. However, I decided to enhance its flexibility by introducing two parameters - name and HTML div name where the data should be shown. The function worked properly upon the first call, but the second invocation does not seem to render any information. My projects are predominantly based on PHP, and while I am new to JavaScript, I managed to create a similar functional in PHP which functions as expected. Any thoughts on how I can resolve this issue?

function getInfoByCountry(name, displayName) {
  fetch("https://something.com/countries/" + name)
    .then(res => res.json())
    .then(data => {
      output = `
      <tr>
        <td>Total Cases</td>
        <td>${data.cases}</td>
      </tr>
      <tr>
        <td>Today Cases</td>
        <td>${data.todayCases}</td>
      </tr>
      <tr>
        <td>Deaths</td>
        <td>${data.deaths}</td>
      </tr>
      <tr>
        <td>Recovered</td>
        <td>${data.recovered}</td>
      </tr>        
      <tr>
        <td>Critical</td>
        <td>${data.critical}</td>
      </tr>
      <tr>
        <td>Active Cases</td>
        <td>${data.active}</td>
      </tr>                        
    `;
      document.getElementById(displayName).innerHTML = output;
    });
}

getInfoByCountry("USA", "USAInfo");

getInfoByCountry("China", "ChinaInfo");
<div class="table-responsive">
  <table class="table table-striped mb-0">
    <tbody id="ChinaInfo">

    </tbody>
  </table>
</div>

Answer №1

Include the return statement as shown below:

 function fetchCountryInfo(name, displayName) {
  var display = document.getElementById(displayName);
  return fetch("https://example.com/countries/"+name)
    .then(res => res.json())
    .then(data => {

      output = `
  <tr>
    <td>Total Cases</td>
    <td>${data.cases}</td>
  </tr>
  <tr>
    <td>Today Cases</td>
    <td>${data.todayCases}</td>
  </tr>
  <tr>
    <td>Deaths</td>
    <td>${data.deaths}</td>
  </tr>
  <tr>
    <td>Recovered</td>
    <td>${data.recovered}</td>
  </tr>        
  <tr>
    <td>Critical</td>
    <td>${data.critical}</td>
  </tr>
  <tr>
    <td>Active Cases</td>
    <td>${data.active}</td>
  </tr>                        
`;

  document.getElementById(displayName).innerHTML += output;

    }

    );
}

fetchCountryInfo("USA", "display");

fetchCountryInfo("China", "display");

Answer №2

To ensure the function returns an output, don't forget to include a return statement.

If you want to see the function in action, click here to access the fiddle.

function getInfoByCountry(name,displayName) {
    debugger;
  return fetch("https://jsonplaceholder.typicode.com/posts/"+name)
    .then(res => res.json())
    .then(data => {
      output = `
      <tr>
        <td>Total Cases</td>
        <td>${data.title}</td>
      </tr>
      <tr>
        <td>Today Cases</td>
        <td>${data.body}</td>
      </tr>
    `;
      document.getElementById(displayName).innerHTML = output;
    });
}

Answer №3

When adding the result using displayName as an id attribute, it is suggested to also add one for USAinfo as per the comments. Alternatively, a more efficient implementation would be to dynamically create the table and then append the result to the container.

function getInfoByCountry(name, displayName) {
  fetch("API_URL" + name)
    .then(res => res.json())
    .then(data => {
      output = `
      <table class="table table-striped mb-0">
    <tbody>

      <tr>
        <td>Total Cases</td>
        <td>${data.cases}</td>
      </tr>
      <tr>
        <td>Today Cases</td>
        <td>${data.todayCases}</td>
      </tr>
      <tr>
        <td>Deaths</td>
        <td>${data.deaths}</td>
      </tr>
      <tr>
        <td>Recovered</td>
        <td>${data.recovered}</td>
      </tr>        
      <tr>
        <td>Critical</td>
        <td>${data.critical}</td>
      </tr>
      <tr>
        <td>Active Cases</td>
        <td>${data.active}</td>
      </tr>
       </tbody>
  </table><hr />
    `;
      document.getElementById("container").innerHTML += output;
    });
}

getInfoByCountry("USA", "USAInfo");

getInfoByCountry("China", "ChinaInfo");
table, td {
  border: 1px solid;
}
<div id="container" class="table-responsive">
  
</div>

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

What is the TypeScript syntax for indicating multiple generic types for a variable?

Currently working on transitioning one of my projects from JavaScript to TypeScript, however I've hit a roadblock when it comes to type annotation. I have an interface called Serializer and a class that merges these interfaces as shown below: interfa ...

Guide to displaying the output of a JS calculation in a Bootstrap modal dialog box

I have a HTML and JavaScript code that determines the ideal surfboard for the user based on their input data (style, experience, height, weight) and displays the recommended surfboard type. Here is the initial code snippet I attempted to use: function c ...

Retrieving a specific id from a meteor-rendered template to access a collection field

UPDATE: I have recently included additional code for clarification, marked as * NEW *. To explain the functionality of this code - it involves inputting a series of data into a collection named posts. The displayed output on the postsList template occurs w ...

Styling: Ensuring my sidebar does not overlap with my main content on the webpage

Currently, I am working on arranging my sidebar and map so that they are displayed side by side instead of the sidebar appearing on top of the map (as shown in the image). I'm seeking advice on how to achieve this layout using CSS because I have been ...

Obtain a collection of data- attribute values using jQuery

I am attempting to extract all the values from the data-hiringurl attributes found on this particular page . When I used var data = $("li").attr('data-hiringurl'); and var data = $("li").data('hiringurl'); in the console, an error mess ...

Aligning inline form controls with Bootstrap and Syncfusion widgets

I'm facing a challenge aligning the Syncfusion JavaScript widget - a dropdownlist - to be displayed inline with the label. I am using Bootstrap 3. I haven't been successful in achieving a nice alignment, meaning getting the middle of the label p ...

Integrate a new Webview Window into an existing iOS App to display locally stored HTML content

Integrate a WebView Window into an existing iOS application to display locally stored HTML content. I have already completed the feed RSS feature in my app, but now there is a requirement for a section that can be easily updated... ...

What is the right way to send a success response from Express JS to Backbone when logging out a user?

I'm currently learning how to work with Express JS and Backbone. On the server side using Express.js, I have this code snippet for logging out a user: app.get('/logout', function(req, res) { req.logout(); res.send('How can I ...

Error in TypeScript: Typography type does not accept 'string' type as valid

As I attempt to implement the Typography component from material-ui using TypeScript, I encounter a perplexing error message TypeScript is throwing an error: Type 'string' is not assignable to type 'ComponentClass<HTMLAttributes<HTMLE ...

Expand the display on mobile devices

What is the solution for adjusting a table on mobile view? I am aiming to achieve: https://i.sstatic.net/YkKAW.png However, it currently looks like this: https://i.sstatic.net/GW5mX.png Here are my code snippets: <script src="https://cdnjs. ...

Unable to execute Protractor using Node.js command line

Hi there! Currently, I am in the process of setting up protractor for the very first time using Node.js. I found detailed instructions on how to do this on the AngularJS website under the section "Running E2E Tests": https://docs.angularjs.org/tutorial Ho ...

Tips on how to eliminate focus after choosing a radio button in Angular Material?

This is a snippet from my HTML template file, which includes two Angular Material radio buttons. My goal is to disable the focus on the rings quickly after selecting any radio button. <div id="login-form" class="vh-100 overflow-auto" ...

How to refresh a page in React when the browser's back button is pressed

In my React project using Material-UI, I have created a simple search form. On page A, users can input values in text boxes and select options from drop-down lists and checkboxes. The results are then displayed on page B. My issue arises when returning to ...

Showcasing a variety of product titles with the help of CSS

Since the HTML is hosted on another server and I have no control over it, how can I use CSS to style certain list items? For example, The HTML on the server side: <ol> <li>Coffee</li> <li>Milk</li> <li>Orange Juice< ...

What is the best way to clear radio button selections in a form using reactjs?

I designed a survey form with 4 radio buttons for a single question. I also included buttons to submit the form and clear input fields. However, when I click on "Clear Input," the checked radio buttons do not get cleared. How can I achieve this using the r ...

Displaying the usernames of the users on the interface leads to encountering the 'Undefined Index' error

Hey there, I'm currently facing an issue with displaying the user's first name as a greeting message on index.php. I want it to say 'Hello, (user's first name)', but since I'm fairly new to PHP, I'm struggling to make it ...

Obtain asynchronous state in VueJS without the need for intricate v-if conditions

I am working on an application that heavily relies on Vue-Router and Vuex for state management. Within the Dashboard component, important user information is displayed. This data is fetched asynchronously from a database by Vue and then stored in Vuex. T ...

(Enhancing Angular) Capture HttpResponse errors and seamlessly proceed with the Observable

There's a dropdown text box with type-ahead search functionality. Valid item names prompt the expected list of items in the drop-down menu, while invalid entries trigger a 400 error response from the API. This error is caught by the HttpErrorIntercept ...

Show one line of text at a time with a pause in between each one

On my HTML page, I am looking to showcase text lines in succession with a delay. The unique condition is that when the second line appears, the color of the first line should change. Then, as the third line emerges, the color of the second line should also ...

Positioning Elements Absolutely in Relation to List Items

I am looking to style a list item by adding background-color, border, and other properties. Below is the CSS and HTML I have tried so far. Additionally, I want to use the div element to position more absolute elements in relation to the li > div. ul { ...