helps create unique query keys for use with the react-query package
npm install react-query-keys



sh
$ yarn add @tanstack/react-query
`
Table of contents
- Project Name
- Prerequisites
- Table of contents
- Getting Started
- Installation
- Usage
- Creating your keys
- Using your keys
- API
- all
- key
- Configuration
- Credits
Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.
Installation
To install the library, run:
`sh
$ npm install react-query-keys
`
Or if you prefer using Yarn:
`sh
$ yarn add react-query-keys
`
Usage
$3
`ts
import ReactQueryKeys from "react-query-keys";
// the name of this section of the app
const keysName = "customers";
const queryKeyConfig = {
keyDefinitions: {
list: {
dynamicVariableNames: ["productCount", "customerId"],
},
detail: {
dynamicVariableNames: ["customerId"],
},
pagedList: {
childOf: "list",
dynamicVariableNames: ["skip", "take"],
},
},
};
// create an instance of your keys for this section. I like to do this once for each section of an app and split my queries accordingly
const customerQueryKeys = new ReactQueryKeys(keysName, queryKeyConfig);
`
$3
`ts
import { useQuery, useMutation } from "@tanstack/react-query";
const useGetCustomersQuery = (customerId: string) =>
useQuery(
customerQueryKeys.key("list", { customerId }), // resolves to ['customers', 'list', { customerId }]
() => getCustomers(customerId)
);
const useCreateCustomerQuery = () =>
useMutation(
({ customerId, customer }: { customerId: string; customer: Customer }) =>
createCustomer(customer),
{
// invalidate all queries that contain ['customer', 'list'] in their key
onSuccess: () =>
reactQueryClient.invalidateQueries(customerQueryKeys.key("list")),
}
);
`
API
$3
`ts
ReactQueryKeys.all();
`
Returns top level key for this instance. You can use this to refer to all other keys created with this instance. For example given a key ['customers', 'list'], reactQueryKeys.all() would return ['customers'].
$3
`ts
ReactQueryKeys.key(name: string, dynamicValues?: Record)
`
Get the value of a specific key with option to provide an object literal with dynamic values, thus creating different query keys as the given values change.
$3
config
| Name | Type |
| -------------- | --------------------------------------------------------------------- |
| keyDefinitions | Record |
Use the config constructor parameter to create your query keys instance. Each keyName refers to query key you want to be able to use for this instance. You can configure each key to be a child of another key, thus making the key dependent on the childOf key. You can also provide dynamicVariableNames which are the property names for any dynamic values you would like to include in your key. For example to use the value { customerId: '123' } in your key, you would have dynamicVariableNames include 'customerId'`.