resourcerer 1.0.0-alpha-3 → 1.0.0-beta-4

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
@@ -1,6 +1,6 @@
1
1
  <img src="https://user-images.githubusercontent.com/1355779/61337603-f9fffd80-a7ea-11e9-9cb3-fa82e044c86e.png" alt="Resourcerer Icon" height="200" width="200" />
2
2
 
3
- # resourcerer
3
+ # resourcerer (now in 1.0-beta!)
4
4
 
5
5
  `resourcerer` is a library for declaratively fetching and caching your application's data. Its powerful [`useResources`](#useresources) React hook or [`withResources`](#withresources) higher-order React component (HOC) allows you to easily construct a component's data flow, including:
6
6
 
@@ -17,6 +17,7 @@ Additional features include:
17
17
  * refetching
18
18
  * updating a component when a resource updates
19
19
  * zero dependencies
20
+ * < 10kB!
20
21
  * ...and more
21
22
 
22
23
  Getting started is easy:
@@ -94,7 +95,7 @@ import 'js/core/resourcerer-config';
94
95
  import React from 'react';
95
96
  import {withResources} from 'resourcerer';
96
97
 
97
- @withResources((props, {TODOS}) => ({[TODOS]: {}}))
98
+ @withResources(({TODOS}, props) => ({[TODOS]: {}}))
98
99
  class MyComponent extends React.Component {
99
100
  render() {
100
101
  // when MyComponent is mounted, the todosCollection is fetched and available
@@ -129,23 +130,24 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
129
130
  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
131
  1. [Requesting Prop-driven Data](#requesting-prop-driven-data)
131
132
  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)
133
+ 1. [Common Resource Config Options](#common-resource-config-options)
134
+ 1. [params](#params)
135
135
  1. [options](#options)
136
- 1. [attributes](#attributes)
137
136
  1. [noncritical](#noncritical)
138
137
  1. [forceFetch](#forcefetch)
139
138
  1. [Custom Resource Names](#custom-resource-names)
140
139
  1. [prefetches](#prefetches)
141
- 1. [status](#status)
140
+ 1. [data](#data)
141
+ 1. [dependsOn](#dependson)
142
+ 1. [provides](#provides)
142
143
  1. [Data mutations](#data-mutations)
143
- 1. [Differences between useResources and withResources](#differences-between-useresources-and-withresources)
144
- 1. [Caching Resources with ModelCache](#caching-resources-with-modelcache)
145
- 1. [Declarative Cache Keys](#declarative-cache-keys)
146
- 1. [Prefetch on Hover](#prefetch-on-hover)
147
- 1. [Refetching](#refetching)
148
- 1. [Tracking Request Times](#tracking-request-times)
144
+ 1. [Serial Requests](#serial-requests)
145
+ 3. [Differences between useResources and withResources](#differences-between-useresources-and-withresources)
146
+ 4. [Caching Resources with ModelCache](#caching-resources-with-modelcache)
147
+ 5. [Declarative Cache Keys](#declarative-cache-keys)
148
+ 6. [Prefetch on Hover](#prefetch-on-hover)
149
+ 7. [Refetching](#refetching)
150
+ 8. [Tracking Request Times](#tracking-request-times)
149
151
  1. [Configuring resourcerer](#configuring-resourcerer)
150
152
  1. [FAQs](#faqs)
151
153
 
@@ -154,7 +156,7 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
154
156
 
155
157
  `$ npm i resourcerer`
156
158
 
157
- `resourcerer` requires on React >= 16 but has no external dependencies.
159
+ `resourcerer` requires on React >= 16.8 but has no external dependencies.
158
160
 
159
161
  Note that Resourcerer uses ES2015 in its source and does no transpiling&mdash;including import/export (Local babel configuration is for testing, only).
160
162
  This means that if you're not babelifying your `node_modules` folder, you'll need to make an exception for this package, ie:
@@ -170,21 +172,11 @@ module: {
170
172
  }
171
173
  ```
172
174
 
173
- Also note that it also uses [legacy, Stage-1 decorators](https://github.com/tc39/proposal-decorators/blob/master/previous/METAPROGRAMMING.md), so you'll need to use the [babel decorators plugin](https://babeljs.io/docs/en/babel-plugin-proposal-decorators) with the `{legacy: true}` option:
174
-
175
- ```
176
- // .babelrc
177
- "plugins": [
178
- ["@babel/proposal-decorators", {"legacy": true}],
179
- // ...
180
- ]
181
- ```
182
-
183
175
  # Nomenclature
184
176
 
185
177
  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.
186
178
 
187
- 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.
179
+ 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.
188
180
 
189
181
  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:
190
182
 
@@ -200,7 +192,7 @@ Also note that it also uses [legacy, Stage-1 decorators](https://github.com/tc39
200
192
 
201
193
  return {
202
194
  [USER_TODOS]: {
203
- data: {
195
+ params: {
204
196
  limit: 20,
205
197
  end_time: now,
206
198
  start_time: now - props.timeRange,
@@ -220,8 +212,9 @@ Also note that it also uses [legacy, Stage-1 decorators](https://github.com/tc39
220
212
  Okay, back to the initial example. Let's take a look at our `useResources` usage in the component:
221
213
 
222
214
  ```js
223
- // Note: in these docs, you will see a combination of `ResourceKeys` in the executor function as well as
224
- // its more common destructured version, ie `@withResources(({TODOS}, props) => ({[TODOS]: {}}))`
215
+ // Note: in these docs, you will see a combination of `ResourceKeys` in the executor
216
+ // function as well as its more common destructured version, ie:
217
+ // `@withResources(({TODOS}, props) => ({[TODOS]: {}}))`
225
218
  const getResources = (ResourceKeys, props) => ({[ResourceKeys.TODOS]: {}});
226
219
 
227
220
  export default function MyComponent(props) {
@@ -249,15 +242,15 @@ ModelMap.add({TODOS: TodosCollection});
249
242
 
250
243
  (We can also pass custom prefixes for our prop names in a component, but [we'll get to that later](#custom-resource-names).)
251
244
 
252
- 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.
245
+ 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.
253
246
 
254
247
 
255
248
  ## Other Props Returned from the Hook/Passed from the HOC (Loading States)
256
249
 
257
- 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:
250
+ 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:
258
251
 
259
252
 
260
- - `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)
253
+ - `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`)
261
254
  - `hasLoaded` {boolean} - all critical resources have successfully completed and are ready to be used by the component
262
255
  - `isLoading` {boolean} - any of the critical resources are still in the process of being fetched
263
256
  - `hasErrored` {boolean} - any of the critical resource requests did not complete successfully
@@ -265,7 +258,7 @@ Of course, in our initial example, the todos collection won’t get passed down
265
258
  `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:
266
259
 
267
260
  ```js
268
- const getResources = ({TODOS, USER}, props) => ({
261
+ const getResources = ({TODOS, USERS}, props) => ({
269
262
  [TODOS]: {},
270
263
  [USERS]: {noncritical: true}
271
264
  });
@@ -317,7 +310,8 @@ function MyClassWithTodosAndAUsers(props) {
317
310
 
318
311
  {hasLoaded ? (
319
312
  // at this point we are guaranteed all critical resources have returned.
320
- // before that, todosCollection is a Collection instance, just empty
313
+ // before that, todosCollection is still a Collection instance that can be
314
+ // mapped over--it's just empty
321
315
  <ul>
322
316
  {todosCollection.map((todoModel) => (
323
317
  <li key={todoModel.id}>
@@ -346,7 +340,7 @@ And here's what it looks like when the stats endpoint returns:
346
340
 
347
341
  ![Noncritical Resource Returned](https://user-images.githubusercontent.com/1355779/57596646-9a425900-7500-11e9-8121-5ced72c0fcba.png)
348
342
 
349
- 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.
343
+ 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.
350
344
 
351
345
 
352
346
  ## Requesting Prop-driven Data
@@ -372,25 +366,23 @@ And here's what our model might look like:
372
366
  import {Model} from 'resourcerer';
373
367
 
374
368
  export default class UserModel extends Model {
375
- constructor(attributes, options={}) {
376
- this.userId = options.userId;
377
- }
378
-
379
- url() {
380
- return `/users/${this.userId}`;
369
+ url({userId}) {
370
+ // `userId` is passed in here because we have
371
+ // `options: {userId: props.userId}` in the resource config object
372
+ return `/users/${userId}`;
381
373
  }
382
374
 
383
375
  static cacheFields = ['userId']
384
376
  }
385
377
  ```
386
378
 
387
- 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:
379
+ 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:
388
380
 
389
- 1. the `options` object it is initialized with
390
- 1. the `attributes` object it is initialized with
391
- 1. the `data` it gets passed in a fetch
381
+ 1. the `options` object
382
+ 1. the `data` object
383
+ 1. the `params` object
392
384
 
393
- All three of these come from what's returned from our executor function; it might look like this:
385
+ All three of these come from via the [Resource Configuration Object](#nomenclature) that is returned from our executor function; it might look like this:
394
386
 
395
387
  ```jsx
396
388
  const getResources = ({USER}, props) => ({[USER]: {options: {userId: props.id}}})
@@ -418,84 +410,25 @@ In general, there are two ways to change `props.id` as in the previous example:
418
410
 
419
411
  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.
420
412
 
421
- 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 `setState` we all know and love. It sets internal hook/HOC state, which is then returned/passed down, respectively, overriding any initial prop, ie `setResourceState({id: 'fredsadaghiani'})`. This is _not_ indexable.
413
+ 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.
422
414
 
423
- Note that `setResourceState` has some subtle discrepancies between the hook and the HOC; see [Differences between useResources and withResources](#differences-between-useresources-and-withresources) for more.
415
+ 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.
424
416
 
425
417
 
426
- ## Serial Requests
427
418
 
428
- 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.
419
+ ## Common Resource Config Options
429
420
 
430
- ```js
431
- @withResources((props, {QUEUE_ITEM, USER}) => ({
432
- [USER]: {
433
- options: {userId: props.userId},
434
- dependsOn: ['userId']
435
- },
436
- [QUEUE_ITEM]: {
437
- attributes: {id: props.itemId}
438
- provides: {userId: getUserIdFromItem}
439
- }
440
- }))
441
- export default class QueueItemPage extends React.Component {}
442
-
443
- function getUserIdFromItem(queueItemModel) {
444
- return queueItemModel.get('userId');
445
- }
446
- ```
421
+ ### params
447
422
 
448
- 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.
449
-
450
- 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!
451
-
452
- 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).
453
-
454
- 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:
423
+ 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:
455
424
 
456
425
  ```js
457
- const getResources = ({QUEUE_ITEM, USER}, props) => ({
458
- [USER]: {
459
- options: {state: props.activeState, userId: props.userId},
460
- // userModel depends on multiple props from queueItemModel
461
- dependsOn: ['activeState', 'userId']
462
- },
463
- [QUEUE_ITEM]: {
464
- attributes: {id: props.itemId}
465
- // use an underscore here to tell resourcerer to spread the resulting object
466
- provides: {_: getUserDataFromItem}
467
- }
468
- });
469
-
470
- export default function QueueItemPage(props) {
471
- // activeState and userId are internal state within `useResources` and returned
472
- var {
473
- activeState,
474
- userId,
475
- userModel,
476
- queueItemModel
477
- } = useResources(getResources, props);
478
- }
479
-
480
- function getUserDataFromItem(queueItemModel) {
481
- // transform function now returns an object of prop names/values instead of a simple prop value
482
- return {userId: queueItemModel.get('userId'), activeState: queueItemModel.get('state')};
483
- }
484
- ```
485
-
486
- ## Other Common Resource Config Options
487
-
488
- ### data
489
-
490
- 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:
491
-
492
- ```js
493
- @withResources((props, ResourceKeys) => {
426
+ @withResources((ResourceKeys, props) => {
494
427
  const now = Date.now();
495
428
 
496
429
  return {
497
430
  [ResourceKeys.USER_TODOS]: {
498
- data: {
431
+ params: {
499
432
  limit: 20,
500
433
  end_time: now,
501
434
  start_time: now - props.timeRange,
@@ -507,13 +440,14 @@ The `data` option is passed directly to the [sync](/docs/model.md#sync) module a
507
440
  class UserTodos extends React.Component {}
508
441
  ```
509
442
 
510
- Now, as the prop fields change, the data sent with the request changes as well (provided we set our `cacheFields` property accordingly):
443
+ Now, as the prop fields change, the params sent with the request changes as well (provided we set our `cacheFields` property accordingly):
511
444
 
512
445
  `https://example.com/users/noahgrant/todos?limit=20&end_time=1494611831024&start_time=1492019831024&sort_field=importance`
513
446
 
514
- ### options
515
447
 
516
- [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:
448
+ ### options
449
+
450
+ [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:
517
451
 
518
452
  ```js
519
453
  const getResources = (ResourceKeys, props) => {
@@ -521,7 +455,7 @@ const getResources = (ResourceKeys, props) => {
521
455
 
522
456
  return {
523
457
  [ResourceKeys.USER_TODOS]: {
524
- data: {
458
+ params: {
525
459
  limit: 20,
526
460
  end_time: now,
527
461
  start_time: now - props.timeRange,
@@ -533,11 +467,19 @@ const getResources = (ResourceKeys, props) => {
533
467
  };
534
468
  ```
535
469
 
536
- 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.
537
-
538
- ### attributes
470
+ 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:
539
471
 
540
- 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).
472
+ ```js
473
+ // js/models/user_todos_collection.js
474
+ export class UserTodosCollection extends Collection {
475
+ url({userId}) {
476
+ // userId gets passed in for us to help construct our url
477
+ return `/users/${userId}/todos`;
478
+ }
479
+
480
+ static cacheFields = ['userId']
481
+ };
482
+ ```
541
483
 
542
484
 
543
485
  ### noncritical
@@ -555,7 +497,7 @@ As alluded to in the [Other Props](#other-props-returned-from-the-hookpassed-fro
555
497
  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.
556
498
 
557
499
  ```js
558
- @withResources((props, ResourceKeys) => ({[ResourceKeys.LATEST_STATS]: {forceFetch: true}}))
500
+ @withResources((ResourceKeys, props) => ({[ResourceKeys.LATEST_STATS]: {forceFetch: true}}))
559
501
  class MyComponentWithLatestStats extends React.Component {}
560
502
  ```
561
503
 
@@ -591,7 +533,7 @@ const getResources = (ResourceKeys, props) => {
591
533
 
592
534
  return {
593
535
  [ResourceKeys.USER_TODOS]: {
594
- data: {
536
+ params: {
595
537
  from: props.page * REQUESTS_PER_PAGE,
596
538
  limit: REQUESTS_PER_PAGE,
597
539
  end_time: now,
@@ -616,20 +558,32 @@ When the user clicks on a 'next' arrow that updates page state, the collection w
616
558
 
617
559
  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.
618
560
 
619
- ### status
620
- ##### *(`withResources` only)*
561
+ ### data
621
562
 
622
- Passing a `status: true` config option will pass props down to the component reflecting the resource’s status code. For example, if you pass the option to a `TODOS` resource that 404s, the wrapped component will have a prop called `todosStatus` that will be equal to `404`.
563
+ 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:
623
564
 
624
565
  ```js
625
- @withResources((props, ResourceKeys) => ({
626
- [ResourceKeys.TODOS]: {measure: true, status: true}
627
- }))
628
- class MyComponentWithTodos extends React.Component {}
566
+ getResources = ({CUSTOMER}) => ({[CUSTOMER]: {data: {id: props.customerId}}});
567
+
568
+ function MyCustomerComponent(props) {
569
+ var {customerModel} = useResources(getResources, props);
570
+
571
+ // now you can reference the id directly on the model
572
+ console.log(customerModel.get('id')); // or the id shorthand, customerModel.id
573
+ }
629
574
  ```
630
575
 
631
- Note that in the `useResources` hook, which does not pollute any `props` object, statuses are returned by default; you can choose which ones you want to use in your component and ignore the rest.
576
+ You can also use `data` to take advantage of [re-caching](/docs/advanced_topics.md#recaching-newly-saved-models).
577
+
578
+ 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.
579
+
580
+ ### dependsOn
581
+
582
+ See the section on [serial requests](#serial-requests).
632
583
 
584
+ ### provides
585
+
586
+ See the section on [serial requests](#serial-requests).
633
587
 
634
588
  # Data Mutations
635
589
 
@@ -702,30 +656,79 @@ Each one of these methods exhibit the following behaviors:
702
656
  **Note:**
703
657
  1. All calls resolve an array, which is a tuple of [model, response]. All reject with just the response.
704
658
  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.
659
+ 2.
705
660
 
661
+ ## Serial Requests
706
662
 
707
- # Differences between useResources and withResources
663
+ 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.
708
664
 
709
- The hook and HOC largely operate interchangeably, but do note a couple critical differences:
665
+ ```js
666
+ @withResources(({QUEUE_ITEM, USER}, props) => ({
667
+ [USER]: {
668
+ options: {userId: props.userId},
669
+ dependsOn: ['userId']
670
+ },
671
+ [QUEUE_ITEM]: {
672
+ data: {id: props.itemId}
673
+ provides: {userId: getUserIdFromItem}
674
+ }
675
+ }))
676
+ export default class QueueItemPage extends React.Component {}
677
+
678
+ function getUserIdFromItem(queueItemModel) {
679
+ return queueItemModel.get('userId');
680
+ }
681
+ ```
710
682
 
711
- 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.
683
+ 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.
712
684
 
713
- 1. The hooks's `setResourceState` function utilizes React's [useState](https://reactjs.org/docs/hooks-reference.html#usestate) hook, which does **not auto-merge updates like `setState` does**. Be sure to manually merge all resource state!
685
+ 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!
714
686
 
715
- ```jsx
716
- setResourceState((existingState) => ({
717
- ...existingState,
718
- timeRange: newTimeRange
719
- }));
720
- ```
687
+ 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).
721
688
 
722
- 1. The hook does not accept a [`{status: true}`](#status) option like the HOC does because it returns all statuses by default.
689
+ 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:
723
690
 
724
- 1. With the executor function now inlined in your component, be extra careful to avoid this anti-pattern:
691
+ ```js
692
+ const getResources = ({QUEUE_ITEM, USER}, props) => ({
693
+ [USER]: {
694
+ options: {state: props.activeState, userId: props.userId},
695
+ // userModel depends on multiple props from queueItemModel
696
+ dependsOn: ['activeState', 'userId']
697
+ },
698
+ [QUEUE_ITEM]: {
699
+ data: {id: props.itemId}
700
+ // use an underscore here to tell resourcerer to spread the resulting object
701
+ provides: {_: getUserDataFromItem}
702
+ }
703
+ });
704
+
705
+ export default function QueueItemPage(props) {
706
+ // activeState and userId are internal state within `useResources` and returned
707
+ var {
708
+ activeState,
709
+ userId,
710
+ userModel,
711
+ queueItemModel
712
+ } = useResources(getResources, props);
713
+ }
714
+
715
+ function getUserDataFromItem(queueItemModel) {
716
+ // transform function now returns an object of prop names/values instead of a simple prop value
717
+ return {userId: queueItemModel.get('userId'), activeState: queueItemModel.get('state')};
718
+ }
719
+ ```
720
+
721
+ # Differences between useResources and withResources
722
+
723
+ The hook and HOC largely operate interchangeably, but do note a couple critical differences:
724
+
725
+ 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.
726
+
727
+ 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:
725
728
 
726
729
  ```js
727
730
  function MyComponent({start_time, ...props}) {
728
- var {todosCollection} = useResources(({TODOS}, _props) => ({[TODOS]: {data: {start_time}}}), props);
731
+ var {todosCollection} = useResources(({TODOS}, _props) => ({[TODOS]: {params: {start_time}}}), props);
729
732
 
730
733
  // ...
731
734
  ```
@@ -734,15 +737,15 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
734
737
 
735
738
  ```js
736
739
  function MyComponent(props) {
737
- var {todosCollection} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {data: {start_time}}}), props);
740
+ var {todosCollection} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
738
741
 
739
742
  // ...
740
743
  ```
741
744
 
742
- or define your executor function outside of the component scope, as we've done throughout this tutorial (now you know why!):
745
+ or, even clearer, define your executor function outside of the component scope, as we've done throughout this tutorial (now you know why!):
743
746
 
744
747
  ```js
745
- const getResources = ({TODOS}, {start_time}) => ({[TODOS]: {data: {start_time}}});
748
+ const getResources = ({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}});
746
749
 
747
750
  function MyComponent(props) {
748
751
  var {todosCollection} = useResources(getResources, props);
@@ -762,7 +765,7 @@ Again, it’s unlikely that you’ll use `ModelCache` directly while using `reso
762
765
 
763
766
  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:
764
767
 
765
- 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.
768
+ 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.
766
769
 
767
770
  2. A function, whose return value is an object of keys and values that should both contribute to the cache key.
768
771
 
@@ -774,7 +777,7 @@ const getResources = (ResourceKeys, props) => {
774
777
 
775
778
  return {
776
779
  [ResourceKeys.USER_TODOS]: {
777
- data: {
780
+ params: {
778
781
  limit: props.limit,
779
782
  end_time: now,
780
783
  start_time: now - props.timeRange,
@@ -790,12 +793,8 @@ And our corresponding model definition might look like this:
790
793
 
791
794
  ```js
792
795
  export class UserTodosCollection extends Collection {
793
- constructor(models, options={}) {
794
- this.userId = options.userId;
795
- }
796
-
797
- url() {
798
- return `/users/${this.userId}/todos`;
796
+ url({userId}) {
797
+ return `/users/${userId}/todos`;
799
798
  }
800
799
  // ...
801
800
 
@@ -808,15 +807,15 @@ export class UserTodosCollection extends Collection {
808
807
  };
809
808
  ```
810
809
 
811
- 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.
810
+ 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.
812
811
 
813
- 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.
812
+ 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.
814
813
 
815
814
  The generated cache key would be something like `userTodos_limit=50_$range=86400000_sort_field=importance_userId=noah`. Again, note that:
816
815
 
817
816
  - the `userId` value is taken from the `options` hash
818
- - the `limit` and `sort_field` values are taken from the `data` hash
819
- - the `range` value is taken from a function that takes `start_millis`/`end_millis` from the `data` hash into account.
817
+ - the `limit` and `sort_field` values are taken from the `params` hash
818
+ - the `range` value is taken from a function that takes `start_millis`/`end_millis` from the `params` hash into account.
820
819
 
821
820
 
822
821
  ## Prefetch on Hover
@@ -827,12 +826,12 @@ You can use `resourcerer`'s executor function to optimistically prefetch resourc
827
826
  import {prefetch} from 'resourcerer';
828
827
 
829
828
  // here's our executor function just as we pass to useResources or withResources
830
- const getTodos = (props, ResourceKeys) => {
829
+ const getTodos = (ResourceKeys, props) => {
831
830
  const now = Date.now();
832
831
 
833
832
  return {
834
833
  [ResourceKeys.USER_TODOS]: {
835
- data: {
834
+ params: {
836
835
  limit: props.limit,
837
836
  end_time: now,
838
837
  start_time: now - props.timeRange,
@@ -862,7 +861,7 @@ It takes a function that is passed `ResourceKeys` and should return a list of `R
862
861
 
863
862
  ```js
864
863
  function MyComponent(props) {
865
- var {todosCollection, refetch} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {data: {start_time}}}), props);
864
+ var {todosCollection, refetch} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
866
865
 
867
866
  // ...
868
867
 
@@ -885,7 +884,7 @@ class MyMeasuredModel extends Model {
885
884
  static measure = true
886
885
 
887
886
  // or a function that returns a boolean, which will track instance requests based on a condition
888
- static measure = ({attributes={}}) => attributes.id === 'noahgrant'
887
+ static measure = ({data={}}) => data.id === 'noahgrant'
889
888
  }
890
889
  ```
891
890
 
@@ -944,22 +943,22 @@ ResourcesConfig.set(configObj);
944
943
  import {stringify} from 'qs';
945
944
 
946
945
  ResourcesConfig.set({
947
- stringify(data, options) {
948
- // data is the data object to be stringified into query parameters
946
+ stringify(params, options) {
947
+ // params is the params object to be stringified into query parameters
949
948
  // options is the request options object
950
- return stringify(data);
949
+ return stringify(params);
951
950
  }
952
951
  });
953
952
  ```
954
953
 
955
954
  * `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'`.
956
955
 
957
- * `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:
956
+ * `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:
958
957
 
959
958
  * the event string, `'API Fetch'`
960
959
  * event data object with the following properties:
961
960
  * Resource (string): the name of the resource (taken from the entry in `ResourceKeys`)
962
- * data (object): data object supplied via the resource's config
961
+ * params (object): params object supplied via the resource's config
963
962
  * options (object): options object supplied via the resource's config
964
963
  * duration (number): time in milliseconds between request and response
965
964
 
@@ -1059,12 +1058,12 @@ ResourcesConfig.set(configObj);
1059
1058
  </div>
1060
1059
  );
1061
1060
 
1062
- export withResources((props, ResourceKeys) => {
1061
+ export withResources((ResourceKeys, props) => {
1063
1062
  const now = Date.now();
1064
1063
 
1065
1064
  return {
1066
1065
  [ResourceKeys.USER_TODOS]: {
1067
- data: {
1066
+ params: {
1068
1067
  limit: 20,
1069
1068
  end_time: now,
1070
1069
  start_time: now - props.timeRange,
@@ -1080,7 +1079,7 @@ ResourcesConfig.set(configObj);
1080
1079
 
1081
1080
  * Can `resourcerer` do anything other than `GET` requests?
1082
1081
 
1083
- `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.
1082
+ `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.
1084
1083
 
1085
1084
  For write operations, use Models' [`save`](/docs/model.md#save) and [`destroy`](/docs/model.md#destroy) methods directly:
1086
1085
 
@@ -1107,7 +1106,7 @@ ResourcesConfig.set(configObj);
1107
1106
 
1108
1107
  * How big is the `resourcerer` package?
1109
1108
 
1110
- 13kB gzipped. It has no dependencies.
1109
+ Under 10kB gzipped. It has no dependencies.
1111
1110
 
1112
1111
  * Semver?
1113
1112