mobx-tanstack-query
v3.1.7
Published
MobX wrappers for Tanstack Query (Core)
Downloads
1,169
Maintainers
Readme
MobX wrapper for Tanstack Query Core package
Current supporting Queries and Mutations
Usage
First of needs to create queryClient
using tanstack-query
core package
import { hashKey, QueryClient } from '@tanstack/query-core';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
throwOnError: true,
staleTime: Infinity,
queryKeyHashFn: hashKey,
},
mutations: {
throwOnError: true,
},
},
});
MobxQuery
import { MobxQuery } from "mobx-tanstack-query";
const query = new MobxQuery({
queryClient,
disposer?,
...options, // TanstackQuery.Query options
// Dynamic query parameters, when result of this function changed query will be updated
// (reaction -> setOptions)
options: () => ({
...options // TanstackQuery.Query options
})
})
class YammyModel {
listQuery = new MobxQuery({
queryClient,
disposer: this.disposer,
enabled: false,
queryKey: ['yammy'],
queryFn: async () => {
const response = await yammiApi.list(this.params);
return response.data;
},
onInit: (query) => {
this.disposer.add(
reaction(
() => this.params,
debounce(() => {
query.result.refetch();
}, 200),
),
);
},
});
}
yammyModel.listQuery.update({ enabled: true })
MobxMutation
import { MobxMutation } from "mobx-tanstack-query";
class YammyModel {
createMutation = new MobxMutation({
queryClient,
disposer: this.disposer,
mutationFn: async ({ kek }: { kek: string }) => {
const response = await yammyApi.create(kek);
return response.data;
},
onMutate: () => {
// on start actions
},
onError: (error) => {
// on error actions
this.rootStore.notifications.push({
type: 'alert',
title: 'Failed to create yammy',
description: apiLib.getResponseErrorDetailedText(error),
});
},
onSuccess: (_, payload) => {
// on success actions
this.rootStore.notifications.push({
type: 'success',
title: 'Yammy created successfully',
});
queryClient.resetQueries({
queryKey: ['yammy'],
exact: false,
});
},
onSettled: () => {
// on finished actions
},
});
}
yammyModel.createMutation.mutate({ kek: 'M&M' })
MobxInfiniteQuery
import { MobxInfiniteQuery } from "mobx-tanstack-query";
const query = new MobxInfiniteQuery({
queryClient,
disposer?,
...options, // TanstackInfiniteQuery.Query options
// Dynamic query parameters, when result of this function changed query will be updated
// (reaction -> setOptions)
options: () => ({
...options // TanstackInfiniteQuery.Query options
})
})