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