To use react-query with typescript, you need to first install the library and its types:
index.ts55 chars3 lines
You can then use react-query's hooks in your functional components:
index.ts464 chars25 linesIn the example above, useQuery is used to fetch a list of User objects from the /api/users endpoint. The data and error states are destructured from the hook's result for rendering purposes. The generic type argument 'users' is used as a key for caching purposes.
You can also use react-query's useMutation hook for making mutations to your API and updating the cache accordingly:
index.ts1130 chars44 linesIn the example above, useMutation is used to create a new User object by making a POST request to the /api/users endpoint. The onSuccess option is used to update the cache by appending the new user to the existing list of users stored under the 'users' key. The useQueryClient hook is used to obtain access to the query client used by react-query.
Note that you need to provide your custom types for User and Error wherever you use them. In the examples above, I assumed they are defined in my-app/types.
gistlibby LogSnag