|
| 1 | +import { SerializedError } from "@reduxjs/toolkit"; |
| 2 | +import { FetchBaseQueryError } from "@reduxjs/toolkit/dist/query"; |
1 | 3 | import React from "react"; |
2 | 4 | import { RTKLoader } from "./RTKLoader"; |
3 | 5 | import * as Types from "./types"; |
@@ -25,48 +27,51 @@ export const withLoader = < |
25 | 27 | ) as unknown as Types.ComponentWithLoaderData<P, R>; |
26 | 28 | } |
27 | 29 |
|
| 30 | + const onLoading = args.onLoading?.(props); |
| 31 | + |
| 32 | + const onError = args.onError |
| 33 | + ? (error: SerializedError | FetchBaseQueryError) => { |
| 34 | + if (!args.onError) return <React.Fragment />; |
| 35 | + return args.onError( |
| 36 | + props, |
| 37 | + error, |
| 38 | + query as Types.UseQueryResult<undefined> |
| 39 | + ); |
| 40 | + } |
| 41 | + : undefined; |
| 42 | + |
| 43 | + const onSuccess = (data: R) => ( |
| 44 | + <CachedComponent {...props} ref={data} /> |
| 45 | + ); |
| 46 | + |
| 47 | + const whileFetching = args.whileFetching |
| 48 | + ? { |
| 49 | + prepend: args.whileFetching.prepend?.( |
| 50 | + props, |
| 51 | + query?.data |
| 52 | + ), |
| 53 | + append: args.whileFetching.append?.( |
| 54 | + props, |
| 55 | + query?.data |
| 56 | + ), |
| 57 | + } |
| 58 | + : undefined; |
| 59 | + |
| 60 | + const onFetching = args?.onFetching?.( |
| 61 | + props, |
| 62 | + query.data |
| 63 | + ? () => onSuccess(query.data as R) |
| 64 | + : () => <React.Fragment /> |
| 65 | + ); |
| 66 | + |
28 | 67 | return ( |
29 | 68 | <RTKLoader |
30 | 69 | query={query} |
31 | | - loader={args.onLoading?.(props)} |
32 | | - onError={ |
33 | | - args.onError |
34 | | - ? (error) => |
35 | | - args.onError?.( |
36 | | - props, |
37 | | - error, |
38 | | - query as Types.UseQueryResult<undefined> |
39 | | - ) ?? <React.Fragment /> |
40 | | - : undefined |
41 | | - } |
42 | | - onSuccess={(data) => ( |
43 | | - <CachedComponent {...props} ref={data} /> |
44 | | - )} |
45 | | - whileFetching={ |
46 | | - args.whileFetching |
47 | | - ? { |
48 | | - prepend: args.whileFetching?.prepend?.( |
49 | | - props, |
50 | | - query?.data |
51 | | - ), |
52 | | - append: args.whileFetching?.append?.( |
53 | | - props, |
54 | | - query?.data |
55 | | - ), |
56 | | - } |
57 | | - : undefined |
58 | | - } |
59 | | - onFetching={args?.onFetching?.( |
60 | | - props, |
61 | | - query.data |
62 | | - ? () => ( |
63 | | - <CachedComponent |
64 | | - {...props} |
65 | | - ref={query.data as R} |
66 | | - /> |
67 | | - ) |
68 | | - : () => <React.Fragment /> |
69 | | - )} |
| 70 | + onSuccess={onSuccess} |
| 71 | + onError={onError} |
| 72 | + loader={onLoading} |
| 73 | + onFetching={onFetching} |
| 74 | + whileFetching={whileFetching} |
70 | 75 | /> |
71 | 76 | ); |
72 | 77 | }; |
|
0 commit comments