What is the best way to showcase 100 json data entries within an HTML document?

Starting from scratch with html, css, and javascript, I've embarked on a basic learning project. Within this project, I plan to create two main pages: a list page and a detail page. The list page will showcase posts on the html screen, featuring only the title and body of each post. To achieve this, I am fetching post data from https://jsonplaceholder.typicode.com/posts

Here is my HTML code for the list page:

<!DOCTYPE html>
<html>
    <head>
        <script src="fetch.js"></script>
        <title>List</title>
    </head>
    <body>
        <a>
            <h3><span id="title"> </span></h3>
            <p><span id="body"></span></p>
        </a>  
    </body> 
</html>

As for my javascript code:

const api_url='https://jsonplaceholder.typicode.com/posts/1';

async function getISS(){
   const response = await fetch(api_url);
   const data= await response.json();
   const { title, body } = data;


   document.getElementById('title').textContent=title;
   document.getElementById('body').textContent=body;
}

getISS();

The current implementation solely displays the post with ID number 1 as demonstrated in this output. My question now is how do I proceed to list all post titles and bodies? Do I need to implement some form of loop to achieve this task considering there are 100 posts in the JSON dataset that I wish to display?

Answer №1

const api_url='https://jsonplaceholder.typicode.com/posts/';

async function fetchPosts(){
   const res = await fetch(api_url);
   const data= await res.json();
   const { title, body } = data;

    let postContent = data.map((post,index)=> {
      return`<a>
            <span> post: ${+index+1} <span>
            <h3><span class="title"> ${post.title} </span></h3>
            <p><span class="body"> ${post.body} </span></p>
        </a>
        `
    })
   document.querySelector('body').innerHTML=postContent.join('');
}

fetchPosts();
    <body>

    </body> 

Answer №2

In my approach with React, I leverage the map function on the data array to achieve this. The same concept can be applied using JavaScript and HTML. The basic idea is to iterate over each item in the data array and generate a new element. It would look something like this:

const books = [{title: "Book 1", id: 1}, {title: "Book 2", id: 2}]
books.map((book) => //create the element);

When working with an API, books represents the response received from the API (which is expected to be an array)

Answer №3

give this a try in JS:


async function retrieveData() {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts');

  const data = await response.json();
  let title = '';
  let body = '';
  data.map((item) => {
    title += item.title;
    body += item.body;
  })

  document.getElementById('title').textContent = title;
  document.getElementById('body').textContent = body;
}

retrieveData();

Answer №4

Make sure to double-check the API endpoint link you are using:

const api_url='https://jsonplaceholder.typicode.com/posts/1';

By specifying "/1", you are indicating that you want to retrieve the post with id 1.

Consider omitting /1 from the api_url variable, so it appears like this:

const api_url='https://jsonplaceholder.typicode.com/posts';

Keep in mind that this will return a JSON array of posts, requiring adjustments in your JavaScript code to display all fetched posts accurately from the API.

I hope this information proves helpful.

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

Guide on how to iterate through the list of users within the component

Hello, I'm fairly new to working with react and I've encountered a challenge regarding implementing a loop within this component to display a list of all users. Despite trying numerous approaches, I haven't been able to figure it out. colum ...

Angular does not recognize the function element.sortable

I'm attempting to utilize ui.sortable in order to create a sortable list. Despite following the instructions provided at https://github.com/angular-ui/ui-sortable, I am still encountering an issue and receiving the following error message: TypeError: ...

Enhance your Kendo UI File Manager by incorporating image uploading and folder renaming capabilities

Currently utilizing the kendo UI file manager to navigate through my files and images. According to telerik documentation, only the functions to add folders and remove files and folders are supported. However, I am in need of the ability to rename both f ...

Steps for resetting the counter to 0 following an Ajax Refresh or Submission to the database

I have been working on a code that successfully sends multiple data to a MySQL Database using JQuery Ajax. Everything works smoothly, but I encountered an issue when trying to refresh the page with ajax and add a new record; it populates the number of time ...

Tips for showcasing MySQL JSON data

There is a table in my database called purchase, where I insert data in JSON format. The JSON format contains multiple sets of data, for example, "products" has 2 items. https://i.stack.imgur.com/NJ5qz.png [{"products":["Asulak Silver 7","Print Gum MAP N ...

"Mastering the art of passing variables within the index parameter for JavaScript push method

I need help passing a variable inside index in JavaScript push while working with Angular. Here is my current code: angular.forEach(Val, function (Value,Key) { angular.forEach(Value, function (Value1,Key1) { saveDetailArr.push({ 'option_i ...

The Next.js React app is constantly loading without any interruptions

Just diving into Next.js and attempting to transform a single HTML page into a Next.js website in order to integrate sanity. Managed to import all necessary assets, but stuck with the persistent preloader issue. After inspecting elements, noticed that a fi ...

NodeJS API integration failure during ReactJs login attempt

Currently, I am tackling a small project on implementing user login functionality in ReactJs with Nodejs and Express-session. The issue I am facing is that my front end (React login page) isn't functioning properly. Below is the Fetch API code snippet ...

Creating an autocomplete feature with just one input field to display information for two to three additional input fields

I'm working on implementing an autocomplete feature similar to this example: . Feel free to test it out with the code snippets provided: 1000, 1001. I've successfully implemented the autocomplete functionality where typing in Pa suggests Paris. ...

What is the method for inputting a JSON array list into the application.properties file in a spring-boot application?

Is there a way to efficiently write a Json array list within the application.properties file in a spring-boot application, allowing for easy retrieval of the entire Json data? Here is an example of a json object: { "userdetail": [ { "user": "us ...

Limit access to Google Fusion Table to specific types of maps. Eliminate Google Fusion Table for selected map formats

Currently, I am in the process of creating a web map using the Google Maps Javascript API. My objective is to display a Google Fusion Table containing buildings in Boston exclusively on a stylized map named "Buildings." When I switch to the Buildings map t ...

Having issues with my script in Node.js where I am getting a TypeError when trying to make a https request. How can I properly

I am attempting to execute a curl request using node.js curl \ -H 'Authorization: ABC XYZ' \ 'https://api.wit.ai/message?q=Test' (Authorization has been replaced) This is the node.js code I tried: var https = require(" ...

How can Angular prevent displaying 404 errors in the console by utilizing fallback mechanisms?

I have implemented a custom directive that loads a backup image source if the initial one returns a 404 error. Here is the code for the directive: .directive('errSrc', function() { return { link: function(scope, element, attrs) { ...

What is the best way to start the server when the files are located in separate directories?

I have organized my project into two separate folders, one for the client and one for the server Is there a way to use npm start to simultaneously run both the frontend and backend scripts? Check out the screenshot below: View of Two Folders in my Projec ...

Implementing custom styles in JavaScript according to the specific browser or platform

When it comes to adding multiple css styles to a dom element and ensuring compatibility across different browsers, which approach is more optimal for performance? Combining all prefixed css properties together, allowing the browser to decide which one ...

Exploring the power of promises in the JavaScript event loop

Just when I thought I had a solid understanding of how the event loop operates in JavaScript, I encountered a perplexing issue. If this is not new to you, I would greatly appreciate an explanation. Here's an example of the code that has left me scratc ...

AngularJS - Setting an initial delay for ng-bind

We have a span element with the following attributes: <span role="link" ng-show="showLink()" ng-bind="textLink"></span> (Just an fyi: we implemented a fade-in, fade-out animation for this link, hence the use of ng-show instead of ng-if) The ...

Simple steps for transforming an array into a JavaScript object

Here is an array resembling a JSON structure with n elements: const mainData = [ { phrase: "Phrase 1", categorynumber: 1, optionnumber: 1, }, { phrase: "Phrase 2", categorynumber: 1, optionnumber: 2, }, ...

Displaying the focus icon on the active tab using Angular Material

I am currently utilizing Angular material to dynamically generate tabs in my HTML code. I'm trying to display a drop arrow icon on the active or selected tabs, but I am facing some challenges with the implementation. Below is the code snippet I have ...

The JavaScript code is not running as expected!

i have this index.html file: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" ...