skip to Main Content

I am loading 10 items per page from API and storing the data in redux
suppose I scroll 3 pages so in my redux there are 30 elements 10 elements on page 1 10 on page 2 10 on page 3.
Now I go to the next screen and return to the pagination screen again. My page 1 is again called and in the redux, there is duplication of elements because page 1 elements are already in the redux,
So, should I clear the redux before going to the next screen? So it again starts with page 1

2

Answers


  1. I suggest you keep another key inside the redux to track the last searched page index.

    • Initially, it would be something like {lastSearchedPageIndex: 0, items: []}.
    • When you opened the page for the first time, you would make an API call with the page parameter as 0. You would get a successful response from the API and now the state of redux has to be {lastSearchedPageIndex: 0, items: [SOME_ITEMS_OF_PAGE_0]}.
    • When you scroll up and reach the page end, you would make another API call. But here you have to make sure that you would only call the API if the page is not searched before. The condition should be if(currentPage > lastSearchedPageIndex) { MAKE_AN_API_CALL_WITH_PAGE_1 } where currentPage is the page number you are searching for. Once you get the response the redux state would be {lastSearchedPageIndex: 1, items:[SOME_ITEMS_FROM_PAGE0, SOME_ITEMS_FROM_PAGE1]}. This would be continued for the remaining pages as well.

    Now the paging is done and you are moved to some other screen and come back to the pagination screen. Now the redux state as per your question is {lastSearchedPageIndex: 2, items:[SOME_ITEMS_FROM_PAGE0, SOME_ITEMS_FROM_PAGE1, SOME_ITEMS_FROM_PAGE2]}. You are at the page and scroll to the end of page 0. As we already wrote the guard condition if(currentPage > lastSearchedPageIndex) { MAKE_AN_API_CALL_WITH_PAGE } and according to this, the current page is 1 and lastSearchedPageIndex is 2. So no API call would happen.

    Login or Signup to reply.
  2. It depends on what you want, so here you go 2 solutions:

    1- If you want to keep your data:

    Add the pagination logic in your redux code, that way if you reach page 3, in redux the page will be updated to 3, therefore, when you come back to the screen the page will go on from 3 .

    A good way to implement the paging logic in redux, is by adding a +1 to the page value in redux state whenever you receive a response:

     return { 
     ...state,
    data:[...state.data,...data]
     page:data.length >0? state.page+1:state.page
     }
    

    2- If you are using the same redux for different screens or you want to clear it (which I don’t recommend):

    Then definitely you will have to clear all your redux data while leaving the screen.

    If you have any question, Let me know and good luck!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search