[英]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?任何人都知道我应该用我的代码更改什么来获取所有项目,这样我就可以运行 skip 和 take 直到我获得所有项目,以及如何更新skip
和take
异步以便使用正确的参数更新下一个请求? With class component, I would use setState callback?对于类组件,我会使用 setState 回调吗?
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在这种情况下,您应该将 loadMoreFlag 保持为组件的状态,例如
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之后,您可以在这样的 fetch 调用中使用它
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.现在您可以在需要时使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.