Home > Software engineering >  how can i fetch data from "multiple" pages using axios and useState-useEffect
how can i fetch data from "multiple" pages using axios and useState-useEffect

Time:12-08

I have a url which is https://rickandmortyapi.com/api/character/ This api consist of 42 pages and 826 datas.

I want to keep all data in one variable to filter later (and i will use show more button). at the beginnig the interface 20 datas(1 page) will be displayed. then, when the user click on show more button it should should fetch the datas of the next page and be inserted below the existing data. That's the reasons why i want to keep all data in one variable.

[Here is my fetch code with axios]



const [characters, setCharacters] = useState({});
  const [filtered, setFiltered] = useState({});
  const url = 'https://rickandmortyapi.com/api/character/';

  useEffect(() => {
    axios
      .get(url)
      .then((res) => {
        setCharacters(res.data.results);
        setFiltered(res.data.results);
      })
      .catch((error) => console.error(error));
  }, []);

(however, this code is getting only one page from the api)

CodePudding user response:

To fetch all pages of the API at once, you can use a loop to make multiple requests and then combine the results into a single variable.

Here's an example using axios:

const [characters, setCharacters] = useState([]);
const [filtered, setFiltered] = useState([]);
const url = 'https://rickandmortyapi.com/api/character/';

useEffect(() => {
  let cancelled = false;

  async function fetchData() {
    const results = [];

    for (let i = 1; i <= 42; i  ) {
      const res = await axios.get(`${url}?page=${i}`);
      if (!cancelled) {
        results.push(...res.data.results);
      }
    }

    setCharacters(results);
    setFiltered(results);
  }

  fetchData();

  return () => {
    cancelled = true;
  }
}, []);

This code makes a request to the API for each page and adds the results to the results array. Then, it sets the characters and filtered state variables to the combined results.

When the user clicks on the "show more" button, you can use the setFiltered function to update the filtered state variable with the next page of results. You can also use pagination to only show a certain number of results at a time.

CodePudding user response:

To fetch data from multiple pages using axios and useState-useEffect in React, the following steps can be followed:

Import the axios library and the useState and useEffect hooks from React at the top of the component file.

 import axios from 'axios';
import { useState, useEffect } from 'react';
Define a state variable to store the data that is fetched from the pages, and a state variable to store the current page number. Initialize these variables using the useState hook.


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

Define a function that uses axios to fetch data from the specified page. This function should take the page number as an argument and return a promise that resolves to the data from that page.

const fetchData = (page) => {
  return axios.get(`https://rickandmortyapi.com/api/character/?page=${page}`)
    .then(response => response.data.results);
}

Use the useEffect hook to define a function that is called when the component mounts and whenever the page number changes. In this function, call the fetchData function to retrieve the data from the current page and update the data state variable with the returned data.

useEffect(() => {
  fetchData(page)
    .then(data => setData(data));
}, [page]);
To fetch data from the next page, define a function that increments the page number and updates the page state variable. This function can be called when a button or other UI element is clicked to load the next page of data.

const loadNextPage = () => {
  setPage(page   1);
}

To display the data that is fetched from the pages, use the data state variable in the component's render method.

return (
  <div>
    {data.map(item => (
      <div key={item.id}>{item.name}</div>
    ))}
  </div>
);
  • Related