resourcerer 1.2.2 → 2.0.0-beta

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.
Files changed (59) hide show
  1. package/README.md +138 -164
  2. package/build/index.d.ts +9 -0
  3. package/build/index.js +9 -0
  4. package/build/lib/collection.d.ts +107 -0
  5. package/build/lib/collection.js +251 -0
  6. package/build/lib/config.d.ts +20 -0
  7. package/build/lib/config.js +23 -0
  8. package/build/lib/error-boundary.d.ts +12 -0
  9. package/build/lib/error-boundary.js +18 -0
  10. package/build/lib/events.d.ts +11 -0
  11. package/build/lib/events.js +12 -0
  12. package/build/lib/model-cache.d.ts +13 -0
  13. package/build/lib/model-cache.js +62 -0
  14. package/build/lib/model.d.ts +48 -0
  15. package/build/lib/model.js +170 -0
  16. package/build/lib/prefetch.d.ts +3 -0
  17. package/build/lib/prefetch.js +27 -0
  18. package/build/lib/request.d.ts +20 -0
  19. package/build/lib/request.js +53 -0
  20. package/build/lib/resourcerer.d.ts +13 -0
  21. package/build/lib/resourcerer.js +406 -0
  22. package/build/lib/sync.d.ts +18 -0
  23. package/build/lib/sync.js +58 -0
  24. package/build/lib/types.d.ts +66 -0
  25. package/build/lib/types.js +1 -0
  26. package/build/lib/utils.d.ts +14 -0
  27. package/build/lib/utils.js +87 -0
  28. package/docs/advanced_topics.md +9 -77
  29. package/docs/collection.md +28 -28
  30. package/docs/migrating_to_2.0.md +72 -0
  31. package/docs/model.md +21 -21
  32. package/docs/typescript.md +68 -20
  33. package/package.json +27 -30
  34. package/resourcerer.d.ts +50 -0
  35. package/test/collection.test.js +305 -316
  36. package/test/config.test.js +21 -75
  37. package/test/events.test.js +42 -41
  38. package/test/model-cache.test.js +99 -77
  39. package/test/model.test.js +204 -209
  40. package/test/prefetch.test.js +35 -61
  41. package/test/request.test.js +104 -109
  42. package/test/sync.test.js +132 -107
  43. package/test/utils.test.js +173 -159
  44. package/index.d.ts +0 -269
  45. package/index.js +0 -14
  46. package/lib/collection.js +0 -584
  47. package/lib/config.js +0 -131
  48. package/lib/constants.js +0 -6
  49. package/lib/error-boundary.js +0 -47
  50. package/lib/events.js +0 -19
  51. package/lib/model-cache.js +0 -131
  52. package/lib/model.js +0 -372
  53. package/lib/prefetch.js +0 -59
  54. package/lib/request.js +0 -126
  55. package/lib/resourcerer.js +0 -963
  56. package/lib/sync.js +0 -94
  57. package/lib/utils.js +0 -220
  58. package/test/model-mocks.js +0 -110
  59. package/test/setup.js +0 -63
package/README.md CHANGED
@@ -17,9 +17,10 @@ Additional features include:
17
17
  * smart client-side caching
18
18
  * lazy fetching
19
19
  * refetching
20
+ * forced cache invalidation
20
21
  * updating a component when a resource updates
21
22
  * zero dependencies
22
- * < 10kB!
23
+ * < 6kB!
23
24
 
24
25
  Getting started is easy:
25
26
 
