What is the best way to create pages that showcase 10 posts each?

Currently, I am facing a challenge with displaying 100 posts using the Fetch API on one single page. I am looking for a way to create separate pages where each page would showcase only 10 posts.

Below is my existing JavaScript code:

      fetch('https://jsonplaceholder.typicode.com/posts')
       .then((res)=>res.json())
       .then((data)=>{
       let output = '<h2 class="posts"></h2>';
       let i=0;
       data.forEach(function(thePost){
        output += `
         <div style="background-color: gray;margin- 
       right:60px;width:300px;height:350px;border-radius: 30px;display: 
       inline-block;overflow: hidden;"  class="post" id=item${i}>
          <h3 style="padding:10px;color:white;">${thePost.title}</h3>
          <p style="padding:10px;color:white;">${thePost.body}</p>
        </div>
      `;
      i++;
      //if (i==3){`<br> <br>`}
    });
    document.getElementById('posts').innerHTML=output;

});

You can view how the div posts appear here.

Answer â„–1

One way to accomplish this is by splicing the array and extracting only the first 10 elements using the splice method.

data = data.splice(0, 10);

Here is the complete code snippet:

fetch('https://jsonplaceholder.typicode.com/posts')
       .then((res)=>res.json())
       .then((data)=>{
       let output = '<h2 class="posts"></h2>';
       let i=0;
       data = data.splice(0, 10);
       data.forEach(function(thePost){
        output += `
         <div style="background-color: gray;margin- 
       right:60px;width:300px;height:350px;border-radius: 30px;display: 
       inline-block;overflow: hidden;"  class="post" id=item${i}>
          <h3 style="padding:10px;color:white;">${thePost.title}</h3>
          <p style="padding:10px;color:white;">${thePost.body}</p>
        </div>
      `;
      i++;
    });
    document.getElementById('posts').innerHTML=output;

});

Another approach can be utilizing the pagination feature provided by jsonplaceholder, allowing you to fetch a specific number of posts based on the page number and limit specified in the query string parameters.

To achieve this, you can adjust your request URL as follows:

https://jsonplaceholder.typicode.com/posts?_page=0&_limit=10

Below is the full code implementing this method:

fetch('https://jsonplaceholder.typicode.com/posts?_page=0&_limit=10')
       .then((res)=>res.json())
       .then((data)=>{
       let output = '<h2 class="posts"></h2>';
       let i=0;
       data.forEach(function(thePost){
        output += `
         <div style="background-color: gray;margin- 
       right:60px;width:300px;height:350px;border-radius: 30px;display: 
       inline-block;overflow: hidden;"  class="post" id=item${i}>
          <h3 style="padding:10px;color:white;">${thePost.title}</h3>
          <p style="padding:10px;color:white;">${thePost.body}</p>
        </div>
      `;
      i++;
    });
    document.getElementById('posts').innerHTML=output;

});

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

Access AWS Lambda environment variables in Node.js using webpack

Looking to access environment variables in Node.js with Webpack? When trying to access them using process.env null values are returned. ...

Combining JSON fields and searching based on the combined value within MarkLogic

In the JSON format provided below, I have stored a person's first name and last name along with their nickname. { "Person": { "Records": [ { "nameType": "Primary", "firstName": "Sagar", "lastName" ...

Access the configuration of a web browser

I am in the process of creating a website where I need to prompt the user to enable JavaScript. Is there a way for me to include a link to the browser's settings page? Here is an example: <noscript> <div>Please enable JavaScript &l ...

Dealing with Errors When Working with Angular Promises

Currently, I am in the process of mastering promises within Angular. In my code snippet, I have two "GET" requests that I need to execute sequentially. Everything is functioning properly, but I'm unsure about how to handle errors in this scenario. If ...

Repeated information displayed in modal pop-ups

