I am trying to create a custom vue composable that use vue-query (tanstack-query) to fetch data from paginated API.
I want to fetch new data if there is any change of query parameter.
I have created a custom composable that will help fetch data from paginated query:
Here is my custom composable:
/composables/useNewsData.ts
import { useQuery } from '@tanstack/vue-query';
import authApi from '~/services/apiService';
type QueryOptionType = {
limit?: number;
page?: number;
};
// wrap with useQuery
export default ({ limit = 10, page = 1 }: QueryOptionType) => {
return useQuery({
queryKey: ['news', `limit${limit}`, `page${page}`],
queryFn: () =>
authApi.get(`/news`, {
params: {
limit,
page,
},
}),
});
};
I am trying to utilize the above composable from vue component:
/components/News.vue
// ----
const newsLimit = ref(10);
const currentPage = ref(1);
const { data, isLoading, refech } = useNewROomData({
limit: newsLimit.value,
page: currentPage.value,
});
When updating the newsLimit / currentPage value from the user interaction (button click etc), it does not do any network request to fetch data with new query.
If I call refetch method from useQuery
on any parameter change, it can refetch the new data, but I can not use the useQuery
cache feature if newsLimit
/ currentPage
change.
Is there any ideal way to trigger the custom useQuery
composable if there is any data or parameter change? What is the best way to solve this issue.
I'm new to the vue world. Please accept my apology for any mistake.