I am doing server side pagination in my MERN project. Suppose I get 100 products from Database and I want to show only 30 products, 10 products per page. and I want that when user want to visit 4rth page I make another call to api to get next 30 products and previous 30 should not overridden. So I need to concatenate current array data with previous data. How can I do this?
Here is my code:
calling api function using useQuery
and send offset
and postsPerPage(limit)
and jwttoken
as arguments:
let { isFetching: isFetchingPage, refetch: fetchPage } = useQuery(
["pages", user],
async (user) => {
return await getProductsPage(
user?.queryKey[1]?.jwtToken,
offset,
postsPerPage,
);
},
{
enabled: false,
staleTime: 10000,
onSuccess: (data) => {
setProduct(data?.data?.data);
},
}
);
Get data from API
export const getProductsPage = async (token, offset, limit,)=>{
{
const data = await axios.get(`getMarketPlace`,
{
params:{
details:false, offset:offset, limit:limit
},
headers:{
'Content-Type':'application/json',
Authorization:token,
}
})
return data
}
}
it works perfectly the only thing I want is that to concatenate currentData with previous data. How can I do that?
CodePudding user response:
You can simply use the spread operator …
.
onSuccess: (data) => {
const newData = data?.data?.data
if (!newData) return // return if data not valid
setProduct([…product, …newData]) // concatenate arrays
}
More about the spread syntax.
CodePudding user response:
SetState((oldState) => [...oldState, ...newData])