Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

suspensive-react-query.md

69 lines2.2 KB

1---
2id: suspensive-react-query
3title: Suspensive React Query
4---
5​
6Typesafe useQuery, useInfiniteQuery with default suspense option.
7​
8Use @suspensive/react-query, delegate loading and error handling to the outside of the component with useSuspenseQuery and useSuspenseInfiniteQuery, and focus on success inside the component.
9​
10You don't even need to use the isSuccess flag.
11​
12## Installation
13You can install @suspensive/react-query via [NPM](https://www.npmjs.com/package/@suspensive/react-query).
14​
15```bash
16$ npm i @suspensive/react @suspensive/react-query
17# or
18$ pnpm add @suspensive/react @suspensive/react-query
19# or
20$ yarn add @suspensive/react @suspensive/react-query
21```
22​
23### Motivation
24​
25If you turn suspense mode on in @tanstack/react-query, You can use useQuery with Suspense and ErrorBoundary.
26​
27```tsx
28import { useQuery } from '@tanstack/react-query'
29​
30const Example = () => {
31 const query = useQuery(queryKey, queryFn, {
32 suspense: true,
33 })
34​
35 query.data // TData | undefined
36​
37 if (query.isSuccess) {
38 query.data // TData
39 }
41```
42​
43Typically query.data will be `TData | undefined` like this code example.
44But actual useQuery's return type:query.data will be always fulfilled because of [Suspense](https://suspensive.org/docs/react/src/Suspense.i18n) and [ErrorBoundary](https://suspensive.org/docs/react/src/ErrorBoundary.i18n) as parent of this component.
45​
46This is why @suspensive/react-query provide **useSuspenseQuery**
47​
48## useSuspenseQuery
49​
50Return type of this hook have no isLoading, isError property. because Suspense and ErrorBoundary will guarantee this hook's data.
51​
52In addition, this hook's options have default suspense: true. and you can provide new options to this hook like useQuery of @tanstack/react-query.
53​
54```tsx
55import { useSuspenseQuery } from '@suspensive/react-query'
56​
57const Example = () => {
58 const query = useSuspenseQuery(queryKey, queryFn, options) // suspense:true is default.
59​
60 // No need to do type narrowing by isSuccess
61 query.data // TData
63```
64​
65### Concentrate on only Success
66​
67Now, we can concentrate component as any fetching will be always success in component.
68​
69Check the complete documentation on [GitHub](https://github.com/suspensive/react).