Home > Net >  Get the firsts json items with axios
Get the firsts json items with axios

Time:03-28

I'm working on the front-end of an API in react and I'm trying to get the ten first items of a JSON list like: [{"element1":"value", "element2":"value"}, {"element1":"other value", "element2":"other value"}, ...] But I don't know how to do that with Axios :/ I found nothing in the Axios' Docs or on this forum

Thanks for your help :)

CodePudding user response:

What you are talking about is called pagination and this feature should be implemented on the back end. If pagination is not supported by the backend, then you just have to use regular js array methods, for example, slice https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

CodePudding user response:

Ok, so what you are going to want to use is headers with Axios. Like this:

// headers are like variables that tell your backend what it needs to know
const config = {
  headers: {
    numberOfElements: 5
  }
}

axios.get('/apiendpoint', config)
  .then((response) => {
    // what your backend is sending the frontend
    console.log(response);
  })

Then in your backend you can get the data from that header with express and serve your data:

const express = require('express');
const app = express();

// here is your example data
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

app.get('/urlendpoint', (req, res) => {
  // use the req.get method to get the header data
  const numberOfElements = req.get('numberOfElements');
  // now we can use the arrays .slice() method to get the first x elements of an array and send it in the response
  res.send(numbers.slice(0, numberOfElements));
});

you can read more about the .slice method here

  • Related