I want to load the list of products from local API work with pages and I want to load new products while the user is scrolling, the problem is when I want to push the new product to the list of products using setProduct const [products, setProducts] = useState<ProductModel[]>([]);
this is the function loading products:
const getProductList = async () => {
const token: string | null = await localStorage.getValue("token");
console.log("page:", currentPage);
if (currentPage >= maxNumberOfPages - 1) {
setLoading(true);
getAllProducts(token!, currentPage)
.then((res) => {
console.log(
"res",
res.data.numberOfElements,
"totalPages: ",
res.data.totalPages
);
if (products.length === 0) {
setProducts(res.data.content);
setCurrentPage(1);
setMaxNumberOfPages(res.data.totalPages);
setLoading(false);
}
if (products!.length > 0 && res.data.numberOfElements > 0) {
setProducts([...products, res.data.content]); <== error happened here
setCurrentPage(currentPage 1);
setLoading(false);
}
})
.catch((error) => {
console.log("get products error:", error);
});
}
};
flat list component:
{products.length !== 0 ? (
<FlatList
data={products}
renderItem={renderPrices}
numColumns={1}
// keyExtractor={(item) => item.id.toString()}
ListFooterComponent={() =>
loading ? (
<View style={{ justifyContent: "center", alignItems: "center" }}>
<Spinner size="giant" />
</View>
) : null
}
nestedScrollEnabled={true}
onEndReached={() => getProductList()}
onEndReachedThreshold={0.1}
/>
) : (
<View style={{ justifyContent: "center", alignItems: "center" }}>
<Spinner size="giant" />
</View>
)}Ï
this error happens when I tried to setProducts([...products, res.data.content]);
screenshot of the problem:
CodePudding user response:
Try this:
setProducts([...products, ...res.data.content])
make sure you're also spreading the 2nd array.