Skip to content

Commit 2407aa3

Browse files
committed
docs: updated docs for v1
1 parent 97286c1 commit 2407aa3

File tree

8 files changed

+110
-111
lines changed

8 files changed

+110
-111
lines changed

docs/docs/Exports/create-loader.md

Lines changed: 15 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,22 @@ type ConsumerProps = Record<string, any> & {
1313

1414
const loader = createLoader({
1515
queriesArg: (props: ConsumerProps) => props.userId,
16-
queries: (userId) => {
17-
return [useGetUser(userId)] as const;
16+
useQueries: (userId) => {
17+
return {
18+
queries: {
19+
user: useGetUser(userId),
20+
},
21+
deferredQueries: {
22+
relations: useGetUserRelations(userId),
23+
},
24+
payload: {
25+
// Lets you send any static data to your consumer
26+
static: "data",
27+
},
28+
};
1829
},
19-
deferredQueries: (userId) => {
20-
return [useGetUserRelations(userId)] as const;
21-
},
22-
transform: (queries, deferredQueries) => ({
23-
queries: [...queries, ...deferredQueries],
30+
transform: (loaderData) => ({
31+
...loaderData,
2432
foo: "bar",
2533
}),
2634
onLoading: (props) => <div>Loading...</div>,
@@ -36,58 +44,3 @@ A `Loader` takes ownership over...
3644
- Data-loading
3745
- Data-transformation
3846
- Fetch-state rendering
39-
40-
Here is the `createLoader` argument:
41-
42-
````typescript
43-
type CreateLoaderArgs<
44-
P extends unknown, // Props
45-
QRU extends readonly UseQueryResult<unknown>[], // List of queries returned in `queries`
46-
QRUD extends readonly UseQueryResult<unknown>[], // List of queries returned in `deferredQueries`
47-
R extends unknown = MakeDataRequired<QRU>, // Return type
48-
A = never // Loader argument
49-
> = {
50-
/** Should return a list of RTK useQuery results.
51-
* Example:
52-
* ```typescript
53-
* (args: Args) => [
54-
* useGetPokemonQuery(args.pokemonId),
55-
* useGetSomethingElse(args.someArg)
56-
* ] as const
57-
* ```
58-
*/
59-
queries?: (...args: OptionalGenericArg<A>) => QRU;
60-
/** Should return a list of RTK useQuery results.
61-
* Example:
62-
* ```typescript
63-
* (args: Args) => [
64-
* useGetPokemonQuery(args.pokemonId),
65-
* useGetSomethingElse(args.someArg)
66-
* ] as const
67-
* ```
68-
*/
69-
deferredQueries?: (...args: OptionalGenericArg<A>) => QRUD;
70-
/** Transforms the output of the queries */
71-
transform?: LoaderTransformFunction<QRU, QRUD, R>;
72-
/** Generates an argument for the `queries` based on component props */
73-
queriesArg?: (props: P) => A;
74-
/** Determines what to render while loading (with no data to fallback on) */
75-
onLoading?: (props: P) => ReactElement;
76-
/** Determines what to render when query fails. */
77-
onError?: (
78-
props: P,
79-
error: FetchBaseQueryError | SerializedError,
80-
joinedQuery: UseQueryResult<undefined>
81-
) => ReactElement;
82-
/** @deprecated Using onFetching might result in loss of internal state. Use `whileFetching` instead, or pass the query to the component */
83-
onFetching?: (
84-
props: P,
85-
renderBody: () => ReactElement
86-
) => ReactElement;
87-
/** Determines what to render besides success-result while query is fetching. */
88-
whileFetching?: WhileFetchingArgs<P, R>;
89-
/** The component to use to switch between rendering the different query states. */
90-
loaderComponent?: Component<CustomLoaderProps>;
91-
};
92-
```
93-
````

docs/docs/Exports/use-create-query.md

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,24 @@ import {
1414
useCreateQuery,
1515
} from "@ryfylke-react/rtk-query-loader";
1616

17+
const getUser = async (userId: string) => {
18+
const res = await fetch(`users/${userId}`);
19+
const json = await res.json();
20+
return json as SomeDataType;
21+
};
22+
1723
const loader = createLoader({
18-
queries: (userId: string) => {
19-
const query = useCreateQuery(async () => {
20-
const res = await fetch(`users/${userId}`);
21-
const json = await res.json();
22-
return json as SomeDataType;
23-
// dependency array
24-
}, [userId]);
25-
return [query] as const;
24+
useQueries: (userId: string) => {
25+
const query = useCreateQuery(
26+
async () => await getUser(userId),
27+
[userId]
28+
);
29+
30+
return {
31+
queries: {
32+
query,
33+
},
34+
};
2635
},
2736
});
2837
```

docs/docs/Features/defer-queries.md

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,29 @@ Say you have a query that takes a long time to resolve. You want to put it in th
88

99
## Example
1010

11-
```typescript {3-7}
11+
```typescript {3-13}
1212
const loader = createLoader({
13-
queries: () => [useImportantQuery()] as const,
14-
deferredQueries: () => [useSlowQuery()] as const,
15-
transform: (queries, deferred) => ({
16-
important: queries[0].data,
17-
slow: deferred[0].data,
13+
useQueries: () => {
14+
const importantQuery = useImportantQuery();
15+
const slowQuery = useSlowQuery();
16+
17+
return {
18+
queries: {
19+
importantQuery,
20+
},
21+
deferredQueries: {
22+
slowQuery,
23+
},
24+
};
25+
},
26+
transform: (loader) => ({
27+
important: loader.queries.importantQuery.data, // ImportantQueryResponse
28+
slow: loader.deferredQueries.slowQuery.data, // SlowQueryResponse | undefined
1829
}),
1930
});
2031
```
2132

22-
Deferred queries are not automatically passed to the output of the loader, you have to use the `transform` argument (and it's second argument) to expose the queries for the consumers. The format of how you transform it is not important, but it is the only way to _get_ the deferred query result out of the loader.
23-
2433
Deferred queries
2534

2635
- Do not affect the loading state
27-
- Are only exposed through `transform`
2836
- Cause the component to rerender when fulfilled

docs/docs/Features/extending.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,18 +12,20 @@ const parentLoader = createLoader({
1212
});
1313

1414
const childLoader = parentLoader.extend({
15-
queries: () => [...] as const,
15+
useQueries: () => ({...}),
1616
})
1717
```
1818

1919
It's worth mentioning that queries and transform are linked in this context, meaning that if you supply a new queries argument in the extended loader, but no transform, then you will not inherit the transform from the original loader.
2020

21-
- Supplying just a new `queries` argument will result in transform being undefined in practise.
21+
- Supplying just a new `useQueries` argument will result in transform being undefined in practise.
2222
- Supplying just a new `transform` argument will result in the new transform being ignored.
23-
- Supplying a new `transform` and a new `queries` argument will properly overwrite the existing base properties.
23+
- Supplying a new `transform` and a new `useQueries` argument will properly overwrite the existing base properties.
2424

2525
All other properties in the loader will overwrite as expected. You can, for example, just supply a new `onLoading`, or `onError`.
2626

27+
`.extend` will not merge two separate `useQueries` properties. For example, you cannot _just_ inherit the deferredQueries, you must either inherit all or none of the `useQueries` argument.
28+
2729
:::info
2830
You may extend _extended_ loaders, to create an inheritance model.
2931
:::

docs/docs/Features/transforming.md

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,21 @@ You can transform the queries to any format you'd like.
88

99
```ts
1010
const notTransformed = createLoader({
11-
queries: () => [useGetPokemonsQuery()],
11+
useQueries: () => ({
12+
queries: { pokemons: useGetPokemonsQuery() },
13+
}),
1214
});
1315

1416
type NotTransformedData = InferLoaderData<typeof notTransformed>;
15-
// readonly [UseQueryResults<Pokemon[]>]
17+
// { queries: { pokemons: UseQueryResult<Pokemon[]> } }
1618

1719
const transformed = createLoader({
18-
queries: () => [useGetPokemonsQuery()],
19-
transform: (queries) => ({
20-
results: queries[0].data,
21-
query: queries[0],
20+
useQueries: () => ({
21+
queries: { pokemons: useGetPokemonsQuery() },
22+
}),
23+
transform: (loader) => ({
24+
results: loader.queries.pokemons.data,
25+
query: loader.queries.pokemons,
2226
}),
2327
});
2428

docs/docs/Quick Guide/add-queries.md

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,36 +6,46 @@ sidebar_position: 3
66

77
You can now start to add queries to your extended loaders.
88

9-
The `queries` argument of [createLoader](/Exports/create-loader) is a _hook_, which means that [the rules of hooks](https://reactjs.org/docs/hooks-rules.html) apply. This gives you the super-power of utilizing other hooks inside of your loader.
9+
The `useQueries` argument of [createLoader](/Exports/create-loader) is a _hook_, which means that [the rules of hooks](https://reactjs.org/docs/hooks-rules.html) apply. This gives you the super-power of utilizing other hooks inside of your loader.
1010

11-
```tsx title="/src/loaders/userRouteLoader.tsx" {6-10}
11+
```tsx title="/src/loaders/userRouteLoader.tsx" {6-15}
1212
import { baseLoader } from "./baseLoader";
1313
// ...
1414

1515
export const userRouteLoader = baseLoader.extend({
16-
queries: () => {
16+
useQueries: () => {
1717
const { userId } = useParams();
1818
const user = useGetUserQuery(userId);
1919
const posts = useGetPostsByUser(userId);
2020

21-
return [user, posts] as const;
21+
return {
22+
queries: {
23+
user,
24+
posts,
25+
},
26+
};
2227
},
2328
});
2429
```
2530

26-
The hook should return a `readonly array` of the `useQuery` results. This means that in typescript, you need to specify `as const` after the array.
31+
You can add as many queries as you'd like to `Response.queries`, and they will all aggregate to a common loading state.
2732

2833
## Accepting arguments
2934

3035
If you want the loader to take an argument, you can do that.
3136

3237
```tsx {2}
3338
export const userRouteLoader = baseLoader.extend({
34-
queries: (userId: string) => {
39+
useQueries: (userId: string) => {
3540
const user = useGetUserQuery(userId);
3641
const posts = useGetPostsByUser(userId);
3742

38-
return [user, posts] as const;
43+
return {
44+
queries: {
45+
user,
46+
posts,
47+
},
48+
};
3949
},
4050
});
4151
```
@@ -58,25 +68,30 @@ type UserRouteLoaderProps = Record<string, any> & {
5868
export const userRouteLoader = baseLoader.extend({
5969
queriesArg: (props: UserRouteLoaderProps) => props.userId,
6070
// type is now inferred from queriesArg return
61-
queries: (userId) => {
71+
useQueries: (userId) => {
6272
const user = useGetUserQuery(userId);
6373
const posts = useGetPostsByUser(userId);
6474

65-
return [user, posts] as const;
75+
return {
76+
queries: {
77+
user,
78+
posts,
79+
},
80+
};
6681
},
6782
});
6883
```
6984

7085
A component consuming this loader would pass the argument automatically through this pipeline:
7186

7287
```typescript
73-
// props → queriesArg → queries
74-
loaderArgs.queries(queriesArg(consumerProps));
88+
// props → queriesArg → useQueries
89+
loaderArgs.useQueries(queriesArg(consumerProps));
7590
```
7691

7792
```typescript
7893
<UserRoute userId="1234" />
7994
// → queriesArg({ userId: "1234" })
8095
// → "1234"
81-
// → loader.queries("1234")
96+
// → loader.useQueries("1234")
8297
```

docs/docs/Quick Guide/consume-loader.mdx

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,25 +14,29 @@ A convenient wrapper that ensures that the component is only rendered when it ha
1414

1515
This is definitely the preferred and optimal way to consume the loaders.
1616

17-
```tsx {8-22}
17+
```tsx {8-26}
1818
import { withLoader } from "@ryfylke-react/rtk-query-loader";
1919
import { userRouteLoader } from "../loaders/baseLoader";
2020

2121
type Props = {
2222
/* ... */
2323
};
2424

25-
export const UserRoute = withLoader((props: Props, queries) => {
25+
export const UserRoute = withLoader((props: Props, loader) => {
2626
// `queries` is typed correctly, and ensured to have loaded.
27-
const user = queries[0].data;
28-
const posts = queries[1].data;
27+
const {
28+
user,
29+
posts
30+
} = loader.queries;
31+
2932
return (
3033
<article>
3134
<header>
32-
<h2>{user.name}</h2>
35+
<h2>{user.data.name}</h2>
36+
{user.isFetching || posts.isFetching ? (<InlineLoading />) : null}
3337
</header>
3438
<main>
35-
{posts.map((post) => (...))}
39+
{posts.data.map((post) => (...))}
3640
</main>
3741
</article>
3842
);

docs/docs/examples.md

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ sidebar_position: 3
44

55
# Simple example
66

7-
```tsx {10-19,22-31}
7+
```tsx {10-23,26-35}
88
import {
99
withLoader,
1010
createLoader,
@@ -15,20 +15,24 @@ import { ErrorView } from "../components/ErrorView";
1515

1616
// Create a loader
1717
const userRouteLoader = createLoader({
18-
queries: () => {
18+
useQueries: () => {
1919
const { userId } = useParams();
2020
const userQuery = useGetUserQuery(userId);
2121

22-
return [userQuery] as const; // important
22+
return {
23+
queries: {
24+
userQuery,
25+
},
26+
};
2327
},
2428
onLoading: (props) => <div>Loading...</div>,
2529
onError: (props, error) => <ErrorView error={error} />,
2630
});
2731

2832
// Consume the loader
29-
const UserRoute = withLoader((props: {}, queries) => {
33+
const UserRoute = withLoader((props, loader) => {
3034
// Queries have successfully loaded
31-
const user = queries[0].data;
35+
const user = loader.queries.userQuery.data;
3236

3337
return (
3438
<div>

0 commit comments

Comments
 (0)