@xtreamsrl/react-query
v0.11.1
Published
This package exposes tools to manage server state in React applications.
Downloads
74
Readme
@xtreamsrl/react-query
This package exposes tools to manage server state in React applications.
Installation
npm install @xtreamsrl/react-query
Usage
Configure and provide query client
Set up the query client using configureQueryClient
in the main app and wrap it with ServerStateManagementProvider
.
The provider includes ReactQueryDevtools.
configureQueryClient({defaultOptions: {queries: {staleTime: Infinity}}});
function App() {
return
<ServerStateManagementProvider>
{/* all the app logic */}
<MainApp />
</ServerStateManagementProvider>
}
The configuration method accepts other object fields as well as defaultOptions
:
queryCache
mutationCache
logger
Query
Create query
Create the query using createQuery
, specifying parameters if necessary (like id
in the example below).
export const myQuery = createQuery((id: string) => ({
queryKey: ["test", id],
queryFn: () => getTestAPI(id),
}));
The query key is a unique identifier for a specific query.
In the code snippet, getTestAPI
is the function used to fetch remote data.
Use query
To fetch desired data it is necessary to invoke the hook
method on the query object.
const {data, isError, error, isSuccess, isLoading} = myQuery.hook(id);
The execution has fixed values for:
retry
: false,staleTime
: 5 * 60 * 1000 milliseconds, 5 minutes
Update data
To update data it is necessary to specify the updater function and parameters. This method is used to immediately update a query's cached data.
myQuery.update(previous => previous ? { ...previous, value: previous.value + 1} : undefined, id);
Invalidate data
The invalidation process requires params to be specified
myQuery.invalidate(id).finally(() => console.log('invalidated'));
Prefetch data
The prefetching process requires params to be specified
myQuery.prefetch(id).finally(() => console.log('prefetched'));
infiniteQuery
Infinite queries are useful to handle paginated data fetching.
createInfiniteQuery
Create the query using createInfiniteQuery
, specifying parameters if necessary.
- The first argument is an array corresponding to the query key.
- The second argument is a function that takes two parameters:
- The first parameter is an object { pageParam } to handle pagination.
- The second parameter is an object with required params for the query.
- The third argument is an
Options
object which allows to specifystaleTime
andgetNextPageParam
. Here is an example of infiniteQuery creation.
const myInfiniteQuery = createInfiniteQuery(
[TransactionsKeys.Transactions],
(
{ pageParam },
{
sorting,
filters,
}: {
sorting: TransactionSortingParams;
filters: TransactionFiltersParams;
},
) => getTransactionsAPI(filters, sorting, {
page: pageParam,
hasNext: true,
pageSize: 20,
}),
{
getNextPageParam: lastPage => lastPage.pageInfo.nextPage ?? undefined,
},
);
Another trivial example that can help using the createInfiniteQuery
for its simplicity and immediacy is the following:
const myInfiniteQuery = createInfiniteQuery(
["test"],
({pageParam}) : Promise<Test> => fetch.get("http://localhost:3000/test/test" + pageParam),
{
getNextPageParam: lastPage => 1
}
);
Use infiniteQuery
To fetch desired data it is necessary to invoke the hook
method on the query object specifying the needed params.
const {
data,
isError,
isSuccess,
isLoading,
errorMessage,
errorCode,
refetch,
isFetchingNextPage,
hasNextPage,
fetchNextPage
} = myInfiniteQuery.hook({ sorting, filters });
Update data
To update data it is necessary to specify the updater function. The update uses the key passed during the creation of the infiniteQuery.
myInfiniteQuery.update(previous => previous ? { ...previous, value: previous.value + 1} : undefined);
Invalidate data
The invalidation process does not require any parameter to be passed, it uses the key passed during the creation of the infiniteQuery.
myInfiniteQuery.invalidate().finally(() => console.log('invalidated'));
Mutation
A mutation is a mechanism for managing asynchronous operations that modify data on a server, such as creating, updating, or deleting resources.
Create mutation
To create a mutation it necessary to use the createMutation
hook passing a param object in which three fields can be specified:
mutatingFunction
: is an asynchronous function that performs the actual operation, for example to create, update, or delete data on a server.options
: is an object that contains theonSuccess
field.retry
: is an option that specifies whether a mutation should automatically retry if it encounters a network error.
const myMutation = createMutation({
mutationFunction: createPostAPI,
options: {
onSuccess: () => {myInfiniteQuery.invalidate().finally(() => reset())}
},
retry: 3 // Retry the mutation up to 3 times on network error
})
Use mutation
When exploiting the mutation it is possible to specify the behaviour in case of success and in case of error.
myMutation.hook({
onSuccess: (data, payload) => {
console.log('Operation successful:', data);
console.log('Payload used:', payload);
},
onError: (error, payload) => {
console.error('Error during operation:', error);
console.log('Payload used:', payload);
},
})
data
refers to the data returned or received upon a successful operation, it represents the result or response data when the asynchronous operation succeeds.
error
represents an error object that might occur during the asynchronous operation.
payload
refers to additional information or input data that you can pass along with the callbacks. It's a way to carry extra context or data to be used within the callback functions.
It is also possible specify a listener that executes following a success event
myMutation.onSuccessEvent(() => console.log("data"))