Home > Blockchain >  I am facing a problem in Pagination using states in React JS
I am facing a problem in Pagination using states in React JS

Time:11-26

I am using using useEffect() to render an article API and on one page only 20 out of 26 articles are shown. I am trying to apply pagination concept to it but Its not giving me any error and its not working either. nextPageHandler() is responsible to show the remaining 6 articles on the next page.

let articles = [];

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




useEffect(async () => {
    let url =
      `https://newsapi.org/v2/top-headlines?q=house&from=2021-10-25&sortBy=publishedAt&apiKey=abc&page=${page}`;
    let data = await fetch(url);
    let parsedData = await data.json();
    setArticle(parsedData.articles);
  }, []);



  const nextPageHandler = async () => {
    let url = `https://newsapi.org/v2/top-headlines?q=house&from=2021-10-25&sortBy=publishedAt&apiKey=abc&page=${setPage(page 1)}`;
    let data = await fetch(url);
    let parsedData = await data.json();
    setArticle(parsedData.articles);
    setPage(page   1);
    console.log("next");
  };

  const prevPageHandler = async () => {
    let url = `https://newsapi.org/v2/top-headlines?q=house&from=2021-10-25&sortBy=publishedAt&apiKey=abc&page=${setPage(
      page - 1
    )}`;
    let data = await fetch(url);
    let parsedData = await data.json();
    setArticle(parsedData.articles);
    setPage(page - 1);
    console.log("previous");
  };

Please correct me where I am wrong. Thankyou

CodePudding user response:

You need to add page state in useEffect dependency array. to trigger the api call

useEffect(async () => {
    let url =
      `https://newsapi.org/v2/top-headlines?q=house&from=2021-10-25&sortBy=publishedAt&apiKey=abc&page=${page}`;
    let data = await fetch(url);
    let parsedData = await data.json();
    setArticle(parsedData.articles);
  }, [page]);

also you don't need to call the api from function again

const nextPageHandler =  () => {

    setPage(page   1);
    console.log("next");
  };

  const prevPageHandler =  () => {
    setPage(page - 1);
    console.log("previous");
  };
  • Related