|
| 1 | +--- |
| 2 | +id: suspensive-react-query |
| 3 | +title: Suspensive React Query |
| 4 | +--- |
| 5 | + |
| 6 | +Typesafe useQuery, useInfiniteQuery with default suspense option. |
| 7 | + |
| 8 | +Use @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 | + |
| 10 | +You don't even need to use the isSuccess flag. |
| 11 | + |
| 12 | +## Installation |
| 13 | +You 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 | + |
| 25 | +If you turn suspense mode on in @tanstack/react-query, You can use useQuery with Suspense and ErrorBoundary. |
| 26 | + |
| 27 | +```tsx |
| 28 | +import { useQuery } from '@tanstack/react-query' |
| 29 | + |
| 30 | +const 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 | + } |
| 40 | +} |
| 41 | +``` |
| 42 | + |
| 43 | +Typically query.data will be `TData | undefined` like this code example. |
| 44 | +But 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 | + |
| 46 | +This is why @suspensive/react-query provide **useSuspenseQuery** |
| 47 | + |
| 48 | +## useSuspenseQuery |
| 49 | + |
| 50 | +Return type of this hook have no isLoading, isError property. because Suspense and ErrorBoundary will guarantee this hook's data. |
| 51 | + |
| 52 | +In 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 |
| 55 | +import { useSuspenseQuery } from '@suspensive/react-query' |
| 56 | + |
| 57 | +const 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 |
| 62 | +} |
| 63 | +``` |
| 64 | + |
| 65 | +### Concentrate on only Success |
| 66 | + |
| 67 | +Now, we can concentrate component as any fetching will be always success in component. |
| 68 | + |
| 69 | +Check the complete documentation on [GitHub](https://github.com/suspensive/react). |
0 commit comments