[英]How to load data from api and load component asynchronously with map function
My backend database has a hundreds of products stored and i want to list them to the frontend react user in a async way without waiting until all data is loaded.我的后端数据库存储了数百个产品,我想以异步方式将它们列出给前端反应用户,而无需等到所有数据都加载完毕。 although i use the api cashing but it's still taking few seconds to map products list to components.
虽然我使用 api 兑现,但它仍然需要几秒钟才能将 map 产品列表添加到组件。
I use a useAPI hook with axios & async/wait function to fetch data from api.我使用带有 axios 和异步/等待 function 的 useAPI 钩子从 api 获取数据。
Is there any way to improve the loading and make the component update periodically?有没有办法改善加载并使组件定期更新? How can i cache data in the frontend to avoid overcalls for the database?
如何在前端缓存数据以避免过度调用数据库?
import React from "react";
import useAPI from '../../api/useAPI'
import { ProductsListWrap, ProductCard } from '../../components'
const ProductsList = (props) => {
const handleSelect = (data) => {
console.log(data)
};
const [products, loading, error, retry] = useAPI('/api/v1/products');
return (
<ProductsListWrap>
{products.map((data, i) => {
return (
<ProductCard
handleSelect={() => handleSelect(data)}
key={i}
{...data}
/>
);
})}
</ProductsListWrap>
);
};
export default ProductsList;
First, you probably need to paginate your requests..首先,您可能需要对您的请求进行分页……
You can create a 'cache' adding a state to your hook .您可以创建一个“缓存”,将 state 添加到您的钩子中。 Also you would need to create a function inside to make the request whenever you want.
此外,您还需要在内部创建一个 function 以便随时发出请求。
Add also a function called, ie fetchData
to your hook (if it does not exists already).还添加一个 function 调用,即
fetchData
到您的挂钩(如果它不存在)。
Return also that fetchData
function.还返回
fetchData
function。
function yourHook() {
const [cache, setCache] = useState();
function fetchData() {
if (!cache) {
// your axios logic
setCache(response);
}
}
...
return [fetchData, cache, loading, error, retry];
}
Call fetchData
in your component (note that now products
is cache
):在您的组件中调用
fetchData
(注意现在products
是cache
):
const [fetchData, products, loading, error, retry] = useAPI('/api/v1/products');
useEffect(() => {
fetchData();
}, []);
return (
<ProductsListWrap>
{products && products.map...}
</ProductsListWrap>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.