resourcerer 1.0.0-beta-2 → 1.0.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
@@ -12,12 +12,13 @@
12
12
 
13
13
  Additional features include:
14
14
 
15
+ * fully declarative (no more writing any imperative Fetch API calls)
15
16
  * first-class loading and error state support
16
17
  * smart client-side caching
17
18
  * refetching
18
19
  * updating a component when a resource updates
19
20
  * zero dependencies
20
- * ...and more
21
+ * < 10kB!
21
22
 
22
23
  Getting started is easy:
23
24
 
@@ -55,13 +56,12 @@ import 'js/core/resourcerer-config';
55
56
  1. ### useResources
56
57
 
57
58
  ```jsx
58
- import React from 'react';
59
59
  import {useResources} from 'resourcerer';
60
60
 
61
61
  const getResources = ({TODOS}, props) => ({[TODOS]: {}});
62
62
 
63
63
  function MyComponent(props) {
64
- var {
64
+ const {
65
65
  isLoading,
66
66
  hasErrored,
67
67
  hasLoaded,
@@ -126,25 +126,27 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
126
126
  1. [Nomenclature](#nomenclature)
127
127
  1. [Tutorial](#tutorial)
128
128
  1. [Intro](#tutorial)
129
- 1. [Other Props Returned from the Hook/Passed from the HOC (Loading States)](other-props-returned-from-the-hookpassed-from-the-hoc-loading-states)
129
+ 1. [Other Props Returned from the Hook/Passed from the HOC (Loading States)](#other-props-returned-from-the-hookpassed-from-the-hoc-loading-states)
130
130
  1. [Requesting Prop-driven Data](#requesting-prop-driven-data)
131
131
  1. [Changing Props](#changing-props)
132
- 1. [Serial Requests](#serial-requests)
133
- 1. [Other Common Resource Config Options](#other-common-resource-config-options)
134
- 1. [data](#data)
132
+ 1. [Common Resource Config Options](#common-resource-config-options)
133
+ 1. [params](#params)
135
134
  1. [options](#options)
136
- 1. [attributes](#attributes)
137
135
  1. [noncritical](#noncritical)
138
- 1. [forceFetch](#forcefetch)
136
+ 1. [force](#force)
139
137
  1. [Custom Resource Names](#custom-resource-names)
140
138
  1. [prefetches](#prefetches)
139
+ 1. [data](#data)
140
+ 1. [dependsOn](#dependson)
141
+ 1. [provides](#provides)
141
142
  1. [Data mutations](#data-mutations)
142
- 1. [Differences between useResources and withResources](#differences-between-useresources-and-withresources)
143
- 1. [Caching Resources with ModelCache](#caching-resources-with-modelcache)
144
- 1. [Declarative Cache Keys](#declarative-cache-keys)
145
- 1. [Prefetch on Hover](#prefetch-on-hover)
146
- 1. [Refetching](#refetching)
147
- 1. [Tracking Request Times](#tracking-request-times)
143
+ 1. [Serial Requests](#serial-requests)
144
+ 3. [Differences between useResources and withResources](#differences-between-useresources-and-withresources)
145
+ 4. [Caching Resources with ModelCache](#caching-resources-with-modelcache)
146
+ 5. [Declarative Cache Keys](#declarative-cache-keys)
147
+ 6. [Prefetch on Hover](#prefetch-on-hover)
148
+ 7. [Refetching](#refetching)
149
+ 8. [Tracking Request Times](#tracking-request-times)
148
150
  1. [Configuring resourcerer](#configuring-resourcerer)
149
151
  1. [FAQs](#faqs)
150
152
 
@@ -153,7 +155,7 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
153
155
 
154
156
  `$ npm i resourcerer`
155
157
 
156
- `resourcerer` requires on React >= 16 but has no external dependencies.
158
+ `resourcerer` requires on React >= 16.8 but has no external dependencies.
157
159
 
158
160
  Note that Resourcerer uses ES2015 in its source and does no transpiling&mdash;including import/export (Local babel configuration is for testing, only).
159
161
  This means that if you're not babelifying your `node_modules` folder, you'll need to make an exception for this package, ie:
@@ -173,9 +175,9 @@ module: {
173
175
 
174
176
  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.
175
177
 
176
- 1. **ResourceKeys**. These are the keys added to the `ModelMap` 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.
178
+ 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.
177
179
 
178
- 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. It accepts `ResourceKeys` and `props` as arguments and may look like, as we'll explore in an example later:
180
+ 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:
179
181
 
180
182
  ```js
