resourcerer 1.0.12 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,6 +15,7 @@ Additional features include:
15
15
  * fully declarative (no more writing any imperative Fetch API calls)
16
16
  * first-class loading and error state support
17
17
  * smart client-side caching
18
+ * lazy fetching
18
19
  * refetching
19
20
  * updating a component when a resource updates
20
21
  * zero dependencies
@@ -137,11 +138,13 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
137
138
  1. [Custom Resource Names](#custom-resource-names)
138
139
  1. [prefetches](#prefetches)
139
140
  1. [data](#data)
141
+ 1. [lazy](#lazy)
140
142
  1. [dependsOn](#dependson)
141
143
  1. [provides](#provides)
142
144
  1. [Data mutations](#data-mutations)
143
145
  1. [Serial Requests](#serial-requests)
144
146
  3. [Differences between useResources and withResources](#differences-between-useresources-and-withresources)
147
+ 4. [Using resourcerer with TypeScript](docs/typescript.md)
145
148
  4. [Caching Resources with ModelCache](#caching-resources-with-modelcache)
146
149
  5. [Declarative Cache Keys](#declarative-cache-keys)
147
150
  6. [Prefetch on Hover](#prefetch-on-hover)
@@ -157,7 +160,7 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
157
160
 
158
161
  `resourcerer` requires on React >= 16.8 but has no external dependencies.
159
162
 
160
- Note that Resourcerer uses ES2015 in its source and does no transpiling—including import/export (Local babel configuration is for testing, only).
163
+ Note that Resourcerer uses ESNext in its source and does no transpiling—including import/export (Local babel configuration is for testing, only).
161
164
  This means that if you're not babelifying your `node_modules` folder, you'll need to make an exception for this package, ie:
162
165
 
163
166
  ```js
@@ -241,7 +244,7 @@ ModelMap.add({TODOS: TodosCollection});
241
244
 
242
245
  (We can also pass custom prefixes for our prop names in a component, but [we'll get to that later](#custom-resource-names).)
243
246
 
244
- Back to the executor function. In the example above, you see it returns an object of `{[ResourceKeys.TODOS]: {}}`. In general, the object it should return is of type `{string<ResourceKey>: object<Options>}`, where `Options` is a generic map of config options. It can contain as many keys as resources you would like the component to request. In our initial example, the options object was empty. Further down, we'll go over the plethora of options and how to use them. For now let's take a look at some of the resource-related props this simple configuration provides our component.
247
+ Back to the executor function. In the example above, you see it returns an object of `{[ResourceKeys.TODOS]: {}}`. In general, the object it should return is of type `{[key: ResourceKeys]: Options}`, where `Options` is a generic map of config options. It can contain as many keys as resources you would like the component to request. In our initial example, the options object was empty. Further down, we'll go over the plethora of options and how to use them. For now let's take a look at some of the resource-related props this simple configuration provides our component.
245
248
 
246
249
 
247
250
  ## Other Props Returned from the Hook/Passed from the HOC (Loading States)
@@ -576,6 +579,49 @@ You can also use `data` to take advantage of [re-caching](/docs/advanced_topics.
576
579
 
577
580
  Like `params` and `options`, the `data` object will also be used in cache key generation if it has any fields specified in the model's static `cacheFields` property (See the [cache key section](#declarative-cache-keys) for more). For [Collections](/docs/collection.md#constructor), there is an equivalent `models` property, but again, these are seldom used.
578
581
 
582
+ ### lazy
583
+
584
+ Lazy fetching is one of resourcerer's most powerful features, allowing you to get a reference to a model without actually fetching it. If the model is ultimately fetched elsewhere on the page, the component that lazily fetched it will still listen for updates.
585
+
586
+ A great example of when this would be useful is for search results. Search results are read-only, but if you modify the entity of a result somewhere else in the page, you'd like to see it reflected in your search results. Yet you don't want to fetch the entity details for every search result and spam your API. Enter lazy loading:
587
+
588
+ ```jsx
589
+ // todo_search.jsx
590
+ getResources = ({TODOS_SEARCH}) => ({[TODOS_SEARCH]: {params: someSearchParams}});
591
+
592
+ function TodoSearch(props) {
593
+ const {todoSearchModel} = useResources(getResources, props);
594
+
595
+ return (
596
+ <Table>
597
+ <thead>
598
+ <TableHeader>Name</TableHeader>
599
+ <TableHeader>Last Updated</TableHeader>
600
+ </thead>
601
+ <tbody>
602
+ {todoSearchModel.get('results').map((todo) => <TodoSearchItem {...todo} />)}
603
+ </tbody>
604
+ </Table>
605
+ );
606
+ }
607
+
608
+ // todo_search_item.jsx
609
+ // the todoModel is never actually fetched here, it's only listened on, allowing any changes made elsewhere in the page to be reflected here.
610
+ getResources = ({TODO}) => ({[TODO]: {id: props.id, lazy: true}});
611
+
612
+ function TodoSearchItem(props) {
613
+ const {todoModel} = useResources(getResources, props);
614
+
615
+ return (
616
+ <tr>
617
+ <td>{todoModel.get('name') || props.name}</td>
618
+ <td>{todoModel.get('updated_at') || props.updated_at}</td>
619
+ </tr>
620
+ );
621
+ ```
622
+
623
+ If the todo model has been fetched already, we'll read straight from that. And if it gets updated, this component, via resourcerer, is listening for updates and will re-render to keep our entire UI in sync. Otherwise, we'll just fall back to our read-only search results. WIN!
624
+
579
625
  ### dependsOn
580
626
 
581
627
  See the section on [serial requests](#serial-requests).
@@ -620,20 +666,20 @@ So far we've only discussed fetching data. But `resourcerer` also makes it very
620
666
  const {hasLoaded, todosCollection} = useResources(getResources, props),
621
667
  todoModel = todosCollection.get(props.id),
622
668
 
623
- onSaveTodo = {
624
- // set some loading state...
669
+ onSaveTodo = {
670
+ // set some loading state...
625
671
 
626
- if (!props.id) {
627
- // create new todo!
628
- return todosCollection.create(attrs)
629
- .then(([model]) => // ...)
630
- .catch(() => alert('create failed'));
631
- .then(() => // remove loading state);
632
- }
672
+ if (!props.id) {
673
+ // create new todo!
674
+ return todosCollection.create(attrs)
675
+ .then(([model]) => // ...)
676
+ .catch(() => alert('create failed'));
677
+ .then(() => // remove loading state);
678
+ }
633
679
 
634
- // update existing
635
- todoModel.save(attrs).then(([model]) => ...).catch(() => alert('update failed'));
636
- };
680
+ // update existing
681
+ todoModel.save(attrs).then(([model]) => ...).catch(() => alert('update failed'));
682
+ };
637
683
 
638
684
  if (hasLoaded && props.id && !todoModel) {
639
685
  return <p>Todo not found.</p>;
@@ -678,7 +724,7 @@ function getUserIdFromItem(queueItemModel) {
678
724
  }
679
725
  ```
680
726
 
681
- In this simplified example, only `props.itemId` is initially present at the url `items/<itemId>`, and since the UserModel depends on `props.userId` being present, that model won’t initially get fetched. Only the QueueItemModel gets fetched at first; it has the `provides` option, which is a map of `<string: function>`, where the string is the prop that it provides to the HOC wrapper, and the function is a private static ‘transform’ function&mdash;it takes its model as an argument and returns the value for the prop it provides.
727
+ In this simplified example, only `props.itemId` is initially present at the url `items/<itemId>`, and since the UserModel depends on `props.userId` being present, that model won’t initially get fetched. Only the QueueItemModel gets fetched at first; it has the `provides` option, which is a map of `[key: string]: (model: Model | Collection) => any`, where the string is the prop that it provides to the HOC wrapper, and the function is a private static ‘transform’ function&mdash;it takes its model as an argument and returns the value for the prop it provides.
682
728
 
683
729
  So, in this case, `getUserIdFromItem` is the transform function, which takes the `queueItemModel` as an argument and returns the userId that will be assigned to `props.userId` (or, more accurately, will be set as state via `setResourceState` as described in the previous section). When the QueueItemModel resource returns, the transform function is invoked; at that point, `props.userId` exists, and the UserModel will be fetched. And we have serially requested our resources!
684
730
 
@@ -755,7 +801,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
755
801
 
756
802
  `resourcerer` handles resource storage and caching, so that when multiple components request the same resource with the same parameters or the same body, they receive the same model in response. If multiple components request a resource still in-flight, only a single request is made, and each component awaits the return of the same resource. Fetched resources are stored in the `ModelCache`. Under most circumstances, you won’t need to interact with directly; but it’s still worth knowing a little bit about what it does.
757
803
 
758
- The `ModelCache` is a simple module that contains a couple of Maps&mdash;one that is the actual cache `{cacheKey<string>: model<Model|Collection>}`, and one that is a component manifest, keeping track of all component instances that are using a given resource (unique by cache key). When a component unmounts, `resourcerer` will unregister the component instance from the component manifest; if a resource no longer has any component instances attached, it gets scheduled for cache removal. The timeout period for cache removal is two minutes by default (but can be changed, see [Configuring resourcerer](#configuring-resourcerer)), to allow navigating back and forth between pages without requiring a refetch of all resources. After the timeout, if no other new component instances have requested the resource, it’s removed from the `ModelCache`. Any further requests for that resource then go back through the network.
804
+ The `ModelCache` is a simple module that contains a couple of Maps&mdash;one that is the actual cache `{[cacheKey: string]: Model | Collection}`, and one that is a component manifest, keeping track of all component instances that are using a given resource (unique by cache key). When a component unmounts, `resourcerer` will unregister the component instance from the component manifest; if a resource no longer has any component instances attached, it gets scheduled for cache removal. The timeout period for cache removal is two minutes by default (but can be changed, see [Configuring resourcerer](#configuring-resourcerer), or [overridden on a model-class basis](/docs/model.md#static-cachetimeout)), to allow navigating back and forth between pages without requiring a refetch of all resources. After the timeout, if no other new component instances have requested the resource, it’s removed from the `ModelCache`. Any further requests for that resource then go back through the network.
759
805
 
760
806
  Again, it’s unlikely that you’ll use `ModelCache` directly while using `resourcerer`, but it’s helpful to know a bit about what’s going on behind-the-scenes.
761
807
 
@@ -900,7 +946,7 @@ ResourcesConfig.set(configObj);
900
946
 
901
947
  `ResourcesConfig.set` accepts an object with any of the following properties:
902
948
 
903
- * `cacheGracePeriod` (number in ms): the length of time a resource will be kept in the cache after being scheduled for removal (see the [caching section](#caching-resources-with-modelcache) for more). **Default:** 120000 (2 minutes).
949
+ * `cacheGracePeriod` (number in ms): the length of time a resource will be kept in the cache after being scheduled for removal (see the [caching section](#caching-resources-with-modelcache) for more). **Default:** 120000 (2 minutes). Note that each model class can provide its own timeout override.
904
950
 
905
951
  * `errorBoundaryChild` (JSX/React.Element): the element or component that should be rendered in the ErrorBoundary included in every `withResources` wrapping. By default, a caught error renders this child:
906
952
 
@@ -0,0 +1,299 @@
1
+ # Contents
2
+
3
+ 1. [Thoughts on the PENDING Resource](#thoughts-on-the-pending-resource)
4
+ 1. [Implicit dependent resources](#implicit-dependent-resources)
5
+ 1. [Unfetched Resources](#unfetched-resources)
6
+ 1. [Loading Overlays](#loading-overlays)
7
+ 1. [isOrWillBeLoading](#isorwillbeloading)
8
+ 1. [Recaching newly-saved models](#recaching-newly-saved-models)
9
+
10
+ ## Thoughts on the PENDING Resource
11
+
12
+ Using `dependsOn` in simple cases like the one highlighted in the [README](https://github.com/noahgrant/resourcerer/blob/master/README.md) is pretty straightforward and very powerful. But `PENDING` resources bring additional complexities to your resource logic, some of which are enumerated here:
13
+
14
+
15
+
16
+ 1. `PENDING` critical resources don’t contribute to `isLoading`/`hasErrored` states, but will keep your component from reaching a `hasLoaded` state. Semantically, this makes sense, because `hasLoaded` should only be true when all critical resources have loaded, regardless of when a resource’s request is made.
17
+
18
+ 1. When a `PENDING` resource request is not in flight, its model prop will still be the empty model instance whose properties are frozen (as happens when the resource is in the other three possible loading states). This is to more predictably handle our resources in our components. We don’t need to be defensive with syntax like:
19
+
20
+ ```js
21
+ todosCollection && todosCollection.toJSON(); // unnecessary
22
+ ```
23
+
24
+ Furthermore, if you've defined additional instance methods on your model, they will be present without being defensive:
25
+
26
+ ```js
27
+ todosCollection.myInstanceMethod(); // guaranteed not to error regardless of loading state
28
+ ```
29
+
30
+ 1. When a previously-`PENDING` but currently `LOADED` resource has its dependent prop removed, it goes back to a `PENDING` state (recall that if the dependent prop is changed, it gets put back into a `LOADING` state while the new resource is fetched). This puts us in an interesting state:
31
+
32
+ 1. `hasInitiallyLoaded` will remain true, as expected. But the `PENDING` resource’s prop&mdash;assuming the resource’s `cacheFields` list includes the dependent prop&mdash;will now return to the empty model/collection, so any child component that may remain in place after `hasInitiallyLoaded` may need to keep that in mind (if `shouldComponentUpdate` returns false when the new resource fetches, then this shouldn’t matter&mdash;see the next point).
33
+
34
+ 2. Recall that we can provide the dependent prop in one of two ways:
35
+ 1. We can include it in another resource’s `provides` property, in which case the dependent prop gets set as state within resourcerer.
36
+ 1. We can also set state in our client component and pass it to the executor function, but that requires an extra render cycle.
37
+ 1. We can modify the url in the component’s `componentDidUpdate`/`useEffect` (either url path or query parameter), which will filter the prop down.
38
+
39
+ When we provide using method (a), the dependent prop can be changed but not removed. When we provide using method (b), the dependent prop can be changed or removed.
40
+
41
+ So if we use method (b) and remove the dependent prop, we enter a state where `isLoading`, `hasLoaded`, and `hasErrored` are all false. And since we have to wait for a `componentDidUpdate`/`useEffect` to re-update the url with the dependent prop, a lifecycle passes with this state, and there’s really nothing we can do about it.
42
+
43
+ And again—`hasInitiallyLoaded` is still true and the model prop is empty, which can cause layout issues if you use, for example, an overlaid loader over a previously-rendered component. For this reason, if using classes/`withResources`, such a previously-rendered component should use `nextProps.hasLoaded` instead of `!nextProps.isLoading` in its `shouldComponentUpdate`:
44
+
45
+ ```js
46
+ // overlay-wrapped component, where a loader will show over previously-rendered children,
47
+ // which we want to then not update. but this component is also a child of a `withResources`
48
+ // component that has a dependent resource
49
+ shouldComponentUpdate(nextProps) {
50
+ // using `return !nextProps.isLoading;` would update the component in the above
51
+ // scenario, even though `nextProps.myDependentModel` would be empty
52
+ return nextProps.hasLoaded;
53
+ }
54
+
55
+ // this assumes that the parent is handling the `hasErrored` state. if it is not, then
56
+ // you may need to instead use:
57
+ shouldComponentUpdate(nextProps) {
58
+ return !(nextProps.isLoading || areAnyPending(nextProps.myDependentLoadingState));
59
+ }
60
+ ```
61
+
62
+ As an example of how we might be able to remove a dependent prop, consider someone navigating to a `/todos` url that auto-navigates to the first todo item and displays its details. The `todoItem` details resource depends on a `todoId` prop, which it gets in a `componentWillReceiveProps` via changing the url once the `todos` resource loads. So now we’re at `/todos/todo1234`. But if the user clicks the back button, we’ll be back at `/todos` with a cached `todos` resource and `PENDING` `todoItem` resource, and all three loading states set to `false`. (Yes, this is a bit contrived because you should actually replace the history entry in this case, but hopefully it helps to illuminate the issue.)
63
+
64
+ 3. In the case that the model's `cacheFields` does not include the dependent prop (ie, the prop is used solely for triggering the resource request and doesn't factor into the request data), the model will still exist in the cache when the dependent prop is removed. In this case, the loading state is still returned to PENDING, but the existing model will also be present in the return value.
65
+
66
+ ## Implicit dependent resources
67
+
68
+ Another way to effectively have a dependent resource is to use a conditional in your `getResources` method:
69
+
70
+ ```js
71
+ const getResources = (ResourceKeys, props) => ({
72
+ [ResourceKeys.TODOS]: {},
73
+ ...(props.todoId ? {[ResourceKeys.TODO_ITEM]: {data: {id: props.todoId}} : {})
74
+ });
75
+ ```
76
+
77
+ In general, using `dependsOn` is much more preferable, both in terms of semantics and functionality. The key difference here is that the dependent resource does not get put into a `PENDING` state, and `hasLoaded` depends on an unpredictable number of resources&mdash;for example, in the above scenario, what happens if `props.todoId` never arrives? Using `dependsOn`, `hasLoaded` would not be true, but using the conditional, it would be. This means that with the conditional, you can’t freely make assumptions behind the `hasLoaded` flag:
78
+
79
+ ```jsx
80
+ {hasLoaded ? (
81
+ // with the conditional, you don't know which resources are available. with
82
+ // `dependsOn`, you do
83
+ ) : null}
84
+ ```
85
+
86
+ That doesn’t mean that the conditional can’t be useful&mdash;it’s just that its use should be relegated to components that have two discrete forms&mdash;one in which the dependent prop is always present, and one in which the dependent prop is never present. If you’re unsure whether a prop might exist, notably because it comes from a providing resource, you should use `dependsOn`. A good example of when to use a conditional is in this fake component that sometimes fetches a user model and sometimes fetches an order model depending on the presence of an `orderId` prop:
87
+
88
+ ```js
89
+ const getResources = (ResourceKeys, {userId, orderId}) => ({
90
+ ...userId ? {[ResourceKeys.USER]: {options: {userId}} : {},
91
+ ...!userId && orderId ? {
92
+ [ResourceKeys.ORDER]: {
93
+ noncritical: true,
94
+ data: {id: orderId}
95
+ }
96
+ } : {}
97
+ });
98
+ ```
99
+
100
+ In this case, when the component is used as an order component (denoted by the presence of the `orderId` prop), we fetch the `order` resource. Otherwise, we don’t.
101
+
102
+ For all other uses of dependent resources, we should use `dependsOn`.
103
+
104
+
105
+ ## Unfetched Resources
106
+
107
+ You may find, at some point in your application, that you have a `PUT` endpoint for a resource but no `GET`; the 'read portion' of the resource is received as part of some parent resource. For example, imagine you have an accounts resource at `/accounts/{account_id}`, whose response has a `config` property with some account configuration settings. To update the configuration, you make a `PUT` to `/accounts/{account_id}/config`. But reading comes from the parent resource. `resourcerer` supports this via a `providesModels` static property on the model:
108
+
109
+ ```js
110
+ // resources_conifg.js
111
+ import {ResourceKeys, UnfetchedResources} from 'resourcerer';
112
+
113
+ ResourceKeys.add({
114
+ ACCOUNT: 'account',
115
+ ACCOUNT_CONFIG: 'accountConfig'
116
+ });
117
+
118
+ // add the ACCOUNT_CONFIG key to our set of UnfetchedResources
119
+ UnfetchedResources.add(ResourceKeys.ACCOUNT_CONFIG);
120
+
121
+
122
+ // account_model.js
123
+ export default class AccountModel extends Model {
124
+ url() {
125
+ return `/accounts/${this.accountId}`;
126
+ }
127
+
128
+ static cacheFields = ['accountId']
129
+
130
+ static providesModels = (accountModel, ResourceKeys) => [{
131
+ data: accountModel.get('config'),
132
+ modelKey: ResourceKeys.ACCOUNT_CONFIG,
133
+ options: {accountModel}
134
+ }]
135
+ })
136
+ ```
137
+
138
+ The `providesModels` property is a function that takes the parent model and the `ResourceKeys` as arguments and returns an array of resource configs. The resource configs have the same schema as the those used in our general executor functions. What this tells `resourcerer` to do is, after the parent model returns, instantiate the child model(s) and place them into the `ModelCache`. In other components, you can then access the model you know to exist in a `withResources` or `useResources` declaration:
139
+
140
+ ```js
141
+ // child_component.jsx, rendered only after the account model is known to return
142
+ @withResources((ResourceKeys, props) => ({[ResourceKeys.ACCOUNT_CONFIG]: {}}))
143
+ class ChildComponent extends React.Component {
144
+ // component has this.props.accountConfigModel from the cache!
145
+ onClickSomething() {
146
+ // and now you can update the config directly :)
147
+ this.props.accountConfigModel.save();
148
+ }
149
+ }
150
+ ```
151
+
152
+ In general, this should be used in cases where you can ascertain that the parent model has returned before trying to access the child model. However, if by chance it has not, and the child is not found in the cache, `resourcerer` will still not attempt to fetch it, because it is listed within the `UnfetchedResources` set. In that case, the model will get instantiated with no seed data and passed as a prop.
153
+
154
+ Also, note that the `modelKey` property is required here instead of optionally being inferred from the resource config's object property, as is the case in our general `useResources`/`withResources` declarations. This is because here, in contrast, the models are simply placed in the cache and not actually used as props for any component, so they don't need to be named. Accordingly, resource configs are also returned as a list here instead of an object.
155
+
156
+ The resource config objects within `providesModels` have the same schema, as mentioned, as normal. But they also accept an additional optional property, `shouldCache`, which is a function that takes the parent model and the resource config as an argument. If the function exists and returns false, the model will not get instantiated nor placed in the cache:
157
+
158
+ ```js
159
+ // account_model.js
160
+ export default class AccountModel extends Model {
161
+ // ...
162
+ static cacheFields: ['accountId']
163
+
164
+ static providesModels = (accountModel, ResourceKeys) => [{
165
+ data: accountModel.get('config'),
166
+ modelKey: ResourceKeys.ACCOUNT_CONFIG,
167
+ options: {accountModel},
168
+ // if this returns false, account config won't get instantiated and placed in the ModelCache
169
+ shouldCache: (accountModel, config) => accountModel.get('state') === 'ACTIVE'
170
+ }]
171
+ })
172
+ ```
173
+
174
+ ## Loading Overlays
175
+
176
+ You probably want to show loaders when you are moving between one model and the next. Because your resources are held as state, both exist in this intermediate state.
177
+ Both the hook and the HOC provide a `hasInitiallyLoaded` prop that is useful here. Here's an example of what it might look like (shown over one of [Sift](https://sift.com)'s Insights Charts):
178
+
179
+ ![loading_overlay](https://user-images.githubusercontent.com/1355779/69263885-10440e80-0b7b-11ea-811d-29aa404b91d2.gif)
180
+
181
+ Use it like:
182
+
183
+ ```jsx
184
+ import {useResources} from 'resourcerer';
185
+
186
+ const getResources = ({TODOS}, props) => ({[TODOS]: {}});
187
+
188
+ export default function UserTodos(props) {
189
+ const {isLoading, hasInitiallyLoaded, todosCollection} = useResources(getResources, props);
190
+
191
+ return (
192
+ <div className='MyComponent'>
193
+ // it's up to you to make this an OverlayLoader or InlineLoader, if you so choose.
194
+ {isLoading ? <Loader /> : null}
195
+ // this will render once first loaded and remain rendered with a previous
196
+ // model even while in a loading state. when a new resource request returns,
197
+ // this will render with the updated model and the loader will be removed.
198
+ {hasInitiallyLoaded ? (
199
+ <ul>
200
+ {todosCollection.map((todoModel) => (
201
+ <li key={todoModel.id}>{todoModel.get('name')}</li>
202
+ ))}
203
+ </ul>
204
+ ) : null}
205
+ </div>
206
+ );
207
+ }
208
+ ```
209
+
210
+ ## isOrWillBeLoading (`useResources` only)
211
+
212
+ Taking the previous example of [Loading Overlays](#loading-overlays) just a bit further, what if the todosCollection was 5000 entries long? Okay, you'd probably paginate. But that's not the point! Let's say it's an `<ExpensiveComponent />`, and as it is now, when we change loading states, the parent `MyComponent` would render `<ExpensiveComponent />` on every change, which will kill your UX. So let's wrap it in a `React.memo`!
213
+
214
+ But how do we tell `React.memo` when to not render? This is tricky for a couple of reasons:
215
+
216
+ * Because `useEffect`/`componentDidUpdate` occurs _after_ render, we actually have two renders we want to opt out of:
217
+ * parent props change
218
+ * render is called (opt out!) **See Note**
219
+ * resourcerer changes loaded state to loading from the change in props
220
+ * render is called (opt out!). parent shows the overlay loader
221
+ * request returns and loading state changes back to loaded
222
+ * render (we want this update!)
223
+
224
+ This is actually the reason why I am sad React did away with `componentWillReceiveProps` and does not offer an equivalent hook&mdash;using that instead would batch the props change and the loaded -> loading state change, and we'd only need to opt out of a single render. *sigh*. I digress.
225
+
226
+ * React.memo, unlike `shouldComponentUpdate`, does not change its `prevProps` if it skips a render. This makes sense if you think about `memo` being a higher-order-component&mdash;if the component doesn't update, its props don't change. But that makes it much harder to compare `prevProps` and `nextProps` when needing to skip two update cycles.
227
+
228
+ Enter `isOrWillBeLoading`. `isOrWillBeLoading` is a function returned by `useResources`/`withResources` that will take care of all these things for you, and you can invoke it in your `React.memo` [areEqual function](https://reactjs.org/docs/react-api.html#reactmemo). The previous example becomes:
229
+
230
+ ```jsx
231
+ import ExpensiveComponent from 'components/expensive_component/expensive_component';
232
+ import {memo} from 'react';
233
+ import {useResources} from 'resourcerer';
234
+
235
+ const getResources = ({TODOS}, props) => ({[TODOS]: {}});
236
+ const MemoizedExpensiveComponent = memo(ExpensiveComponent, (prevProps, nextProps) => nextProps.isOrWillBeLoading());
237
+
238
+ export default function UserTodos(props) {
239
+ const {isLoading, isOrWillBeLoading, hasInitiallyLoaded} = useResources(getResources, props);
240
+
241
+ return (
242
+ <div className='MyComponent'>
243
+ {isLoading ? <Loader /> : null}
244
+ {hasInitiallyLoaded ? <MemoizedExpensiveComponent {...{isOrWillBeLoading}} /> : null}
245
+ </div>
246
+ );
247
+ }
248
+ ```
249
+
250
+ **Note:** A future upgrade to this library will utilize a [render bailout](https://react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes) to remove this unnecessary render. The other two will still be required, though.
251
+
252
+ ## Recaching newly-saved models
253
+
254
+ A common pattern when creating a new instance of a resource is to keep it in state until the user decides to explicitly save it. For example, when setting up a new
255
+ TODO, we might fill out a form with its name, all kept in state, at a deep-linkable RESTful url that might be `/todos/new`. After the user saves the TODO, we get a
256
+ server-provided `id` property and we might navigate to `/todos/12345`, where `12345` is the new id. This presents an inconvenience: at `/new` we want to read from
257
+ state, but at `/{id}` we want to read from the saved model (this is compounded if the UI allows the user to edit in-place).
258
+
259
+ To accomodate this scenario, `resourcerer` provides a means of re-caching a model instance the first time it receives an id. Thus you can use it with `fetch: false` like
260
+ this:
261
+
262
+ ```jsx
263
+ import {useResources} from 'resourcerer';
264
+
265
+ const getResources = ({TODO}, props) => ({
266
+ [TODO]: {
267
+ data: {id: props.id},
268
+ fetch: !!props.id
269
+ }
270
+ });
271
+
272
+ export default function UserTodo(props) {
273
+ const {todoModel} = useResources(getResources, props),
274
+ onChange = (evt) => todoModel.set('name', evt.target.value),
275
+ onSubmit = todoModel.save()
276
+ .then(([model]) => !props.id ? navigate(`/todos/${model.id}`) : null)
277
+ .catch(() => notify('An error occurred');
278
+
279
+ return (
280
+ <form onSubmit={onSubmit}>
281
+ <label>
282
+ TODO:
283
+ <input name='name' onChange={onChange} value={todoModel.get('name')} />
284
+ </label>
285
+ <button>Save</button>
286
+ </form>
287
+ );
288
+ }
289
+ ```
290
+
291
+ What's so nice about this example is that there's no balancing between React state and model state; in either case you read from
292
+ the model requested from `resourcerer`. When you load `/todos/new`, nothing is fetched and the model is created first client-side;
293
+ when you load `/todos/{todosId}`, the todos resource is first fetched. Both cases, however, are treated identically. And because of
294
+ `resourcerer`'s recaching, when you save for the first time and navigate from `/todos/new` to `/todos/{todosId}`, the model is
295
+ taken from its 'new' cache key and placed in its 'id' cache key, obviating the need to re-request the resource and moving seamlessly
296
+ from one to the other.
297
+
298
+ ***NOTE:*** this is only for models requested individually and not as part of a larger collection. When adding a new model to a collection
299
+ that is fetched by `resourcerer`, you can accomplish the above without recaching.