简体   繁体   中英

React js fetch all data from a paginated api with react hooks

I am working on a react app for what is going to an editing tool for internal use. I have a use-case where I need to get all the items that are paginated. The thing is that all params our backend. has is limit & offset. But there are no response headers that indicate what page I'm on currently. Anyone with an idea of what I should change with my code to get all items so I can run skip and take until I get all the items & how do I update skip & take asynchronous so the next request is updated with the right params? With class component, I would use setState callback?

my code

 const fetchItems = async () => {
    try {
      const items: any = await itemsService.getItems({
        skip: 0,
        take: 50,
      })

      setItems(items)

    } catch (error) {
      console.log(error)
    }
  }

here in this case you should mainatain loadMoreFlag as state of component like

     const [hasLoadMore,setHasLoadMore]=useState(true);//assumeing it will have load more for very first time

after that you can use it in fetch call like this

  const fetchItems = async () => {
            if(!hasLoadeMore)return;
            try {
                const items: any = await itemsService.getItems({
                  skip: 0,
                  take: 50,
                })
            if(items!==null && items !==undefined){
               setHasLoadMore(true);
               setItems(items)  
            }
            else{
              setHasLoadMore(false);//if you are requesting the last+1 page y ou will not recive any items
              }
             } catch (error) {
               console.log(error)
            }
         }

EDIT

for answer to your comment about using skip and take:

How can I make the equivalent logic with react hooks?

you can declaer both inside function component and use with hooks like

      const [skip,setSkip]=useState(0);
      const [take,setTake]=useState(50);

now you can use them when needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM