This package exposes tools to manage server state in React applications.
npm install @xtreamsrl/react-queryThis package exposes tools to manage server state in React applications.
``shell`
npm install @xtreamsrl/react-query
Set up the query client using configureQueryClient in the main app and wrap it with ServerStateManagementProvider.
The provider includes ReactQueryDevtools.
`tsx
configureQueryClient({defaultOptions: {queries: {staleTime: Infinity}}});
function App() {
return
{/ all the app logic /}
}
`defaultOptions
The configuration method accepts other object fields as well as :queryCache
- mutationCache
- logger
-
#### Create query
Create the query using createQuery, specifying parameters if necessary (like id in the example below).`tsx`
export const myQuery = createQuery((id: string) => ({
queryKey: ["test", id],
queryFn: () => getTestAPI(id),
}));getTestAPI
The query key is a unique identifier for a specific query.
In the code snippet, 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.`tsx`
const {data, isError, error, isSuccess, isLoading} = myQuery.hook(id);retry
The execution has fixed values for:
- : 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.
`tsx`
myQuery.update(previous => previous ? { ...previous, value: previous.value + 1} : undefined, id);
#### Invalidate data
The invalidation process requires params to be specified
`tsx`
myQuery.invalidate(id).finally(() => console.log('invalidated'));
#### Prefetch data
The prefetching process requires params to be specified
`tsx`
myQuery.prefetch(id).finally(() => console.log('prefetched'));
#### 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 specify staleTime and getNextPageParam.
Here is an example of infiniteQuery creation.
`tsx`
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,
},
);createInfiniteQuery
Another trivial example that can help using the for its simplicity and immediacy is the following:`tsx`
const myInfiniteQuery = createInfiniteQuery(
["test"],
({pageParam}) : Promise
{
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.`tsx`
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.
`tsx`
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.
`tsx`
myInfiniteQuery.invalidate().finally(() => console.log('invalidated'));
#### 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 the onSuccess field.retry
- : is an option that specifies whether a mutation should automatically retry if it encounters a network error.
`tsx`
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.
`tsx`
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
`tsx``
myMutation.onSuccessEvent(() => console.log("data"))