|
| 1 | +# Under the hood |
| 2 | + |
| 3 | +How does `rtk-query-loader` work _under the hood_? |
| 4 | + |
| 5 | +## Virtual DOM |
| 6 | + |
| 7 | +Imagine you have this component, rendered through `withLoader`: |
| 8 | + |
| 9 | +```tsx |
| 10 | +const loader = createLoader({...}); |
| 11 | + |
| 12 | +const Component = withLoader((props, queries) => {...}, loader); |
| 13 | + |
| 14 | +const App = () => { |
| 15 | + return ( |
| 16 | + <div> |
| 17 | + <Component /> |
| 18 | + </div> |
| 19 | + ) |
| 20 | +} |
| 21 | +``` |
| 22 | + |
| 23 | +What actually ends up rendering in the virtual DOM is something like this: |
| 24 | + |
| 25 | +```txt title="onLoading" |
| 26 | +div |
| 27 | +└── RTKLoader |
| 28 | + └── loader.onLoading(props) |
| 29 | +``` |
| 30 | + |
| 31 | +```txt title="onError" |
| 32 | +div |
| 33 | +└── RTKLoader |
| 34 | + └── loader.onError(props, error) |
| 35 | +``` |
| 36 | + |
| 37 | +```txt title="onFetching" |
| 38 | +div |
| 39 | +└── RTKLoader |
| 40 | + └── loader.onFetching(props, Component) |
| 41 | +``` |
| 42 | + |
| 43 | +```txt title="onSuccess" |
| 44 | +div |
| 45 | +└── RTKLoader |
| 46 | + └── null |
| 47 | + └── Component (with data) |
| 48 | + └── null |
| 49 | +``` |
| 50 | + |
| 51 | +```txt title="whileFetching" |
| 52 | +div |
| 53 | +└── RTKLoader |
| 54 | + └── loader.whileFetching.prepend() |
| 55 | + └── Component (with data) |
| 56 | + └── loader.whileFetching.append() |
| 57 | +``` |
| 58 | + |
| 59 | +## RTKLoader |
| 60 | + |
| 61 | +`RTKLoader` simply receives the loader and component, and handles returning the correct state depending on the query. You can take a look at how this component behaves [in the codebase](https://github.com/ryfylke-react-as/rtk-query-loader/blob/main/src/RTKLoader.tsx). |
| 62 | + |
| 63 | +## Custom `loaderComponent` |
| 64 | + |
| 65 | +You could pass a custom `loaderComponent` to your loaders, if you'd like: |
| 66 | + |
| 67 | +```typescript |
| 68 | +const CustomLoader = (props: CustomLoaderProps) => { |
| 69 | + // Handle rendering |
| 70 | +}; |
| 71 | + |
| 72 | +const loader = createLoader({ |
| 73 | + loaderComponent: CustomLoader, |
| 74 | + // ... |
| 75 | +}); |
| 76 | +``` |
| 77 | + |
| 78 | +This allows you to have really fine control over how the rendering of components using `withLoader` should work. |
0 commit comments