Utilizing Axios to filter response.data in an API request

Looking to retrieve the latest 8 products based on their date? Take a look at the code snippet below:

    const newestProducts= [];
    axios.get("http://localhost:3003/products").then(response => {
        let products = response.data.sort(function(a, b) {
            return new Date(b.date) - new Date(a.date);
        });

        newstProducts = product.slice(0,7)
    });

However, this method might not be efficient when dealing with thousands of products and only needing the newest 8.

One idea could be to add ?_limit=8 to the API call

axios.get("http://localhost:3003/products?_limit=8").then{...}

Yet, this approach also has its limitations as it fetches only the top 8 products from the array.

Is there a way to filter the products before requesting them from the server, or is storing all products in a variable first necessary?

The JSON File

      "categories": [ 
            {
            "id": 9,
            "category": "bathroom",
            "date": "2020/8/3",
            "name": "ullam basin mixer",
            "price": 160,
            "img_1": "rim_mixer_01.jpg",
            "img_2": "rim_mixer_02.jpg",
            "rating": 4.5,
            "description": "MARMO is a complete series made of 72 models, with different shapes and sizes for different functions, that keeps uncompromised its elegant beauty. This is a Demo Online Store."
        },
        ...
    ]

Answer №1

The issue does not lie with the API calls. To improve performance, it is necessary to optimize the database query in the backend so that only the last 8 products are retrieved. Please note: You can achieve this by refining the query sent to the database within the controller (ROUTE) on the backend.

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

Can you provide the regular expression that will successfully match this specific string of text?

Can you solve this fruit riddle? apple is 2kg apple banana mango is 2kg apple apple apple is 6kg banana banana banana is 6kg If the fruits are limited to "apple", "banana", and "mango", how can we write a regex that extracts the names of ...

Encountering the issue of receiving an undefined value for a variable despite having previously defined it within

I’ve been working on implementing the Google Maps distance matrix API with the google-distance-matrix library. Here’s the code snippet I’m using: app.get("/users", (req, res) => { // console.log(req.query); // res.send(req.query); ...

Tips to successfully save and retrieve a state from storage

I've encountered a challenge while working on my Angular 14 and Ionic 6 app. I want to implement a "Welcome" screen that only appears the first time a user opens the app, and never again after that. I'm struggling to figure out how to save the s ...

Troubleshooting focus loss in React input fields within a Datatable component implemented in a

I noticed an issue with my Datatable where the input field loses focus whenever I type a character and define the component inside another component. Surprisingly, when I directly place the component in the datatable, it works perfectly fine. I understand ...

Transforming JSON into a structured table with the help of jQuery's get() function

I am facing a challenge in parsing the JSON data and converting it into an HTML table. Here is the code snippet I'm working with: jQuery.get("/path/to/json?filter=date&pagesize=25&pagestart=1", function(json) { console.log(json) }): It ...

Guidelines for executing a Vue directive when the page is initially loaded

I am iterating through an array of objects containing map svg paths and locales, and I want to execute a function on load. The function needs to take the locale keys from the paths array as a parameter and perform some operation: <p v-for="(country ...

Send the user to the login page once their email has been verified

On my website, I have a process where users need to verify their email by clicking on a link sent through emails. When the user clicks on this verification link, I want them to be redirected to a page thanking them for confirming their account and then a ...

Attempting to retrieve assets from an incorrect directory in a rush

Within my express project, I have encountered an issue when rendering the product route with a specific id. It seems that the assets are attempting to load from /products in the public folder (even though this directory does not exist). However, when I ren ...

Switch up the Javascript popup code without any specific pattern

I am looking to add variety to my pop up ads on my website by randomly changing the Javascript code for each ad every time a page is loaded. How can I achieve this? Script 1 <script type="text/javascript"> var uid = '12946'; var w ...

Storing data in MongoDB upon the emission of a Socket.io event

In my project, I am using a MEAN stack and Socket.io to retrieve images from the real-time Instagram API. The current setup is functioning well, but now I want to store image data in a MongoDB database to maintain a record of images based on locations, rat ...

The React rendering process failed when attempting to utilize a stateless component

Struggling to integrate a stateless component with fetch in my project. The fetch API is successfully retrieving data, but for some reason, the stateless component remains blank. import React, { PropTypes } from 'react'; import { Card, CardTitle ...

Using axios to retrieve data and then sending it to a localhost server using express

I'm a beginner in javascript and currently experimenting with fetching data from an API and posting it to my own server (localhost). For fetching the data, I am using axios as shown below: async function getNCAA() { axios .get(`https://api.th ...

Obtain the access token generated from JSON within a Spring Boot application

@RequestMapping(value = "/check", method = RequestMethod.GET) public ResponseEntity<Product> createProducts() throws JsonProcessingException { String reqUrl = "http://localhost:8080/home"; HttpHeaders heade ...

Creating a sequence of dependent HTTP requests in Angular

Is it possible to execute multiple http get requests sequentially in Angular, where the endpoint URL for the second request depends on the response of the first request? I attempted to nest the requests using the following code snippet: this.http.get(end ...

Sending Parsed Information to Callback for Flexible Use

Is there a way to pass the value of coins, or even better, currency to my callback function so I can freely use the parsed JSON data in other functions? function fetchJSON(path, callback) { var jsonReq = new XMLHttpRequest(); jsonReq.onreadystatechang ...

Unable to modify the bar's color using the .css document

Below is the JavaScript code being used: var marginEducation = {top: 20, right: 30, bottom: 40, left: 300}, widthEducation = 1000, heightEducation = 460; const svgEducation = d3.select("#Education") .append("svg") .attr("w ...

Creating a vibrant and mesmerizing inward spiraling rainbow of colors on canvas using JavaScript

After coming across an image that caught my eye, I was inspired to recreate it using canvas: https://i.stack.imgur.com/fqk3m.png I've attempted drawing arcs starting from the center of the screen, but I'm struggling with getting their paths acc ...

Exploring the use of jQuery autocomplete to retrieve data attributes

Looking to retrieve additional data-attributes from the Mapbox API. The autocomplete plugin I implemented can be found here. (Utilizing Python/Django for backend) My goal is to send extra information such as country code, city, and country to my databas ...

Creating JSON in Android involves following a set of steps to transform data

Can someone help me with creating nested JSON in Android? I need the JSON data to have a structure similar to this: JSON Customername = Alice Customercode = 101 Customercity = New York Customerstate = NY Customercountry = USA Customersales Productname ...

Ways to navigate to a different page using HTML response from an AJAX request

After receiving an HTML document as a response from an AJAX call, I need to create a redirection page using this HTML response. Can anyone provide guidance on how to achieve this? ...