Home > Software design >  Pagination using Flatlist in React Native (Next/Previous)
Pagination using Flatlist in React Native (Next/Previous)

Time:12-01

Recently, I've been starting to learn React Native, and I stack with a pagination for my project. I am trying to create a Flatlist which will show only first ten items from data. Then when you click on the next arrow, it will display next different ten items instead of the first ten, and so on. And the same logic to the back arrow but only previous ten items. Here is my code. It works but with some issues. After the first clicking to the next ten items, it shows the same ten, but when you click again, it displays different ten. The back arrow seems that doesn't work properly at all. Could someone help me tweak my code to fix these issues? I will appreciate any help. Thank you!

https://snack.expo.dev/rWq_FLP8o

CodePudding user response:

What you should do is add pageCurrent as a dependency in your useEffect. So every time pageCurrent changes the useEffect runs.

  useEffect(() => {
    (async () => {
      const apiURL = `https://jsonplaceholder.typicode.com/albums?_limit=10&_page=${pageCurrent}`;
      fetch(apiURL)
        .then((res) => res.json())
        .then((resJson) => {
          setData(resJson);
        });
    })();
  }, [pageCurrent]); // <-- Makes pageCurrent a dependency

Next make it so when you go back on page 1 it stays on page 1. This way you don't get negative pages or a zero page.

const handlePreviousPage = () => {
        console.log("previous page clicked", pageCurrent)
        // Do this so your page can't go negative
        setpageCurrent(pageCurrent - 1<1?1:pageCurrent - 1)
}

Heres a full example (https://snack.expo.dev/@heytony01/keyboard-function-component-example)

  • Related