Home > Software design >  React, how to fetch data from an api by selecting the startpoint ID
React, how to fetch data from an api by selecting the startpoint ID

Time:07-15

Basically, I'm curious If there's a way to fetch data from an API by selecting the startpoint myself. So, for example, Imagine inside that API is an array of objects, each object containing its own unique ID, so lets say, from 1 to 100. Is there a way to fetch the data only from objects whose ID is 20 or higher and not below?

I'm building a project where I'm fetching an API containing data of a single user which contains a list of friends that I'm also fetching separately. I have a UI set up for that single user containing his personal data and below that I'm displaying their friends list as Cards. I'm also using infinite scrolling so on each scroll I'm sending a request to the server to fetch another page of the data. problem is, I'm fetching the friends list data statically so the list is there on the user page on load, the code for it looks like this :

const params = useParams();
const [items, setItems] = useState([]);

// Getting the list of friends 
  const fetchData = (setItems) => {
    let url =  `http://sweeftdigital-intern.eu-central-1.elasticbeanstalk.com/user/${params.id}/friends/1/20`;
    axios.get(url).then((res) => {
        setItems(res.data.list);
        console.log(res);
      });
   };

And when I scroll down, I'm fetching more data from the API containing the friends list :

const [page, setPage] = useState(1);

const moreData = () => {
    let url = `http://sweeftdigital-intern.eu-central-1.elasticbeanstalk.com/user/${params.id}/friends/${page}/40`;
    
    axios.get(url).then(res => {
      setItems([...items,...res.data.list]);
      setPage(page 1)
      setIsFetching(false);
      console.log(res);
    });
    
  }

So here's the problem, when I scroll down, the moreData function starts to work and fetches the friends list data starting over from ID 0 to 40, but I already have the friend list displayed before scrolling containing ID's from 0 to 20, so on the first scroll, it just repeats the first 20 ID's and then loads the rest. So I just want to fetch the data starting from ID 20, in order to not repeat the same ID's starting from 0. I hope I explained it at least okey, I'd appreciate any help, thank you!

CodePudding user response:

This is a flaw in API, it can be solved like this

const [page, setPage] = useState(1);

const moreData = () => {
    let url = `http://sweeftdigital-intern.eu-central-1.elasticbeanstalk.com/user/${params.id}/friends/${page}/40`;

    axios.get(url).then(res => {
        const filteredItems = res.data.list.filter(u => u.id > items.length);
        setItems([...items, ...filteredItems]);
        setPage(page   1);
        setIsFetching(false);
        console.log(res);
    });

};

  • Related