HTML <a class="btn" data-popup-open="popup-1" href="#">More Details</a> <div class="popup" data-popup="popup-1"> <div class="popup-inner"> <h2>Unbelievable! Check this Out! (Popup #1)</h2> ...

What exactly does the combination of {on, attrs} create within Vue/Vuetify?

Although this question may have been asked before, I am still struggling to grasp its meaning. Can you help me understand it better? <v-dialog v-model="dialog" width="500" > <template v-slot:activator=&quo ...

The alignment of the label button within the form-group is being set to the top

While using Bootstrap 4, I encountered an issue with aligning the save button in a form group because there was no label at the same level. Despite trying to follow an example from here, I still had to hard code margin-top to prevent the button from bein ...

Managing absence of ID field in Prisma and retrieving data from API request

When fetching data from an API, my approach looks like this: async function getApiData() { const promises = []; for (let i = 0; i < PAGE_COUNT; i++) { const apiData = fetch(...); } const apiData = await Promise.all(promises); return apiDat ...

The value produced by the interval in Angular is not being displayed in the browser using double curly braces

I am attempting to display the changing value on the web page every second, but for some reason {{}} is not functioning correctly. However, when I use console.log, it does show the changing value. Here is an excerpt from my .ts code: randomValue: number; ...

ng-options do not refresh automatically when modifying elements in the array

Having trouble updating the data in a select list? It seems that when selecting 'test', the value retrieved from the API is 'ÅšlÄ…sk' even though it's not listed. For example: I select 'test' but it shows as 'ÅšlÄ ...

Revising HTML content when Angular array is modified

I have a code snippet below where I am updating the value of an object in the first item of an array. However, I'm struggling to find a way to "refresh" the HTML view so that the changes are immediately reflected on the browser. var dataArr ...

Animating the maximum height causes a delay in the performance of other elements

Attempting to adjust the maximum height of a ul. When the max-height property changes (via toggling a class), the height shifts immediately, while the items below the ul maintain the animated height as expected. var expander = $('.skill-expand&apos ...

Issue Encountered in NodeJS While Processing Multiple GET Requests

I have been developing a web application that utilizes a database containing game data. When a user clicks on a game, a GET request is made to an API to retrieve additional information for the selected game. My goal is to ensure that users can access detai ...

Authenticate yourself as a user or an organization on mongodb

I am currently developing an application that requires user registration and login, as well as organization registration and login. I have implemented the use of Node.js Passport with a local strategy for authentication. While I have successfully created t ...

Ways to update the div's color according to a specific value

Below are the scripts and styles that were implemented: <script src="angular.min.js"></script> <style> .greater { color:#D7E3BF; background-color:#D7E3BF; } .less { color:#E5B9B5; background-co ...

Troubleshooting issue with multer code failing to save files in designated directory within nodejs server when using reactjs frontend

I'm facing an issue while trying to upload a photo into my server folder. Even though the submission process adds the picture to my database, it does not display the image in my server folder. The frontend of my application is built using React JS, an ...

Incorporating ajax and jquery into html: Step-by-step guide

Previously, I inquired about implementing a show/hide functionality for a div that only renders when a specific link is clicked. (View the original question) Following some advice, I was provided with jQuery and AJAX code to achieve this: function unhide() ...

The Strapi plugin seems to be encountering an issue as the API is not reachable, leading to a

In an attempt to create a custom API in Strapi backend, I developed a plugin called "test" for testing purposes. However, when trying to access the test response in Postman, it displays a 404 error stating that it is not accessible. Let me provide you wit ...

The middleware in Express.js is failing to execute the next function

I have been attempting to run a post function that contains a next(); within the code. To solve this issue, I have exported the function's definition from another file and am trying to call it through an express router. Unfortunately, the function is ...

Tips for looping through nested JSON data in Google Sheets

In my attempt to iterate through the nested "line_items" element in a JSON response triggered by a post event, I aim to populate a Google Sheets spreadsheet using Google Apps Script. My objective is to write the elements within each "line_item" into new ro ...