can anybody tell me please why button load more doesn't work. I wrote down the function load more in the file hooks. Then I gave function throw the props. As a result it doesn't work. It returns the same data. how to improve it . Here is a fetching:
const instance = axios.create({
baseURL: "https://fakestoreapi.com/",
})
export const getProducts = async ( page=1, limit = 5) => {
const {data} = await instance.get<IProduct[]>("products", {
params: {
page,
limit
}
});
return data;
}
function Product() {
const [products, setProducts] = useState<IProduct[]>([]);
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState('');
const [page, setPage] = useState<number>(1);
useEffect(() => {
const fetchProducts = async () => {
try {
setLoading(true)
setError(' ')
const data = await getProducts(page);
setProducts(data);
setLoading(false)
} catch (error: unknown) {
setLoading(false)
setError("Network Error!")
}
}
fetchProducts()
}, [page]);
const loadMore = () => {
setPage(prevPage => prevPage 1)
};
return (<>
<ul className={s.wrap}>
{loading && <p>...loading</p>}
{error && <ErrorMessage error={ error} />}
{products.map(product => <ProductList product={product} key={product.id} />)}
{!loading && products.length >= 3 && <button onClick={loadMore}>Load more</button>}
</ul>
</>
)
}
export default Product
CodePudding user response:
I think your code doesn't have any problem.
The problem is that the fake store api doesn't have a 'page' parameter, only has 'limit' and 'sort' parameters.
For getting your required result using this api, you need to update your getProducts function.
Thanks for your time.