@@ -40,11 +41,11 @@ export default class TodosCollection extends Collection {
40
41
 
41
42
  ```js
42
43
  // js/core/resourcerer-config.js
43
- import {ModelMap} from 'resourcerer';
44
+ import {register} from 'resourcerer';
44
45
  import TodosCollection from 'js/models/todos-collection';
45
46
 
46
47
  // choose any string as its key, which becomes its ResourceKey
47
- ModelMap.add({TODOS: TodosCollection});
48
+ register({todos: TodosCollection});
48
49
  ```
49
50
 
50
51
  ```js
@@ -59,7 +60,8 @@ import 'js/core/resourcerer-config';
59
60
  ```jsx
60
61
  import {useResources} from 'resourcerer';
61
62
 
62
- const getResources = ({TODOS}, props) => ({[TODOS]: {}});
63
+ // tell resourcerer which resource you want to fetch in your component
64
+ const getResources = (props) => ({todos: {}});
63
65
 
64
66
  function MyComponent(props) {
65
67
  const {
@@ -95,7 +97,8 @@ import 'js/core/resourcerer-config';
95
97
  import React from 'react';
96
98
  import {withResources} from 'resourcerer';
97
99
 
98
- @withResources(({TODOS}, props) => ({[TODOS]: {}}))
100
+ // tell resourcerer which resource you want to fetch in your component
101
+ @withResources((props) => ({todos: {}}))
99
102
  class MyComponent extends React.Component {
100
103
  render() {
101
104
  // when MyComponent is mounted, the todosCollection is fetched and available
@@ -139,6 +142,7 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
139
142
  1. [prefetches](#prefetches)
140
143
  1. [data](#data)
141
144
  1. [lazy](#lazy)
145
+ 1. [minDuration](#minduration)
142
146
  1. [dependsOn](#dependson)
143
147
  1. [provides](#provides)
144
148
  1. [Data mutations](#data-mutations)
@@ -149,19 +153,21 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
149
153
  5. [Declarative Cache Keys](#declarative-cache-keys)
150
154
  6. [Prefetch on Hover](#prefetch-on-hover)
151
155
  7. [Refetching](#refetching)
152
- 8. [Tracking Request Times](#tracking-request-times)
156
+ 8. [Cache Invalidation](#cache-invalidation)
157
+ 9. [Tracking Request Times](#tracking-request-times)
153
158
  1. [Configuring resourcerer](#configuring-resourcerer)
154
159
  1. [FAQs](#faqs)
160
+ 1. [Migrating to v2.0](#migrating-to-v20)
155
161
 
156
162
 
157
163
  # Installation
158
164
 
159
- `$ npm i resourcerer`
165
+ `$ npm i resourcerer` or `yarn add resourcerer`
160
166
 
161
167
  `resourcerer` requires on React >= 16.8 but has no external dependencies.
162
168
 
163
- Note that Resourcerer uses ESNext in its source and does no transpiling&mdash;including import/export (Local babel configuration is for testing, only).
164
- This means that if you're not babelifying your `node_modules` folder, you'll need to make an exception for this package, ie:
169
+ Note: Resourcerer is written in TypeScript and is compiled to ESNext. It does no further transpiling&mdash;including `import`/`export`.
170
+ If you are using TypeScript yourself, this won't be a problem. If you're not, and you're not babelifying (or similar) your `node_modules` folder, you'll need to make an exception for this package, ie:
165
171
 
166
172
  ```js
167
173
  // webpack.config.js or similar
@@ -178,22 +184,22 @@ module: {
178
184
 
179
185
  1. **Props**. Going forward in this tutorial, we'll try to describe behavior of both the `useResources` hook and the `withResources` HOC at once; we'll also rotate between the two in examples. Note that if we talking about a passed prop of, for example `isLoading`, that that corresponds to an `isLoading` property returned from the hook and a `this.props.isLoading` prop passed down from the HOC.
180
186
 
181
- 1. **ResourceKeys**. These are the keys added to the `ModelMap` (discussed above in the introduction) that link to your model constructors. They are passed to the executor functions and are used to tell the hook or HOC which resources to request.
187
+ 1. **ResourceKeys**. These are the keys of the object passed to the `register` function in your top-level `resourcerer-config.js` file (discussed above in the introduction). The object is of type `Record<ResourceKeys, new () => Model | new () => Collection>`. These keys are passed to the executor functions and are used to tell the hook or HOC which resources to request.
182
188
 
183
- 1. **Executor Function**. The executor function is a function that both the hook and HOC accept that declaratively describes which resources to request and with what config options. In these docs you'll often see it assigned to a variable called `getResources`. It accepts `ResourceKeys` and `props` as arguments and may look like, as we'll explore in an example later:
189
+ 1. **Executor Function**. The executor function is a function that both the hook and HOC accept that declaratively describes which resources to request and with what config options. In these docs you'll often see it assigned to a variable called `getResources`. It accepts `props` as arguments and may look like, as we'll explore in an example later:
184
190
 
185
191
  ```js
186
- const getResources = ({USER}, props) => ({[USER]: {options: {userId: props.id}}});
192
+ const getResources = (props) => ({user: {path: {userId: props.id}}});
187
193
  ```
188
194
 
189
195
  or
190
196
 
191
197
  ```js
192
- const getResources = ({USER_TODOS}, props) => {
198
+ const getResources = (props) => {
193
199
  const now = Date.now();
194
200
 
195
201
  return {
196
- [USER_TODOS]: {
202
+ userTodos: {
197
203
  params: {
198
204
  limit: 20,
199
205
  end_time: now,
@@ -207,17 +213,15 @@ module: {
207
213
 
208
214
  It returns an object whose keys represent the resources to fetch and whose values are **Resource Configuration Objects** that we'll discuss later (and is highlighted below).
209
215
 
210
- 1. **Resource Configuration Object (resource config)**. In the object returned by our executor function, each entry has a key equal to one of the `ResourceKeys` and whose value we will refer to in this document as a Resource Configuration Object. It holds the declarative instructions that `useResources` and `withResources` will use to request the resource.
216
+ 1. **Resource Configuration Object**. In the object returned by our executor function, each entry has a key equal to one of the `ResourceKeys` and whose value we will refer to in this document as a Resource Configuration Object, or Resource Config for short. It holds the declarative instructions that `useResources` and `withResources` will use to request the resource.
211
217
 
212
218
  # Tutorial
213
219
 
214
220
  Okay, back to the initial example. Let's take a look at our `useResources` usage in the component:
215
221
 
216
222
  ```js
217
- // Note: in these docs, you will see a combination of `ResourceKeys` in the executor
218
- // function as well as its more common destructured version, ie:
219
- // `@withResources(({TODOS}, props) => ({[TODOS]: {}}))`
220
- const getResources = (ResourceKeys, props) => ({[ResourceKeys.TODOS]: {}});
223
+ // `@withResources((props) => ({todos: {}}))`
224
+ const getResources = (props) => ({todos: {}});
221
225
 
222
226
  export default function MyComponent(props) {
223
227
  const resources = useResources(getResources, props);
@@ -227,24 +231,22 @@ export default function MyComponent(props) {
227
231
  ```
228
232
 
229
233
  You see that `useResources` takes an executor function that returns an object. The executor function
230
- takes two arguments: an object of `ResourceKeys` and the current props. Where does `ResourceKeys` come
231
- from? From the ModelMap in the config file we added to earlier!
234
+ takes a single argument: the current props, which are component props when you use `withResources`, but can be anything when you use `useResources`. The executor function returns an object whose keys are `ResourceKeys` and whose values are Resource Config objects. Where do `ResourceKeys` come from? From the object passed to the `register` method in the config file we added earlier!
232
235
 
233
236
  ```js
234
237
  // js/core/resourcerer-config.js
235
- import {ModelMap} from 'resourcerer';
238
+ import {register} from 'resourcerer';
236
239
  import TodosCollection from 'js/models/todos-collection';
237
240
 
238
- // after adding this key, resourcerer will add an identical key to the `ResourceKeys` object with a
239
- // camelCased version as its value. `ResourceKeys.TODOS` can then be used in our executor functions to reference
240
- // the Todos resource. The camelCased 'todos' string value will be the default prefix added to all todos-related
241
- // props passed from the HOC to the wrapped component. That's why we have `props.todosCollection`!
242
- ModelMap.add({TODOS: TodosCollection});
241
+ // after adding this key, `todos` can be used in our executor functions to reference the Todos resource.
242
+ // The 'todos' string value will also be the default prefix for all todos-related return values.
243
+ // That's why we have `props.todosCollection`!
244
+ register({todos: TodosCollection});
243
245
  ```
244
246
 
245
247
  (We can also pass custom prefixes for our prop names in a component, but [we'll get to that later](#custom-resource-names).)
246
248
 
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.
249
+ Back to the executor function. In the example above, you see it returns an object of `{todos: {}}`. In general, the object it should return is of type `{[key: ResourceKeys]: ResourceConfigObject}`, where `ResourceConfigObject` 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 Resource Config 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.
248
250
 
249
251
 
250
252
  ## Other Props Returned from the Hook/Passed from the HOC (Loading States)
@@ -252,7 +254,7 @@ Back to the executor function. In the example above, you see it returns an objec
252
254
  Of course, in our initial example, the `todosCollection` won’t be populated with data immediately since, after all, the resource has to be fetched from the API. Some of the most **significant** and most common React UI states we utilize are whether a component’s critical resources have loaded entirely, whether any are still loading, or whether any have errored out. This is how we can appropriately cover our bases&mdash;i.e., we can ensure the component shows a loader while the resource is still in route, or if something goes wrong, we can ensure the component will still fail gracefully and not break the layout. To address these concerns, the `useResources` hook/`withResources` HOC gives you several loading state helper props. From our last example:
253
255
 
254
256
 
255
- - `todosLoadingState` (can be equal to any of the [LoadingStates constants](https://github.com/noahgrant/resourcerer/blob/master/lib/constants.js). There will be one for each resource, and the property names will be equal to `${resourceKey}LoadingState`)
257
+ - `todosLoadingState` (can be equal to any of the [LoadingStates constants](https://github.com/noahgrant/resourcerer/blob/06ed847a8d8d0daefd3ad1b7634d887767d338ac/lib/types.ts#L4). There will be one for each resource, and the property names will be equal to `${resourceKey}LoadingState`)
256
258
  - `hasLoaded` {boolean} - all critical resources have successfully completed and are ready to be used by the component
257
259
  - `isLoading` {boolean} - any of the critical resources are still in the process of being fetched
258
260
  - `hasErrored` {boolean} - any of the critical resource requests did not complete successfully
@@ -260,9 +262,9 @@ Of course, in our initial example, the `todosCollection` won’t be populated wi
260
262
  `isLoading` , `hasLoaded` , and `hasErrored` are not based on individual loading states, but are rather a collective loading state for the aforementioned-critical component resources. In the previous example, the todos resource is the only critical resource, so `isLoading` / `hasLoaded` / `hasErrored` are solely based on `todosLoadingState`. But we can also add a non-critical `users` resource, responsible, say, for only display users' names alongside their TODOs&mdash;a small piece of the overall component and not worth delaying render over. Here’s how we do that:
261
263
 
262
264
  ```js
263
- const getResources = ({TODOS, USERS}, props) => ({
264
- [TODOS]: {},
265
- [USERS]: {noncritical: true}
265
+ const getResources = (props) => ({
266
+ todos: {},
267
+ users: {noncritical: true}
266
268
  });
267
269
 
268
270
  function MyClassWithTodosAndAUsers(props) {
@@ -270,7 +272,7 @@ function MyClassWithTodosAndAUsers(props) {
270
272
  }
271
273
  ```
272
274
 
273
- `MyClassWithDecisionsAndAnalysts` will now receive the following loading-related props, assuming we've assigned the `USERS` key a string value of `'users'` in our config file:
275
+ `MyClassWithTodosAndAUsers` will now receive the following loading-related props, assuming we've registered a `usersCollection` in our config file:
274
276
 
275
277
  - `todosLoadingState`
276
278
  - `usersLoadingState`
@@ -283,7 +285,7 @@ In this case, `isLoading` , et al, are only representative of `todosLoadingState
283
285
  Here’s how might use that to our advantage in `MyClassWithTodosAndAUsers` :
284
286
 
285
287
  ```jsx
286
- import {haveAllLoaded} from 'resourcerer';
288
+ import {Utils} from 'resourcerer';
287
289
 
288
290
  function MyClassWithTodosAndAUsers(props) {
289
291
  const {
@@ -318,11 +320,11 @@ function MyClassWithTodosAndAUsers(props) {
318
320
  {todosCollection.map((todoModel) => (
319
321
  <li key={todoModel.id}>
320
322
  // pure function that accepts loading states as arguments
321
- {haveAllLoaded(usersLoadingState) ?
323
+ {Utils.hasLoaded(usersLoadingState) ?
322
324
  getUserName(todoModel.get('userId')) :
323
325
  // if you're anti-loader, you could opt to render nothing and have the
324
326
  // user name simply appear in place after loading
325
- <Loader size={Loader.Sizes.SMALL} />}
327
+ <Loader type="inline" />}
326
328
  {todoModel.get('name')}
327
329
  </li>
328
330
  )}
@@ -351,17 +353,17 @@ Let's say we wanted to request not the entire users collection, but just a speci
351
353
 
352
354
  ```js
353
355
  // js/core/resourcerer-config.js
354
- import {ModelMap} from 'resourcerer';
356
+ import {register} from 'resourcerer';
355
357
  import TodosCollection from 'js/models/todos-collection';
356
358
  import UserModel from 'js/models/user-model';
357
359
 
358
- ModelMap.add({
359
- TODOS: TodosCollection,
360
- USER: UserModel
360
+ register({
361
+ todos: TodosCollection,
362
+ user: UserModel
361
363
  });
362
364
  ```
363
365
 
364
- And here's what our model might look like:
366
+ And here's what our model might look like (NOTE: use a Model when you've got one resource instance, and a Collection when you've got a list of that resource):
365
367
 
366
368
  ```js
367
369
  // js/models/user-model.js
@@ -370,7 +372,7 @@ import {Model} from 'resourcerer';
370
372
  export default class UserModel extends Model {
371
373
  url({userId}) {
372
374
  // `userId` is passed in here because we have
373
- // `options: {userId: props.userId}` in the resource config object
375
+ // `path: {userId: props.id}` in the resource config object
374
376
  return `/users/${userId}`;
375
377
  }
376
378
 
@@ -380,14 +382,14 @@ export default class UserModel extends Model {
380
382
 
381
383
  The `dependencies` static property is important here, as we'll see in a second; it is a list of properties that `resourcerer` will use to generate a cache key for the model. It will look for the `userId` property in the following places, in order:
382
384
 
383
- 1. the `options` object
385
+ 1. the `path` object
384
386
  1. the `data` object
385
387
  1. the `params` object
386
388
 
387
389
  All three of these come from via the [Resource Configuration Object](#nomenclature) that is returned from our executor function; it might look like this:
388
390
 
389
391
  ```jsx
390
- const getResources = ({USER}, props) => ({[USER]: {options: {userId: props.id}}})
392
+ const getResources = (props) => ({user: {path: {userId: props.id}}})
391
393
 
392
394
  // hook
393
395
  function MyComponent(props) {
@@ -405,14 +407,14 @@ Assuming we have a `props.id` equal to `'noahgrant'`, this setup will put `MyCom
405
407
 
406
408
  ### *...and here's the best part:*
407
409
 
408
- Let's say that `props.id` changes to a different user. `MyComponentWithAUser` will get put _back_ into a loading state while the new endpoint is fetched, _without us having to do anything!_ This works because our model has dictated that its models should be cached by a `userId` field, which is passed to it in the [`options` property](#options).
410
+ Let's say that `props.id` changes to a different user. `MyComponentWithAUser` will get put _back_ into a loading state while the new endpoint is fetched, _without us having to do anything!_ This works because our model has dictated that its models should be cached by a `userId` field, which is passed to it in the [`path` property](#path).
409
411
 
410
412
  ## Changing Props
411
413
  In general, there are two ways to change `props.id` as in the previous example:
412
414
 
413
- 1. Change the url, which is the top-most state-carrying entity of any application. The url can be changed either by path parameter or query paramter, i.e. `example.com/users/noahgrant` -> `example.com/users/fredsadaghiani`, or `example.com/users?id=noahgrant` -> `example.com/users?id=fredsadaghiani`. In this case, each prop change is _indexable_, which is sometimes desirable, sometimes not.
415
+ 1. Change the url, which is the top-most state-carrying entity of any application. The url can be changed either by path parameter or query paramter, i.e. `example.com/users/noahgrant` -> `example.com/users/bobdonut`, or `example.com/users?id=noahgrant` -> `example.com/users?id=bobdonut`. In this case, each prop change is _indexable_, which is sometimes desirable, sometimes not.
414
416
 
415
- 1. Change internal application state. For these cases, `useResources`/`withResources` make available another handy prop: `setResourceState`. `setResourceState` is a function that has the same method signature as the `useState` we all know and love. It sets internal hook/HOC state, which is then returned/passed down, respectively, overriding any initial prop, ie `setResourceState((state) => ({...state, id: 'fredsadaghiani'}))`. This is _not_ indexable.
417
+ 1. Change internal application state. For these cases, `useResources`/`withResources` make available another handy prop: `setResourceState`. `setResourceState` is a function that has the same method signature as the `useState` we all know and love. It sets internal hook/HOC state, which is then returned/passed down, respectively, overriding any initial prop, ie `setResourceState((state) => ({...state, id: 'bobdonut'}))`. This is _not_ indexable.
416
418
 
417
419
  Note that `setResourceState` is very useful for the `withResources` HOC because it allows you to 'lift' state above the fetching component that otherwise would not be possible. For `useResources`, it is a nice-to-have in some cases, but because you can always define your own `useState` above the `useResources` invocation, you may find that you use it less often.
418
420
 
@@ -425,11 +427,11 @@ In general, there are two ways to change `props.id` as in the previous example:
425
427
  The `params` option is passed directly to the [sync method](/docs/model.md#sync) and sent either as stringified query params (GET requests) or as a body (POST/PUT). Its properties are also referenced when generating a cache key if they are listed in a model's static `dependencies` property (See the [cache key section](#declarative-cache-keys) for more). Let's imagine that we have a lot of users and a lot of todos per user. So many that we only want to fetch the todos over a time range selected from a dropdown, sorted by a field also selected by a dropdown. These are query parameters we'd want to pass in our `params` property:
426
428
 
427
429
  ```js
428
- @withResources((ResourceKeys, props) => {
430
+ @withResources((props) => {
429
431
  const now = Date.now();
430
432
 
431
433
  return {
432
- [ResourceKeys.USER_TODOS]: {
434
+ userTodos: {
433
435
  params: {
434
436
  limit: 20,
435
437
  end_time: now,
@@ -447,29 +449,29 @@ Now, as the prop fields change, the params sent with the request changes as well
447
449
  `https://example.com/users/noahgrant/todos?limit=20&end_time=1494611831024&start_time=1492019831024&sort_field=importance`
448
450
 
449
451
 
450
- ### options
452
+ ### path
451
453
 
452
- [As referenced previously](#requesting-prop-driven-data), all properties on an `options` object will be passed into a model's/collection's `url` function. This makes it an ideal place to add _path parameters_ (contrast this with the [`params` object](#params), which is the place to add query (GET) or body (POST/PUT/PATCH) parameters). It will also be used in cache key generation if it has any fields specified in the model's static `dependencies` property (See the [cache key section](#declarative-cache-keys) for more). Continuing with our User Todos example, let's add an `options` property:
454
+ [As referenced previously](#requesting-prop-driven-data), all properties on an `path` object will be passed into a model's/collection's `url` function. This makes it an ideal place to add _path parameters_ (contrast this with the [`params` object](#params), which is the place to add query (GET) or body (POST/PUT/PATCH) parameters). It will also be used in cache key generation if it has any fields specified in the model's static `dependencies` property (See the [cache key section](#declarative-cache-keys) for more). Continuing with our User Todos example, let's add an `path` property:
453
455
 
454
456
  ```js
455
- const getResources = (ResourceKeys, props) => {
457
+ const getResources = (props) => {
456
458
  const now = Date.now();
457
459
 
458
460
  return {
459
- [ResourceKeys.USER_TODOS]: {
461
+ userTodos: {
460
462
  params: {
461
463
  limit: 20,
462
464
  end_time: now,
463
465
  start_time: now - props.timeRange,
464
466
  sort_field: props.sortField
465
467
  },
466
- options: {userId: props.userId}
468
+ path: {userId: props.userId}
467
469
  }
468
470
  };
469
471
  };
470
472
  ```
471
473
 
472
- Here, this UserTodosCollection instance will get a `userId` property passed to both its `url` function as well as the options in its [constructor method](/docs/collection.md#constructor). We'll also want to add the `'userId'` string to the collection's [static `dependencies` array](#requesting-prop-driven-data), because each cached collection should be specific to the user:
474
+ Here, this UserTodosCollection instance will get a `userId` property passed to its `url` function. We'll also want to add the `'userId'` string to the collection's [static `dependencies` array](#requesting-prop-driven-data), because each cached collection should be specific to the user:
473
475
 
474
476
  ```js
475
477
  // js/models/user_todos_collection.js
@@ -490,7 +492,7 @@ As alluded to in the [Other Props](#other-props-returned-from-the-hookpassed-fro
490
492
 
491
493
  - De-prioritize fetching the resource until after all critical resources have been fetched
492
494
  - Remove the resource from consideration within the component-wide loading states (`hasLoaded`, `isLoading`, `hasErrored`), giving us the ability to render without waiting on those resources
493
- - Can set our own UI logic around displaying noncritical data based on their individual loading states, ie `usersLoadingState`, which can be passed to the pure helper methods, `haveAllLoaded`, `haveAnyErrored`, and `areAnyLoading` from `resourcerer`.
495
+ - Can set our own UI logic around displaying noncritical data based on their individual loading states, ie `usersLoadingState`, which can be passed to the pure helper methods, `Utils.hasLoaded`, `Utils.hasErrored`, and `Utils.isLoading` from `resourcerer`.
494
496
 
495
497
 
496
498
 
@@ -499,7 +501,7 @@ As alluded to in the [Other Props](#other-props-returned-from-the-hookpassed-fro
499
501
  Sometimes you want the latest of a resource, bypassing whatever model has already been cached in your application. To accomplish this, simply pass a `force: true` in a resource's config. The force-fetched response will replace any prior model in the cache.
500
502
 
501
503
  ```js
502
- const getResources = ({LATEST_STATS}, props) => ({[LATEST_STATS]: {force: true}});
504
+ const getResources = (props) => ({latestStats: {force: true}});
503
505
 
504
506
  function MyComponentWithLatestStats(props) {
505
507
  const {latestStatsModel} = useResources(getResources, props);
@@ -508,12 +510,15 @@ Sometimes you want the latest of a resource, bypassing whatever model has alread
508
510
 
509
511
  The resource will only get force-requested when the component mounts; the `force` flag will get ignored on subsequent updates. If you need to refetch after mounting to get the latest resource, use [refetch](#refetching).
510
512
 
513
+ This behavior is similar to the behavior you get with [cache invalidation](#cache-invalidation).
514
+
515
+
511
516
  ### Custom Resource Names
512
517
 
513
- Passing a `modelKey: <ResourceKeys>` option allows you to pass a custom name as the `withResources` key, which will become the base name for component-related props passed down to the component. For example, this configuration:
518
+ Passing a `resourceKey: <ResourceKeys>` option allows you to pass a custom name as the `withResources` key, which will become the base name for component-related props passed down to the component. For example, this configuration:
514
519
 
515
520
  ```js
516
- const getResources = (ResourceKeys, props) => ({myRadTodos: {modelKey: ResourceKeys.TODOS});
521
+ const getResources = (props) => ({myRadTodos: {resourceKey: todos});
517
522
 
518
523
  export default function MyComponentWithTodos {
519
524
  const {
@@ -527,6 +532,8 @@ export default function MyComponentWithTodos {
527
532
 
528
533
  would still fetch the todos resource, but the properties returned/props passed to the `MyComponentWithTodos` instance will be `myRadTodosCollection`, `myRadTodosLoadingState`, and `myRadTodosStatus`, etc, as shown. This also allows us to fetch the same resource type multiple times for a single component.
529
534
 
535
+ NOTE: when using resourcerer with [Typescript](docs/typescript.md) (recommended), it will complain about custom resource names, but it _will_ work. For now, you'll need to `// @ts-ignore`, but please submit a PR :).
536
+
530
537
  ### prefetches
531
538
 
532
539
  This option is an array of props objects that represent what is _different_ from the props in the original resource. For each array entry, a new resource configuration object will be calculated by merging the current props with the new props, and the resulting request is made. In contrast to the original resource, however, _no props representing the prefetched requests are returned or passed down to any children (ie, there are no loading state props, no model props, etc)_. They are simply returned and kept in memory so that whenever they are requested, they are already available.
@@ -534,12 +541,12 @@ This option is an array of props objects that represent what is _different_ from
534
541
  A great example of this is for pagination. Let's take our previous example and add a `from` property to go with our `limit` that is based on the value of a `page` prop ([tracked either by url parameter or by `setResourceState`](#changing-props)). We want to request the first page but also prefetch the following page because we think the user is likely to click on it:
535
542
 
536
543
  ```js
537
- const getResources = (ResourceKeys, props) => {
544
+ const getResources = (props) => {
538
545
  const now = Date.now();
539
546
  const REQUESTS_PER_PAGE = 20;
540
547
 
541
548
  return {
542
- [ResourceKeys.USER_TODOS]: {
549
+ userTodos: {
543
550
  params: {
544
551
  from: props.page * REQUESTS_PER_PAGE,
545
552
  limit: REQUESTS_PER_PAGE,
@@ -547,7 +554,7 @@ const getResources = (ResourceKeys, props) => {
547
554
  start_time: now - props.timeRange,
548
555
  sort_field: props.sortField
549
556
  },
550
- options: {userId: props.userId},
557
+ path: {userId: props.userId},
551
558
  // this entry is how we expect the props to change. in this case, we want props.page to be
552
559
  // incremented. the resulting prefetched request will have a `from` value of 20, whereas the
553
560
  // original request will have a `from` value of 0. The `userTodosCollection` returned (hook) or
@@ -558,10 +565,7 @@ const getResources = (ResourceKeys, props) => {
558
565
  };
559
566
  ```
560
567
 
561
- When the user clicks on a 'next' arrow that updates page state, the collection will already be in the cache, and it will get passed as the new `userTodosCollection`. Accordingly, the third page will then get prefetched (`props.page` equal to 2 and `from` equal to 40). Two important things to note here:
562
-
563
- 1. Don't forget to add `from` to the [`dependencies`](#declarative-cache-keys) list!
564
- 1. The prefetched model does not get components registered to it; therefore, it is immediately scheduled for removal after the specified [cacheGracePeriod](#configuring). If the user clicks the next arrow, it then becomes the 'active' model and the `UserTodos` component will get registered to it, clearing the removal timer (see the [caching](caching-resources-with-modelcache) section).
568
+ When the user clicks on a 'next' arrow that updates page state, the collection will already be in the cache, and it will get passed as the new `userTodosCollection`. Accordingly, the third page will then get prefetched (`props.page` equal to 2 and `from` equal to 40). Don't forget to add `from` to the [`dependencies`](#declarative-cache-keys) list!
565
569
 
566
570
  If you're looking to optimistically prefetch resources when a user hovers, say, over a link, see the [Prefetch on Hover](#prefetch-on-hover) section.
567
571
 
@@ -570,7 +574,7 @@ If you're looking to optimistically prefetch resources when a user hovers, say,
570
574
  Pass in a data hash to initialize a Model instance with data before initially fetching. This is passed directly to the [model](/docs/model.md#constructor) `constructor` method, and is typically much less useful than providing the properties directly to the [`params`](#params) property. One place it might be useful is to seed a model with an id you already have:
571
575
 
572
576
  ```js
573
- getResources = ({CUSTOMER}) => ({[CUSTOMER]: {data: {id: props.customerId}}});
577
+ getResources = () => ({customer: {data: {id: props.customerId}}});
574
578
 
575
579
  function MyCustomerComponent(props) {
576
580
  const {customerModel} = useResources(getResources, props);
@@ -582,7 +586,7 @@ function MyCustomerComponent(props) {
582
586
 
583
587
  You can also use `data` to take advantage of [re-caching](/docs/advanced_topics.md#recaching-newly-saved-models).
584
588
 
585
- 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 `dependencies` 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.
589
+ Like `params` and `path`, the `data` object will also be used in cache key generation if it has any fields specified in the model's static `dependencies` property (See the [cache key section](#declarative-cache-keys) for more).
586
590
 
587
591
  ### lazy
588
592
 
@@ -592,7 +596,7 @@ A great example of when this would be useful is for search results. Search resul
592
596
 
593
597
  ```jsx
594
598
  // todo_search.jsx
595
- getResources = ({TODOS_SEARCH}) => ({[TODOS_SEARCH]: {params: someSearchParams}});
599
+ getResources = () => ({todosSearch: {params: someSearchParams}});
596
600
 
597
601
  function TodoSearch(props) {
598
602
  const {todoSearchModel} = useResources(getResources, props);
@@ -612,7 +616,7 @@ function TodoSearch(props) {
612
616
 
613
617
  // todo_search_item.jsx
614
618
  // the todoModel is never actually fetched here, it's only listened on, allowing any changes made elsewhere in the page to be reflected here.
615
- getResources = ({TODO}) => ({[TODO]: {id: props.id, lazy: true}});
619
+ getResources = () => ({todo: {id: props.id, lazy: true}});
616
620
 
617
621
  function TodoSearchItem(props) {
618
622
  const {todoModel} = useResources(getResources, props);
@@ -627,6 +631,10 @@ function TodoSearchItem(props) {
627
631
 
628
632
  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!
629
633
 
634
+ ### minDuration
635
+
636
+ Sometimes requests can be _too_ fast for certain UIs. In these cases, spinners and other loading states can appear more like a jarring flicker than a helpful status indicator. For these, you can pass a `minDuration` equal to the minimum number of milliseconds that a request should take. This is great for [save and destroy](#data-mutations) requests. It will work for fetch requests via `useResources`, as well, but beware: if multiple components use the same resource and there are different (or missing) values for `minDuration`, this will cause a race condition.
637
+
630
638
  ### dependsOn
631
639
 
632
640
  See the section on [serial requests](#serial-requests).
@@ -704,7 +712,7 @@ Each one of these methods exhibit the following behaviors:
704
712
  1. On error, they undo the changes that were done (and their registered components render again).
705
713
 
706
714
  **Note:**
707
- 1. All calls resolve an array, which is a tuple of [model, response]. All reject with just the response.
715
+ 1. All calls resolve an array, which is a tuple of `[model, response]`. All reject with just the response.
708
716
  1. All write calls must have a `.catch` attached, even if the rejection is swallowed. Omitting one risks an uncaught Promise rejection exception if the request fails.
709
717
 
710
718
  ## Serial Requests
@@ -712,42 +720,37 @@ Each one of these methods exhibit the following behaviors:
712
720
  In most situations, all resource requests should be parallelized; but that’s not always possible. Every so often, there may be a situation where one request depends on the result of another. For these cases, we have the `dependsOn` resource config option and the `provides` resource config option. These are probably best explained by example, so here is a simplified instance from the [Sift](https://sift.com) Console, where we load a queue item that has info about a user, but we can't get further user information until we know what user id belongs to this queue item.
713
721
 
714
722
  ```js
715
- @withResources(({QUEUE_ITEM, USER}, props) => ({
716
- [USER]: {
717
- options: {userId: props.userId},
718
- dependsOn: ['userId']
723
+ @withResources((props) => ({
724
+ user: {
725
+ path: {userId: props.userId},
726
+ dependsOn: !!props.userId
719
727
  },
720
- [QUEUE_ITEM]: {
721
- data: {id: props.itemId}
722
- provides: {userId: getUserIdFromItem}
728
+ queueItem: {
729
+ data: {id: props.itemId},
730
+ provides: (queueItemModel) => ({userId: queueItemModel.get('userId')})
723
731
  }
724
732
  }))
725
733
  export default class QueueItemPage extends React.Component {}
726
-
727
- function getUserIdFromItem(queueItemModel) {
728
- return queueItemModel.get('userId');
729
- }
730
- ```
731
734
 
732
- 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.
733
735
 
734
- 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!
736
+ 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 function that takes an instance of the returned model or collection and returns a map of `{[key: string]: any}`. Each key is a new prop name, and each value the new prop's value.
735
737
 
736
- One thing to note here is that while the `QUEUE_ITEM` resource is being fetched, the user resource is in a `PENDING` state, which is a special state that does not contribute to overall component `isLoading`/`hasErrored` states (though it will keep the component from being `hasLoaded`). At this point, the `QueueItemPage` in the example above is in a `LOADING` state (`isLoading === true`) because `QUEUE_ITEM` is loading. When it returns with the user id, the `USER` resource is put into a `LOADING` state, and the component then remains `isLoading === true` until it returns, after which the component has successfully loaded. If the `QUEUE_ITEM` resource happened to error, for some reason, the `USER` resource would never get out of its `PENDING` state, and the component would then take on the `ERROR` state (`hasErrored === true`) of `QUEUE_ITEM`. For more on `PENDING`, see [Thoughts on the PENDING State](/docs/advanced_topics.md#thoughts-on-the-pending-resource) in the [Advanced Topics document](/docs/advanced_topics.md).
738
+ So, in this case, the returned `queueItemModel` instance is passed as an argument, and we return a string that will be assigned to `props.userId` (or, more accurately, will be set as state via `setResourceState` as described in the previous section). At tthis point, `props.userId` exists, and the UserModel will be fetched. And we have serially requested our resources!
737
739
 
738
- Finally, if a model is to provide more than a single prop, use an underscore instead of the prop name in the `provides` object. Instead of the transform function returning the prop value, it should then return an object of prop keys and values, which will get spread to the component:
740
+ One thing to note here is that while the `queueItem` resource is being fetched, the user resource is in a `PENDING` state, which is a special state that does not contribute to overall component `isLoading`/`hasErrored` states (though it will keep the component from being `hasLoaded`). At this point, the `QueueItemPage` in the example above is in a `LOADING` state (`isLoading === true`) because `QUEUE_ITEM` is loading. When it returns with the user id, the `user` resource is put into a `LOADING` state, and the component then remains `isLoading === true` until it returns, after which the component has successfully loaded. If the `queueItem` resource happened to error for some reason, the `user` resource would never get out of its `PENDING` state, and the component would then take on the `ERROR` state (`hasErrored === true`) of `queueItem`. For more on `PENDING`, see [Thoughts on the PENDING State](/docs/advanced_topics.md#thoughts-on-the-pending-resource) in the [Advanced Topics document](/docs/advanced_topics.md).
741
+
742
+ Finally, note that the `provides` function can return any number of fields we want to set as new props for other resources:
739
743
 
740
744
  ```js
741
- const getResources = ({QUEUE_ITEM, USER}, props) => ({
742
- [USER]: {
745
+ const getResources = (props) => ({
746
+ user: {
743
747
  options: {state: props.activeState, userId: props.userId},
744
748
  // userModel depends on multiple props from queueItemModel
745
- dependsOn: ['activeState', 'userId']
749
+ dependsOn: !!props.userId && props.activeState === "active"
746
750
  },
747
- [QUEUE_ITEM]: {
748
- data: {id: props.itemId}
749
- // use an underscore here to tell resourcerer to spread the resulting object
750
- provides: {_: getUserDataFromItem}
751
+ queueItem: {
752
+ data: {id: props.itemId},
753
+ provides: (queueItemModel) => ({userId: queueItemModel.get('userId'), activeState: queueItemModel.get('state')})
751
754
  }
752
755
  });
753
756
 
@@ -760,11 +763,6 @@ export default function QueueItemPage(props) {
760
763
  queueItemModel
761
764
  } = useResources(getResources, props);
762
765
  }
763
-
764
- function getUserDataFromItem(queueItemModel) {
765
- // transform function now returns an object of prop names/values instead of a simple prop value
766
- return {userId: queueItemModel.get('userId'), activeState: queueItemModel.get('state')};
767
- }
768
766
  ```
769
767
 
770
768
  # Differences between useResources and withResources
@@ -777,7 +775,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
777
775
 
778
776
  ```js
779
777
  function MyComponent({start_time, ...props}) {
780
- const {todosCollection} = useResources(({TODOS}, _props) => ({[TODOS]: {params: {start_time}}}), props);
778
+ const {todosCollection} = useResources((_props) => ({todos: {params: {start_time}}}), props);
781
779
 
782
780
  // ...
783
781
  ```
@@ -786,7 +784,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
786
784
 
787
785
  ```js
788
786
  function MyComponent(props) {
789
- const {todosCollection} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
787
+ const {todosCollection} = useResources(({start_time}) => ({todos: {params: {start_time}}}), props);
790
788
 
791
789
  // ...
792
790
  ```
@@ -794,7 +792,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
794
792
  or, even clearer, define your executor function outside of the component scope, as we've done throughout this tutorial (now you know why!):
795
793
 
796
794
  ```js
797
- const getResources = ({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}});
795
+ const getResources = ({start_time}) => ({todos: {params: {start_time}}});
798
796
 
799
797
  function MyComponent(props) {
800
798
  const {todosCollection} = useResources(getResources, props);
@@ -814,25 +812,25 @@ Again, it’s unlikely that you’ll use `ModelCache` directly while using `reso
814
812
 
815
813
  As alluded to previously, `resourcerer` relies on the model classes themselves to tell it how it should be cached. This is accomplished via a static `dependencies` array, where each entry can be either:
816
814
 
817
- 1. A string, where each string is the name of a property that the model receives whose value should take part in the cache key. The model can receive this property either from the [options](#options) hash, the [data](#data) hash, or the [params](#params) hash, in that order.
815
+ 1. A string, where each string is the name of a property that the model receives whose value should take part in the cache key. The model can receive this property either from the [path](#path) hash, the [data](#data) hash, or the [params](#params) hash, in that order.
818
816
 
819
817
  2. A function, whose return value is an object of keys and values that should both contribute to the cache key.
820
818
 
821
- Let's take a look at the USER_TODOS resource from above, where we want to request some top number of todos for a user sorted by some value over some time range. The resource declaration might look like this:
819
+ Let's take a look at the `userTodos` resource from above, where we want to request some top number of todos for a user sorted by some value over some time range. The resource declaration might look like this:
822
820
 
823
821
  ```js
824
- const getResources = (ResourceKeys, props) => {
822
+ const getResources = (props) => {
825
823
  const now = Date.now();
826
824
 
827
825
  return {
828
- [ResourceKeys.USER_TODOS]: {
826
+ userTodos: {
829
827
  params: {
830
828
  limit: props.limit,
831
829
  end_time: now,
832
830
  start_time: now - props.timeRange,
833
831
  sort_field: props.sortField
834
832
  },
835
- options: {userId: props.userId}
833
+ path: {userId: props.userId}
836
834
  }
837
835
  };
838
836
  };
@@ -856,37 +854,37 @@ export class UserTodosCollection extends Collection {
856
854
  };
857
855
  ```
858
856
 
859
- We can see that `limit` and `sort_field` as specified in `dependencies` are taken straight from the `params` object that `resourcerer` transforms into url query parameters. `userId` is part of the `/users/{userId}/todos` path, so it can't be part of the `params` object, which is why it's stored as an instance property. But `resourcerer` will see its value within the `options` hash that is passed and use it for the cache key.
857
+ We can see that `limit` and `sort_field` as specified in `dependencies` are taken straight from the `params` object that `resourcerer` transforms into url query parameters. `userId` is part of the `/users/{userId}/todos` path, so it can't be part of the `params` object, which is why it gets passed in the `path` object instead.
860
858
 
861
859
  The time range is a little tougher to cache, though. We're less interested the spcecific `end_time`/`start_time` values to the millisecond&mdash;it does us little good to cache an endpoint tied to `Date.now()` when it will never be the same for the next request. We're much more interested in the difference between `end_time` and `start_time`. This is a great use-case for a function entry in `dependencies`, which takes the `params` object passed an argument. In the case above, the returned object will contribute a key called `range` and a value equal to the time range to the cache key.
862
860
 
863
- The generated cache key would be something like `userTodos_limit=50_$range=86400000_sort_field=importance_userId=noah`. Again, note that:
861
+ The generated cache key would be something like `userTodos~limit=50_$range=86400000_sort_field=importance_userId=noah`. Again, note that:
864
862
 
865
- - the `userId` value is taken from the `options` hash
863
+ - the `userId` value is taken from the `path` hash
866
864
  - the `limit` and `sort_field` values are taken from the `params` hash
867
865
  - the `range` value is taken from a function that takes `start_millis`/`end_millis` from the `params` hash into account.
868
866
 
869
867
 
870
868
  ## Prefetch on Hover
871
869
 
872
- You can use `resourcerer`'s executor function to optimistically prefetch resources when a user hovers over an element. For example, if a user hovers over a link to their TODOS page, you may want to get a head start on fetching their TODOS resource so that perceived loading time goes down or gets eliminated entirely. We can do this with the top-level `prefetch` function:
870
+ You can use `resourcerer`'s executor function to optimistically prefetch resources when a user hovers over an element. For example, if a user hovers over a link to their TODOS page, you may want to get a head start on fetching their `todos` resource so that perceived loading time goes down or gets eliminated entirely. We can do this with the top-level `prefetch` function:
873
871
 
874
872
  ```jsx
875
873
  import {prefetch} from 'resourcerer';
876
874
 
877
875
  // here's our executor function just as we pass to useResources or withResources
878
- const getTodos = (ResourceKeys, props) => {
876
+ const getTodos = (props) => {
879
877
  const now = Date.now();
880
878
 
881
879
  return {
882
- [ResourceKeys.USER_TODOS]: {
880
+ userTodos: {
883
881
  params: {
884
882
  limit: props.limit,
885
883
  end_time: now,
886
884
  start_time: now - props.timeRange,
887
885
  sort_field: props.sortField
888
886
  },
889
- options: {userId: props.userId}
887
+ path: {userId: props.userId}
890
888
  }
891
889
  };
892
890
  };
@@ -906,21 +904,36 @@ Note, as mentioned in the comment above, that `expectedProps` should take the fo
906
904
  1. A request timed out and you want to give the user the option of retrying.
907
905
  2. You have made a change to one resource that may render an auxiliary resource stale, and you want to bring the auxiliary resource up-to-date.
908
906
 
909
- It takes a function that is passed `ResourceKeys` and should return a list of `ResourceKeys`. Each entry will get refetched.
907
+ The function takes a single or a list of `ResourceKeys`. Each entry will get refetched.
910
908
 
911
909
  ```js
912
910
  function MyComponent(props) {
913
- const {todosCollection, refetch} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
911
+ const {todosCollection, refetch} = useResources(({start_time}) => ({todos: {params: {start_time}}}), props);
914
912
 
915
913
  // ...
916
914
 
917
- return <Button onClick={() => refetch(({TODOS}) => [TODOS])}>Refetch me</Button>;
915
+ return <Button onClick={() => refetch("todos")}>Refetch me</Button>;
918
916
  ```
919
917
 
920
918
  **NOTE:**
921
- * The list returned by the function should only include keys that are currently returned by the executor function. In the example above, returning `USER_TODOS` would not fetch anything because it is not part of the current executor function. To conditionally fetch another resource, add it to the executor function with [dependsOn](#serial-requests).
919
+ * The list returned by the function should only include keys that are currently returned by the executor function. In the example above, returning `userTodos` would not fetch anything because it is not part of the current executor function. To conditionally fetch another resource, add it to the executor function with [dependsOn](#serial-requests).
922
920
  * The resource that will be refetched is the version returned by the executor function with the current props. To fetch a different version, use the standard props flow instead of refetching.
923
921
 
922
+ ## Cache Invalidation
923
+
924
+ In some cases you may want to imperatively remove a resource from the cache. For example, you may make a change to a related resource that renders a resource invalid. For those cases, `useResources` returns an `invalidate` function that takes a single or a list of `ResourceKeys`:
925
+
926
+ ```js
927
+ function MyComponent(props) {
928
+ const {todosCollection, invalidate} = useResources(({start_time}) => ({todos: {params: {start_time}}}), props);
929
+
930
+ // ...
931
+
932
+ return <Button onClick={() => invalidate(["todos"])}>Invalidate me</Button>;
933
+ ```
934
+
935
+ * Unlike [`refetching`](#refetching), the ResourceKeys passed to `invalidate` do not need to be from those returned by the executor function. They can any resource key.
936
+
924
937
  ## Tracking Request Times
925
938
 
926
939
  If you have a metrics aggregator and want to track API request times, you can do this by setting a `measure` static property on your model or collection. `measure` can either be a boolean or a function that returns a boolean. The function takes the resource config object as a parameter:
@@ -941,7 +954,7 @@ When the static `measure` property is/returns true, `resourcerer` will record th
941
954
 
942
955
  # Configuring `resourcerer`
943
956
 
944
- The same config file used to add to `ResourceKeys` and `ModelMap` also allows you to set custom configuration properties for your own application:
957
+ The same config file used to `register` your models also allows you to set custom configuration properties for your own application:
945
958
 
946
959
  ```js
947
960
  import {ResourcesConfig} from 'resourcerer';
@@ -1000,7 +1013,6 @@ ResourcesConfig.set(configObj);
1000
1013
  });
1001
1014
  ```
1002
1015
 
1003
- * `queryParamsPropName` (string): the name of the prop representing url query parameters that `withResources` will look for and flatten for its children. If your application already flattens query parameters, you can ignore this property. Otherwise, when a url search string of, for example, `?end_time=1558100000000&start_time=1555508000000` is turned into an object prop of `{end_time: 1558100000000, start_time: 1555508000000}`, `withResources`-wrapped components will see `props.end_time` and `props.start_time`, and `useResources` will return `end_time` and `start_time` for ease of use in your executor function. **Default:** `'urlParams'`.
1004
1016
 
1005
1017
  * `track` (function): method invoked when [a `measure` property is added to a Model or Collection](#tracking-request-times). Use this hook to send the measured data to your application analytics tracker. **Default:** noop. The method is invoked with two arguments:
1006
1018
 
@@ -1061,12 +1073,12 @@ ResourcesConfig.set(configObj);
1061
1073
 
1062
1074
  // component1
1063
1075
  function MyComponent({category, ...props}) {
1064
- const {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {options: {category}}));
1076
+ const {todosCollection} = useResources(() => ({todos: {path: {category}}));
1065
1077
  }
1066
1078
 
1067
1079
  // component2--identical to the first
1068
1080
  function MyComponent({category, ...props}) {
1069
- const {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {options: {category}}));
1081
+ const {todosCollection} = useResources(() => ({todos: {path: {category}}));
1070
1082
  }
1071
1083
  ```
1072
1084
 
@@ -1083,48 +1095,6 @@ ResourcesConfig.set(configObj);
1083
1095
  1. passes instantiated models directly through the app before calling `renderToString`
1084
1096
  2. provides those models within a top-level `<script>` element that adds them directly to the [ModelCache](#caching-resources-with-modelcache).
1085
1097
 
1086
-
1087
- * Can the `withResources` HOC be used with both function components and class components?
1088
-
1089
- Yes! The docs don't show it, but this is totally valid:
1090
-
1091
- ```jsx
1092
- const UserTodos = (props) => (
1093
- <div className='MyClassWithTodosAndUsers'>
1094
- {props.isLoading ? <Loader /> : null}
1095
-
1096
- {props.hasLoaded ? (
1097
- <ul>
1098
- {props.userTodosCollection.map((todoModel) => (
1099
- <li key={todoModel.id}>
1100
- {todoModel.get('name')}
1101
- </li>
1102
- )}
1103
- </ul>
1104
- ) : null}
1105
-
1106
- {props.hasErrored ? <ErrorMessage /> : null}
1107
- </div>
1108
- );
1109
-
1110
- export withResources((ResourceKeys, props) => {
1111
- const now = Date.now();
1112
-
1113
- return {
1114
- [ResourceKeys.USER_TODOS]: {
1115
- params: {
1116
- limit: 20,
1117
- end_time: now,
1118
- start_time: now - props.timeRange,
1119
- sort_field: props.sortField
1120
- },
1121
- options: {userId: props.userId}
1122
- }
1123
- };
1124
- })(UserTodos)
1125
- ```
1126
-
1127
- There is one caveat, though&mdash;function components should not be wrapped in `React.memo` or they won't be updated when the resource updates.
1128
1098
 
1129
1099
  * Can `resourcerer` do anything other than `GET` requests?
1130
1100
 
@@ -1160,3 +1130,7 @@ ResourcesConfig.set(configObj);
1160
1130
  * Semver?
1161
1131
 
1162
1132
  Yes. Releases will adhere to [semver](https://semver.org/#semantic-versioning-200) rules.
1133
+
1134
+ # Migrating to v2.0
1135
+
1136
+ See the [Migrating to v2.0](/docs/migrating_to_2.0.md) doc.