181
183
  const getResources = ({USER}, props) => ({[USER]: {options: {userId: props.id}}});
@@ -189,7 +191,7 @@ module: {
189
191
 
190
192
  return {
191
193
  [USER_TODOS]: {
192
- data: {
194
+ params: {
193
195
  limit: 20,
194
196
  end_time: now,
195
197
  start_time: now - props.timeRange,
@@ -200,7 +202,7 @@ module: {
200
202
  };
201
203
  ```
202
204
 
203
- 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).
205
+ 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).
204
206
 
205
207
  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.
206
208
 
@@ -209,12 +211,13 @@ module: {
209
211
  Okay, back to the initial example. Let's take a look at our `useResources` usage in the component:
210
212
 
211
213
  ```js
212
- // Note: in these docs, you will see a combination of `ResourceKeys` in the executor function as well as
213
- // its more common destructured version, ie `@withResources(({TODOS}, props) => ({[TODOS]: {}}))`
214
+ // Note: in these docs, you will see a combination of `ResourceKeys` in the executor
215
+ // function as well as its more common destructured version, ie:
216
+ // `@withResources(({TODOS}, props) => ({[TODOS]: {}}))`
214
217
  const getResources = (ResourceKeys, props) => ({[ResourceKeys.TODOS]: {}});
215
218
 
216
219
  export default function MyComponent(props) {
217
- var resources = useResources(getResources, props);
220
+ const resources = useResources(getResources, props);
218
221
 
219
222
  // ...
220
223
  }
@@ -238,15 +241,15 @@ ModelMap.add({TODOS: TodosCollection});
238
241
 
239
242
  (We can also pass custom prefixes for our prop names in a component, but [we'll get to that later](#custom-resource-names).)
240
243
 
241
- 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, and 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.
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.
242
245
 
243
246
 
244
247
  ## Other Props Returned from the Hook/Passed from the HOC (Loading States)
245
248
 
246
- Of course, in our initial example, the todos collection won’t get passed down 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:
249
+ 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:
247
250
 
248
251
 
249
- - `todosLoadingState` (can be equal to any of the [LoadingStates constants](https://github.com/noahgrant/resourcerer/blob/master/lib/constants.js), and there will be one for each resource)
252
+ - `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`)
250
253
  - `hasLoaded` {boolean} - all critical resources have successfully completed and are ready to be used by the component
251
254
  - `isLoading` {boolean} - any of the critical resources are still in the process of being fetched
252
255
  - `hasErrored` {boolean} - any of the critical resource requests did not complete successfully
@@ -254,13 +257,13 @@ Of course, in our initial example, the todos collection won’t get passed down
254
257
  `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:
255
258
 
256
259
  ```js
257
- const getResources = ({TODOS, USER}, props) => ({
260
+ const getResources = ({TODOS, USERS}, props) => ({
258
261
  [TODOS]: {},
259
262
  [USERS]: {noncritical: true}
260
263
  });
261
264
 
262
265
  function MyClassWithTodosAndAUsers(props) {
263
- var resources = useResources(getResources, props);
266
+ const resources = useResources(getResources, props);
264
267
  }
265
268
  ```
266
269
 
@@ -280,7 +283,7 @@ Here’s how might use that to our advantage in `MyClassWithTodosAndAUsers` :
280
283
  import {haveAllLoaded} from 'resourcerer';
281
284
 
282
285
  function MyClassWithTodosAndAUsers(props) {
283
- var {
286
+ const {
284
287
  isLoading,
285
288
  hasErrored,
286
289
  hasLoaded,
@@ -306,7 +309,8 @@ function MyClassWithTodosAndAUsers(props) {
306
309
 
307
310
  {hasLoaded ? (
308
311
  // at this point we are guaranteed all critical resources have returned.
309
- // before that, todosCollection is a Collection instance, just empty
312
+ // before that, todosCollection is still a Collection instance that can be
313
+ // mapped over--it's just empty
310
314
  <ul>
311
315
  {todosCollection.map((todoModel) => (
312
316
  <li key={todoModel.id}>
@@ -335,7 +339,7 @@ And here's what it looks like when the stats endpoint returns:
335
339
 
336
340
  ![Noncritical Resource Returned](https://user-images.githubusercontent.com/1355779/57596646-9a425900-7500-11e9-8121-5ced72c0fcba.png)
337
341
 
338
- There’s one other loading prop offered from the hook/HOC: `hasInitiallyLoaded`. This can be useful for showing a different UI for components that have already fetched the resource. An example might be a component with filters: as the initial resource is fetched, we may want to show a generic loader, but upon changing a filter (and re-fetching the resource), we may want to show a loader with an overlay over the previous version of the component. See the [Advanced Topics docs](/docs/advanced_topics.md#loading-overlays) for more.
342
+ There’s one other loading prop offered from the hook/HOC: `hasInitiallyLoaded`. This can be useful for showing a different UI for components that have already fetched the resource. An example might be a component with filters: when a filter is changed after the initial resource is loaded (thus re-fetching the resource), we may want to show a loader with an overlay over the previous version of the component. See the [Advanced Topics docs](/docs/advanced_topics.md#loading-overlays) for more.
339
343
 
340
344
 
341
345
  ## Requesting Prop-driven Data
@@ -361,32 +365,30 @@ And here's what our model might look like:
361
365
  import {Model} from 'resourcerer';
362
366
 
363
367
  export default class UserModel extends Model {
364
- constructor(attributes, options={}) {
365
- this.userId = options.userId;
366
- }
367
-
368
- url() {
369
- return `/users/${this.userId}`;
368
+ url({userId}) {
369
+ // `userId` is passed in here because we have
370
+ // `options: {userId: props.userId}` in the resource config object
371
+ return `/users/${userId}`;
370
372
  }
371
373
 
372
374
  static cacheFields = ['userId']
373
375
  }
374
376
  ```
375
377
 
376
- The `cacheFields` static property is important here, as we'll see in a second; it is a list of model 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:
378
+ The `cacheFields` 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:
377
379
 
378
- 1. the `options` object it is initialized with
379
- 1. the `attributes` object it is initialized with
380
- 1. the `data` it gets passed in a fetch
380
+ 1. the `options` object
381
+ 1. the `data` object
382
+ 1. the `params` object
381
383
 
382
- All three of these come from what's returned from our executor function; it might look like this:
384
+ All three of these come from via the [Resource Configuration Object](#nomenclature) that is returned from our executor function; it might look like this:
383
385
 
384
386
  ```jsx
385
387
  const getResources = ({USER}, props) => ({[USER]: {options: {userId: props.id}}})
386
388
 
387
389
  // hook
388
390
  function MyComponent(props) {
389
- var resources = useResources(getResources, props);
391
+ const resources = useResources(getResources, props);
390
392
 
391
393
  // ...
392
394
  }
@@ -412,71 +414,12 @@ In general, there are two ways to change `props.id` as in the previous example:
412
414
  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.
413
415
 
414
416
 
415
- ## Serial Requests
416
-
417
- 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 option and the `provides` resource 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.
418
-
419
- ```js
420
- @withResources(({QUEUE_ITEM, USER}, props) => ({
421
- [USER]: {
422
- options: {userId: props.userId},
423
- dependsOn: ['userId']
424
- },
425
- [QUEUE_ITEM]: {
426
- attributes: {id: props.itemId}
427
- provides: {userId: getUserIdFromItem}
428
- }
429
- }))
430
- export default class QueueItemPage extends React.Component {}
431
-
432
- function getUserIdFromItem(queueItemModel) {
433
- return queueItemModel.get('userId');
434
- }
435
- ```
436
-
437
- 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.
438
-
439
- 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 for the HOC wrapper’s state wrapper 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!
440
-
441
- 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).
442
-
443
- 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:
444
-
445
- ```js
446
- const getResources = ({QUEUE_ITEM, USER}, props) => ({
447
- [USER]: {
448
- options: {state: props.activeState, userId: props.userId},
449
- // userModel depends on multiple props from queueItemModel
450
- dependsOn: ['activeState', 'userId']
451
- },
452
- [QUEUE_ITEM]: {
453
- attributes: {id: props.itemId}
454
- // use an underscore here to tell resourcerer to spread the resulting object
455
- provides: {_: getUserDataFromItem}
456
- }
457
- });
458
-
459
- export default function QueueItemPage(props) {
460
- // activeState and userId are internal state within `useResources` and returned
461
- var {
462
- activeState,
463
- userId,
464
- userModel,
465
- queueItemModel
466
- } = useResources(getResources, props);
467
- }
468
-
469
- function getUserDataFromItem(queueItemModel) {
470
- // transform function now returns an object of prop names/values instead of a simple prop value
471
- return {userId: queueItemModel.get('userId'), activeState: queueItemModel.get('state')};
472
- }
473
- ```
474
417
 
475
- ## Other Common Resource Config Options
418
+ ## Common Resource Config Options
476
419
 
477
- ### data
420
+ ### params
478
421
 
479
- The `data` option is passed directly to the [sync](/docs/model.md#sync) module 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 `cacheFields` 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 `data` property:
422
+ 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 `cacheFields` 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:
480
423
 
481
424
  ```js
482
425
  @withResources((ResourceKeys, props) => {
@@ -484,7 +427,7 @@ The `data` option is passed directly to the [sync](/docs/model.md#sync) module a
484
427
 
485
428
  return {
486
429
  [ResourceKeys.USER_TODOS]: {
487
- data: {
430
+ params: {
488
431
  limit: 20,
489
432
  end_time: now,
490
433
  start_time: now - props.timeRange,
@@ -496,13 +439,14 @@ The `data` option is passed directly to the [sync](/docs/model.md#sync) module a
496
439
  class UserTodos extends React.Component {}
497
440
  ```
498
441
 
499
- Now, as the prop fields change, the data sent with the request changes as well (provided we set our `cacheFields` property accordingly):
442
+ Now, as the prop fields change, the params sent with the request changes as well (provided we set our `cacheFields` property accordingly):
500
443
 
501
444
  `https://example.com/users/noahgrant/todos?limit=20&end_time=1494611831024&start_time=1492019831024&sort_field=importance`
502
445
 
503
- ### options
504
446
 
505
- [As referenced previously](#requesting-prop-driven-data), an `options` hash on a resource config will be passed directly as the second parameter to a model's `constructor` method. It 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). Continuing with our User Todos example, let's add an `options` property:
447
+ ### options
448
+
449
+ [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 `cacheFields` property (See the [cache key section](#declarative-cache-keys) for more). Continuing with our User Todos example, let's add an `options` property:
506
450
 
507
451
  ```js
508
452
  const getResources = (ResourceKeys, props) => {
@@ -510,7 +454,7 @@ const getResources = (ResourceKeys, props) => {
510
454
 
511
455
  return {
512
456
  [ResourceKeys.USER_TODOS]: {
513
- data: {
457
+ params: {
514
458
  limit: 20,
515
459
  end_time: now,
516
460
  start_time: now - props.timeRange,
@@ -522,11 +466,19 @@ const getResources = (ResourceKeys, props) => {
522
466
  };
523
467
  ```
524
468
 
525
- Here, the UserTodos collection will be instantiated with an options hash including the `userId` property, which it uses to construct its url. We'll also want to add the `'userId'` string to the collection's [static `cacheFields` array](#requesting-prop-driven-data), because each cached collection should be specific to the user.
526
-
527
- ### attributes
469
+ 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 `cacheFields` array](#requesting-prop-driven-data), because each cached collection should be specific to the user:
528
470
 
529
- Pass in an attributes hash to initialize a Model instance with a body before initially fetching. This is passed directly to the [model](/docs/model.md#constructor) or [collection's](/docs/collection.md#constructor) `constructor` method along with the [`options`](#options) property, and is typically less useful than providing the properties directly to the [`data`](#data) property. Like `data` and `options`, the `attributes` 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).
471
+ ```js
472
+ // js/models/user_todos_collection.js
473
+ export class UserTodosCollection extends Collection {
474
+ url({userId}) {
475
+ // userId gets passed in for us to help construct our url
476
+ return `/users/${userId}/todos`;
477
+ }
478
+
479
+ static cacheFields = ['userId']
480
+ };
481
+ ```
530
482
 
531
483
 
532
484
  ### noncritical
@@ -539,12 +491,12 @@ As alluded to in the [Other Props](#other-props-returned-from-the-hookpassed-fro
539
491
 
540
492
 
541
493
 
542
- ### forceFetch
494
+ ### force
543
495
 
544
- Sometimes you want the latest of a resource, bypassing whatever model has already been cached in your application. To accomplish this, simply pass a `forceFetch: true` in a resource's config. The force-fetched response will replace any prior model in the cache, but may itself get replaced by a subsequent `forceFetch: true` request for the resource.
496
+ 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, but may itself get replaced by a subsequent `force: true` request for the resource.
545
497
 
546
498
  ```js
547
- @withResources((ResourceKeys, props) => ({[ResourceKeys.LATEST_STATS]: {forceFetch: true}}))
499
+ @withResources((ResourceKeys, props) => ({[ResourceKeys.LATEST_STATS]: {force: true}}))
548
500
  class MyComponentWithLatestStats extends React.Component {}
549
501
  ```
550
502
 
@@ -556,7 +508,7 @@ Passing a `modelKey: <ResourceKeys>` option allows you to pass a custom name as
556
508
  const getResources = (ResourceKeys, props) => ({myRadTodos: {modelKey: ResourceKeys.TODOS});
557
509
 
558
510
  export default function MyComponentWithTodos {
559
- var {
511
+ const {
560
512
  myRadTodosCollection,
561
513
  myRadTodosLoadingState,
562
514
  myRadTodosStatus,
@@ -580,7 +532,7 @@ const getResources = (ResourceKeys, props) => {
580
532
 
581
533
  return {
582
534
  [ResourceKeys.USER_TODOS]: {
583
- data: {
535
+ params: {
584
536
  from: props.page * REQUESTS_PER_PAGE,
585
537
  limit: REQUESTS_PER_PAGE,
586
538
  end_time: now,
@@ -605,6 +557,33 @@ When the user clicks on a 'next' arrow that updates page state, the collection w
605
557
 
606
558
  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.
607
559
 
560
+ ### data
561
+
562
+ 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:
563
+
564
+ ```js
565
+ getResources = ({CUSTOMER}) => ({[CUSTOMER]: {data: {id: props.customerId}}});
566
+
567
+ function MyCustomerComponent(props) {
568
+ const {customerModel} = useResources(getResources, props);
569
+
570
+ // now you can reference the id directly on the model
571
+ console.log(customerModel.get('id')); // or the id shorthand, customerModel.id
572
+ }
573
+ ```
574
+
575
+ You can also use `data` to take advantage of [re-caching](/docs/advanced_topics.md#recaching-newly-saved-models).
576
+
577
+ 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
+
579
+ ### dependsOn
580
+
581
+ See the section on [serial requests](#serial-requests).
582
+
583
+ ### provides
584
+
585
+ See the section on [serial requests](#serial-requests).
586
+
608
587
  # Data Mutations
609
588
 
610
589
  So far we've only discussed fetching data. But `resourcerer` also makes it very easy to make write requests via the [Model](/docs/model.md) and [Collection](/docs/collection.md) instances that are returned. These classes are enriched data structures that hold our API server data as well as several utilities that help manage the server data in our application. There are three main write operations via these classes:
@@ -615,10 +594,10 @@ So far we've only discussed fetching data. But `resourcerer` also makes it very
615
594
 
616
595
  ```js
617
596
  function MyComponent(props) {
618
- var {myModel} = useResources(getResources, props),
619
- onSave = () => myModel.save({foo: 'bar'})
620
- .then([model]) => // ...)
621
- .catch(() => alert('request failed'));
597
+ const {myModel} = useResources(getResources, props),
598
+ onSave = () => myModel.save({foo: 'bar'})
599
+ .then([model]) => // ...)
600
+ .catch(() => alert('request failed'));
622
601
 
623
602
  return <button onClick={onSave}>Persist model</button>;
624
603
  }
@@ -638,8 +617,8 @@ So far we've only discussed fetching data. But `resourcerer` also makes it very
638
617
 
639
618
  ```js
640
619
  function TodoDetails(props) {
641
- var {hasLoaded, todosCollection} = useResources(getResources, props),
642
- todoModel = todosCollection.get(props.id),
620
+ const {hasLoaded, todosCollection} = useResources(getResources, props),
621
+ todoModel = todosCollection.get(props.id),
643
622
 
644
623
  onSaveTodo = {
645
624
  // set some loading state...
@@ -676,7 +655,66 @@ Each one of these methods exhibit the following behaviors:
676
655
  **Note:**
677
656
  1. All calls resolve an array, which is a tuple of [model, response]. All reject with just the response.
678
657
  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.
658
+
659
+ ## Serial Requests
660
+
661
+ 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.
662
+
663
+ ```js
664
+ @withResources(({QUEUE_ITEM, USER}, props) => ({
665
+ [USER]: {
666
+ options: {userId: props.userId},
667
+ dependsOn: ['userId']
668
+ },
669
+ [QUEUE_ITEM]: {
670
+ data: {id: props.itemId}
671
+ provides: {userId: getUserIdFromItem}
672
+ }
673
+ }))
674
+ export default class QueueItemPage extends React.Component {}
675
+
676
+ function getUserIdFromItem(queueItemModel) {
677
+ return queueItemModel.get('userId');
678
+ }
679
+ ```
680
+
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.
682
+
683
+ 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!
679
684
 
685
+ 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).
686
+
687
+ 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:
688
+
689
+ ```js
690
+ const getResources = ({QUEUE_ITEM, USER}, props) => ({
691
+ [USER]: {
692
+ options: {state: props.activeState, userId: props.userId},
693
+ // userModel depends on multiple props from queueItemModel
694
+ dependsOn: ['activeState', 'userId']
695
+ },
696
+ [QUEUE_ITEM]: {
697
+ data: {id: props.itemId}
698
+ // use an underscore here to tell resourcerer to spread the resulting object
699
+ provides: {_: getUserDataFromItem}
700
+ }
701
+ });
702
+
703
+ export default function QueueItemPage(props) {
704
+ // activeState and userId are internal state within `useResources` and returned
705
+ const {
706
+ activeState,
707
+ userId,
708
+ userModel,
709
+ queueItemModel
710
+ } = useResources(getResources, props);
711
+ }
712
+
713
+ function getUserDataFromItem(queueItemModel) {
714
+ // transform function now returns an object of prop names/values instead of a simple prop value
715
+ return {userId: queueItemModel.get('userId'), activeState: queueItemModel.get('state')};
716
+ }
717
+ ```
680
718
 
681
719
  # Differences between useResources and withResources
682
720
 
@@ -684,11 +722,11 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
684
722
 
685
723
  1. The `withResources` HOC conveniently contains an [ErrorBoundary](https://reactjs.org/docs/error-boundaries.html) with every instance, but such functionality [does not yet exist in hooks](https://reactjs.org/docs/hooks-faq.html#do-hooks-cover-all-use-cases-for-classes). This is a definite advantage for the HOC right now, since, if we're already setting `hasErrored` clauses in our components to prepare for request errors, we can naturally gracefully degrade when an unexpected exception occurs. You'll need to manage this yourself with hooks until the equivalent functionality is released.
686
724
 
687
- 1. With the executor function now inlined in your component, be extra careful to avoid this anti-pattern:
725
+ 1. The executor function for a hook can be inlined in your component, which puts component props in its closure scope. So be extra careful to avoid this anti-pattern:
688
726
 
689
727
  ```js
690
728
  function MyComponent({start_time, ...props}) {
691
- var {todosCollection} = useResources(({TODOS}, _props) => ({[TODOS]: {data: {start_time}}}), props);
729
+ const {todosCollection} = useResources(({TODOS}, _props) => ({[TODOS]: {params: {start_time}}}), props);
692
730
 
693
731
  // ...
694
732
  ```
@@ -697,18 +735,18 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
697
735
 
698
736
  ```js
699
737
  function MyComponent(props) {
700
- var {todosCollection} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {data: {start_time}}}), props);
738
+ const {todosCollection} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
701
739
 
702
740
  // ...
703
741
  ```
704
742
 
705
- or define your executor function outside of the component scope, as we've done throughout this tutorial (now you know why!):
743
+ or, even clearer, define your executor function outside of the component scope, as we've done throughout this tutorial (now you know why!):
706
744
 
707
745
  ```js
708
- const getResources = ({TODOS}, {start_time}) => ({[TODOS]: {data: {start_time}}});
746
+ const getResources = ({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}});
709
747
 
710
748
  function MyComponent(props) {
711
- var {todosCollection} = useResources(getResources, props);
749
+ const {todosCollection} = useResources(getResources, props);
712
750
 
713
751
  // ...
714
752
  ```
@@ -725,7 +763,7 @@ Again, it’s unlikely that you’ll use `ModelCache` directly while using `reso
725
763
 
726
764
  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 `cacheFields` array, where each entry can be either:
727
765
 
728
- 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 [attributes](#attributes) hash, or the [data](#data) hash, in that order.
766
+ 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.
729
767
 
730
768
  2. A function, whose return value is an object of keys and values that should both contribute to the cache key.
731
769
 
@@ -737,7 +775,7 @@ const getResources = (ResourceKeys, props) => {
737
775
 
738
776
  return {
739
777
  [ResourceKeys.USER_TODOS]: {
740
- data: {
778
+ params: {
741
779
  limit: props.limit,
742
780
  end_time: now,
743
781
  start_time: now - props.timeRange,
@@ -753,12 +791,8 @@ And our corresponding model definition might look like this:
753
791
 
754
792
  ```js
755
793
  export class UserTodosCollection extends Collection {
756
- constructor(models, options={}) {
757
- this.userId = options.userId;
758
- }
759
-
760
- url() {
761
- return `/users/${this.userId}/todos`;
794
+ url({userId}) {
795
+ return `/users/${userId}/todos`;
762
796
  }
763
797
  // ...
764
798
 
@@ -771,15 +805,15 @@ export class UserTodosCollection extends Collection {
771
805
  };
772
806
  ```
773
807
 
774
- We can see that `limit` and `sort_field` as specified in `cacheFields` are taken straight from the `data` 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 `data` 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.
808
+ We can see that `limit` and `sort_field` as specified in `cacheFields` 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.
775
809
 
776
- 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 `cacheFields`, which takes the `data` 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.
810
+ 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 `cacheFields`, 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.
777
811
 
778
812
  The generated cache key would be something like `userTodos_limit=50_$range=86400000_sort_field=importance_userId=noah`. Again, note that:
779
813
 
780
814
  - the `userId` value is taken from the `options` hash
781
- - the `limit` and `sort_field` values are taken from the `data` hash
782
- - the `range` value is taken from a function that takes `start_millis`/`end_millis` from the `data` hash into account.
815
+ - the `limit` and `sort_field` values are taken from the `params` hash
816
+ - the `range` value is taken from a function that takes `start_millis`/`end_millis` from the `params` hash into account.
783
817
 
784
818
 
785
819
  ## Prefetch on Hover
@@ -790,12 +824,12 @@ You can use `resourcerer`'s executor function to optimistically prefetch resourc
790
824
  import {prefetch} from 'resourcerer';
791
825
 
792
826
  // here's our executor function just as we pass to useResources or withResources
793
- const getTodos = (props, ResourceKeys) => {
827
+ const getTodos = (ResourceKeys, props) => {
794
828
  const now = Date.now();
795
829
 
796
830
  return {
797
831
  [ResourceKeys.USER_TODOS]: {
798
- data: {
832
+ params: {
799
833
  limit: props.limit,
800
834
  end_time: now,
801
835
  start_time: now - props.timeRange,
@@ -825,7 +859,7 @@ It takes a function that is passed `ResourceKeys` and should return a list of `R
825
859
 
826
860
  ```js
827
861
  function MyComponent(props) {
828
- var {todosCollection, refetch} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {data: {start_time}}}), props);
862
+ const {todosCollection, refetch} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
829
863
 
830
864
  // ...
831
865
 
@@ -848,7 +882,7 @@ class MyMeasuredModel extends Model {
848
882
  static measure = true
849
883
 
850
884
  // or a function that returns a boolean, which will track instance requests based on a condition
851
- static measure = ({attributes={}}) => attributes.id === 'noahgrant'
885
+ static measure = ({data={}}) => data.id === 'noahgrant'
852
886
  }
853
887
  ```
854
888
 
@@ -907,22 +941,22 @@ ResourcesConfig.set(configObj);
907
941
  import {stringify} from 'qs';
908
942
 
909
943
  ResourcesConfig.set({
910
- stringify(data, options) {
911
- // data is the data object to be stringified into query parameters
944
+ stringify(params, options) {
945
+ // params is the params object to be stringified into query parameters
912
946
  // options is the request options object
913
- return stringify(data);
947
+ return stringify(params);
914
948
  }
915
949
  });
916
950
  ```
917
951
 
918
952
  * `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'`.
919
953
 
920
- * `track` (function): method invoked when [`measure: true`](#measure) is passed in a resource's config. Use this hook to send the measured data to your application analytics tracker. **Default:** noop. The method is invoked with two arguments:
954
+ * `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:
921
955
 
922
956
  * the event string, `'API Fetch'`
923
957
  * event data object with the following properties:
924
958
  * Resource (string): the name of the resource (taken from the entry in `ResourceKeys`)
925
- * data (object): data object supplied via the resource's config
959
+ * params (object): params object supplied via the resource's config
926
960
  * options (object): options object supplied via the resource's config
927
961
  * duration (number): time in milliseconds between request and response
928
962
 
@@ -976,12 +1010,12 @@ ResourcesConfig.set(configObj);
976
1010
 
977
1011
  // component1
978
1012
  function MyComponent({category, ...props}) {
979
- var {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {options: {category}}));
1013
+ const {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {options: {category}}));
980
1014
  }
981
1015
 
982
1016
  // component2--identical to the first
983
1017
  function MyComponent({category, ...props}) {
984
- var {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {options: {category}}));
1018
+ const {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {options: {category}}));
985
1019
  }
986
1020
  ```
987
1021
 
@@ -1027,7 +1061,7 @@ ResourcesConfig.set(configObj);
1027
1061
 
1028
1062
  return {
1029
1063
  [ResourceKeys.USER_TODOS]: {
1030
- data: {
1064
+ params: {
1031
1065
  limit: 20,
1032
1066
  end_time: now,
1033
1067
  start_time: now - props.timeRange,
@@ -1043,7 +1077,7 @@ ResourcesConfig.set(configObj);
1043
1077
 
1044
1078
  * Can `resourcerer` do anything other than `GET` requests?
1045
1079
 
1046
- `resourcerer` only handles resource _fetching_ (i.e. calling [Model.prototype.fetch](/docs/model.md#fetch)). Note that this is not the same as only making `GET` requests; pass in a `method: 'POST'` property in a resource's config to turn the `data` property into a POST body, for example, when making a search request.
1080
+ `resourcerer` only handles resource _fetching_ (i.e. calling [Model.prototype.fetch](/docs/model.md#fetch)). Note that this is not the same as only making `GET` requests; pass in a `method: 'POST'` property in a resource's config to turn the `params` property into a POST body, for example, when making a search request.
1047
1081
 
1048
1082
  For write operations, use Models' [`save`](/docs/model.md#save) and [`destroy`](/docs/model.md#destroy) methods directly:
1049
1083