npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@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 specify staleTime and getNextPageParam. 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 the onSuccess 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"))

Who we are