Home > OS >  how can i get data of a specific id from backend in react js?
how can i get data of a specific id from backend in react js?

Time:12-29

I am trying to get a specific id related data from backend instead of whole database and then comparing the id. i am passing id using state param. I am new to react so it will helpful to explain as simply as you can.

this is my service for getting data

import http from "./http";
const getBoxes = () => {
    return http
      .get("/box/getAllBox")
      .then((result) =>
      result.data.content.map((item, index) => ({ ...item, key: index }))
    );
};

CodePudding user response:

You should create a backend endpoint (if possible) where you can get one box. EG /box/{id}.

This means when you get this endpoint in react you can do result.data.{some property from the returning object} eg result.data.boxName

If you don't have the ability to change the backend, you could get the specific id from the array of boxes by looping through the results and finding where ID of the returned object matches the ID you're looking for - this requires the array of objects being returned to each contain an ID field.

import http from "./http";
const getBoxes = () => {
    return http
      .get("/box/getAllBox")
      .then((result) =>
          let itemFromID;

          for(let i = 0; i < result.data.length; i  ) {
              let item = result.data[i];
              if(item.id === 1) {
                  itemFromID = item;
                  break;
              }
          }
        // now you have the item in itemFromID variable
        console.log(itemFromID);
    );
};

CodePudding user response:

You can easily do that by using the filter() property

For example

import http from "./http";
const getBoxes = () => {
    return http
      .get("/box/getAllBox")
      .then(result=>{
      result.data.content.filter(item=> item.id=="your ID")
      })
      .then((result) =>
      result.data.content.map((item, index) => ({ ...item, key: index }))
    );
};

Replace your ID with your custom id

  • Related