resourcerer 1.0.13 → 1.1.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.
@@ -0,0 +1,246 @@
1
+ # Collection
2
+
3
+ A collection is a client-side abstraction for the latest-saved server state of a list of objects (a model, by contrast, represents a single persisted object in that resource). A collection _must_ have one thing:
4
+ a `url`. This instance property can be a string literal or a function.
5
+
6
+ ```js
7
+ class MyTodos extends Collection {
8
+ url = '/todos'
9
+ }
10
+
11
+ class MyTodos extends Collection {
12
+ url({subtype}) {
13
+ return `/todos/${subtype}`;
14
+ }
15
+ }
16
+ ```
17
+
18
+ A collection instance of the class created and registered in your [resourcerer config](https://github.com/noahgrant/resourcerer#nomenclature) will be returned by every `useResources` call that uses its model key from the [ModelMap](https://github.com/noahgrant/resourcerer#tutorial). You can read simply from it
19
+ by using [`Collection#toJSON`](#tojson) (the most common usage), but there are several other methods and properties in its interface you can customize in your collection definition or
20
+ that you might find useful in rendering your data-hydrated components.
21
+
22
+ ## Properties
23
+
24
+ ### `static` comparator
25
+
26
+ Add this on your Collection definition to tell it how it should sort its models. It can take three forms:
27
+
28
+ 1. A string. In this case, it represents the model property to sort by.
29
+ 2. A function with a single argument. In this case, it takes a model's data as an argument and returns the value by which it should sort.
30
+ 3. A function with two arguments. This is used to sort the collection's models via the native [Array.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) method.
31
+
32
+ ### length
33
+
34
+ This is an instance property that represents the number of models in the collection.
35
+
36
+ ### `static` Model
37
+
38
+ Set this property if you want a collection's models to be an instance of a class other than the default Model
39
+
40
+ ### `static` cacheFields
41
+
42
+ This property tells resourcerer how to determine whether to make a new request or to take a collection out of the cache. It is an array of strings or functions from which its cache key is calculated. See the [cacheKey](https://github.com/noahgrant/resourcerer#caching-resources-with-modelcache) section for more info.
43
+
44
+ ### `static` cacheTimeout
45
+ `number`
46
+
47
+ The number of milliseconds to keep all collections of this class in the cache after all client components stop referencing it. Note that this is on a collection _class_ basis and not an _instance_ basis because the latter can introduce race conditions into your application.
48
+
49
+ ### `static` measure
50
+ `boolean|function`
51
+
52
+ A boolean or function that accepts a [resource configuration object](https://github.com/noahgrant/resourcerer#nomenclature) and returns a boolean, telling resourcerer to track this collection's request time and report it via the `track` method setup in [configuration](https://github.com/noahgrant/resourcerer#configuring-resourcerer).
53
+
54
+ ### `static` modelIdAttribute
55
+
56
+ Use this as a shortcut when you don't want to define a custom Model class just because the collection doesn't contain the default id field (which is `'id'`), ie:
57
+
58
+ ```js
59
+ // the collection will index its models based on the `name` property instead of the default `id` property
60
+ static modelIdAttribute = 'name'
61
+ ```
62
+
63
+
64
+
65
+ ## Methods
66
+
67
+ ### constructor
68
+
69
+ ```js
70
+ constructor: void (models: Array<Object|Model>, options: object)
71
+ ```
72
+
73
+ The Collection's constructor gets passed any initial models, as well as the [options](https://github.com/noahgrant/resourcerer#options) from the executor function. Override this to add some custom logic or instance variables for the collection&mdash;just be sure to pass the arguments to its `.super()` call, as well:
74
+
75
+ ```js
76
+ class MyCollection extends Collection {
77
+ constructor(models, options={}) {
78
+ super(models, options);
79
+
80
+ // initializing some variable to be used later
81
+ this.categoriesList = [];
82
+ }
83
+
84
+ url({category}) {
85
+ return `/todos/${category}`;
86
+ }
87
+ }
88
+ ```
89
+
90
+ Passing in a `Model` option or a `comparator` option to an instance's constructor will override the statically defined properties on its constructor. Other `options` fields (the ones passed from the executor function [options](https://github.com/noahgrant/resourcerer#options) property) are passed to the `url` as shown in the example above.
91
+
92
+
93
+ ### add
94
+ ```js
95
+ add: Collection (models: (Object|Model)|Array<Object|Model>, options: Object)
96
+ ```
97
+
98
+ Add a new entry or list of entries into the collection. Each entry can be an object of data or a Model instance. Will trigger an update in all subscribed components unless the `trigger: true` option is passed. You can also pass a `parse: true` option to run the model through its [parse](/docs/model.md#parse) method before setting its properties. If an entry already exists on the collection, the new properties will get merged into its existing model.
99
+
100
+ ### create
101
+ ```js
102
+ create: Promise<[Model, Response]> (model: (Object|Model), options: Object)
103
+ ```
104
+
105
+ Adds a new entry to the collection and persists it to the server. This is literally the equivalent to calling `collection.add()` and then `model.save()`. Because it also instantiates the new model, be sure to pass any path params you need in your url as the options argument (the same [options](https://github.com/noahgrant/resourcerer#options) in the resource config object). The returned Promise is the same as is returned from [Model#save](/docs/model.md#save). If the request errors, the model is auto-removed from the collection. Pass the `wait: true` option to wait to add the new model until after the save request returns. Subscribed components will update when the new entry is added as well as when the request returns.
106
+
107
+ ***All .create() calls must have a .catch attached, even if the rejection is swallowed. Omitting one risks an uncaught Promise rejection exception if the request fails.***
108
+
109
+ ### fetch
110
+ ```js
111
+ fetch: Promise<[Collection, Response]> (options: Object)
112
+ ```
113
+
114
+ This is the method that `resourcerer` uses internally to get server data and set its parsed response as models on the collection. This should rarely need to be used in your application. Subscribed components will update when the request returns.
115
+
116
+ ***All .fetch() calls must have a .catch attached, even if the rejection is swallowed. Omitting one risks an uncaught Promise rejection exception if the request fails.***
117
+
118
+
119
+ ### get
120
+ ```js
121
+ get: Model? (identifier: string|number)
122
+ ```
123
+
124
+ Collections index their Model instances by either the Model's [`idAttribute`](/docs/model.md#static-idattribute) or, equivalently as a shortcut, by the collection's own static [`modelIdAttribute`](#static-modelidattribute) property. The `.get()` method takes an id value and returns the quick-lookup model instance if one exists.
125
+
126
+ ### has
127
+ ```js
128
+ has: boolean (identifier: string|number|Model|object)
129
+ ```
130
+
131
+ Returns whether or not a model exists in a collection. You can pass the model instance itself, a model's data, or a model's id.
132
+
133
+ ### parse
134
+ ```js
135
+ parse: Array<Object> (response: any)
136
+ ```
137
+
138
+ This method takes in the raw server data response and should return the data in the form that should be set on the Collection. It defaults to the identity function, which might suffice for many endpoints. Override this for your custom needs. For example, for some search results with some metadata (in an API that returns a JSON object), we want to set the results as the collection:
139
+
140
+ ```js
141
+ parse(response) {
142
+ this.totalResults = response.totalResults;
143
+ this.pageNumber = response.pageNumber;
144
+ this.resultsPerPage = response.resultsPerPage;
145
+
146
+ return response.results;
147
+ }
148
+ ```
149
+
150
+ ### remove
151
+ ```js
152
+ remove: Collection (models: (Object|Model)|Array<Object|Model>, options: Object)
153
+ ```
154
+
155
+ Use this to remove a model or models from the collection, which should not often be needed. You can pass in anything or a list of anything that can be accepted via [.get()](#get). Pass in `silent: true` for subscribed components _not_ to get rerendered.
156
+
157
+ ### reset
158
+ ```js
159
+ reset: Collection (models: Array<Object|Model>, options: Object)
160
+ ```
161
+
162
+ Removes all models and their references from a collection and replaces them with the models passed in. Pass in `silent: true` for subscribed components _not_ to get rerendered, and `parse: true` to have data get parsed before being set on their respective models.
163
+
164
+ ### set
165
+ ```js
166
+ set: Collection (models: (Object|Model)|Array<Object|Model>, options: Object)
167
+ ```
168
+
169
+ This is the method that many other write methods (`add`, `remove`, `save`, `reset`, etc) use under the hood, and it should _rarely if ever_ need to be used directly in your application. Sets new data as models and merges existing data with their models, and sorts as necessary. Pass in `silent: true` for subscribed components _not_ to get rerendered, and `parse: true` to have data get parsed before being set on their respective models.
170
+
171
+ ### sync
172
+ This is just a proxy for the [sync](/lib/sync.js) module. Its behavior shouldn't be overridden, but it may be useful to wrap it for custom behavior, ie:
173
+
174
+ ```js
175
+ Collection.sync = Model.sync = function(model, options) {
176
+ // custom logic...
177
+
178
+ // defer again to the sync module
179
+ return sync(this, options);
180
+ }
181
+ ```
182
+
183
+ ### toJSON
184
+ ```js
185
+ toJSON: Array<Object> ()
186
+ ```
187
+
188
+ Returns each model's data objects in a new array.
189
+
190
+ ## Utility instance methods
191
+
192
+ ### at
193
+ ```js
194
+ at: Model (index: number)
195
+ ```
196
+
197
+ Returns the model at a given index in the collection. Index can be negative to count backwards from the end.
198
+
199
+ ### filter
200
+ ```js
201
+ filter: Array<Model> (predicate: function)
202
+ ```
203
+
204
+ Same signature as Array.prototype.filter across a collection's models.
205
+
206
+ ### find
207
+ ```js
208
+ find: Model? (predicate: function)
209
+ ```
210
+
211
+ Same signature as Array.prototype.find across a collection's models.
212
+
213
+ ### findWhere
214
+ ```js
215
+ findWhere: Model? (attrs: object)
216
+ ```
217
+
218
+ Returns the model matching the attributes passed in, or undefined if no match is found. Like `.find` but a shorthand that uses matching attribute values instead of a predicate function.
219
+
220
+ ### map
221
+ ```js
222
+ map: Array<any> (predicate: function)
223
+ ```
224
+
225
+ Same signature as Array.prototype.map across a collection's models.
226
+
227
+ ### pluck
228
+ ```js
229
+ pluck: Array<any> (attribute: string)
230
+ ```
231
+
232
+ Returns a list of the specified attribute value for all models.
233
+
234
+ ### slice
235
+ ```js
236
+ slice: Array<Model> (startIndex:number[, endIndex: number])
237
+ ```
238
+
239
+ Same signature as Array.prototype.slice across a collection's models.
240
+
241
+ ### where
242
+ ```js
243
+ where: Array<Model> (attrs: object)
244
+ ```
245
+
246
+ Returns a list of models matching the data values passed in. Like `.filter` but a shorthand that uses matching data values instead of a predicate function.
package/docs/model.md ADDED
@@ -0,0 +1,203 @@
1
+ # Model
2
+
3
+ A model is a client-side abstraction for a latest-saved server state of an object (a collection, by contrast, represents a list of models). A model _must_ have one thing:
4
+ a `url`. This can come in several forms:
5
+
6
+ * a string literal
7
+
8
+ ```js
9
+ class MyModel extends Model {
10
+ url = '/endpoint'
11
+ }
12
+ ```
13
+
14
+ * a function
15
+
16
+ ```js
17
+ class MyModel extends Model {
18
+ url() {
19
+ return '/endpoint';
20
+ }
21
+ }
22
+ ```
23
+
24
+ * from the model's collection. in this case, no `url` property on the model is needed, and the model's id will be URL-encoded and appended to the collection's url.
25
+
26
+ * a `urlRoot` property. use this when a model is not part of a collection but when passed an id, you'd still like the id to be URL-encoded and appended to the root.
27
+
28
+ ```js
29
+ class MyModel extends Model {
30
+ // with an id of '12345', requests will be made to /endpoint/12345.
31
+ urlRoot() {
32
+ return '/endpoint';
33
+ }
34
+ }
35
+ ```
36
+
37
+ A model instance of the class created and registered in your [resourcerer config](https://github.com/noahgrant/resourcerer#nomenclature) will be returned by every `useResources` call that uses its model key. You can read simply from it
38
+ by using [Model#toJSON](#tojson) (the most common usage), but there are several other methods and properties in its interface you can customize in your collection definition or
39
+ that you might find useful in rendering your data-hydrated components.
40
+
41
+ ## Properties
42
+
43
+ ### `static` cacheFields
44
+ `Array<string|function>`
45
+
46
+ This property tells resourcerer how to determine whether to make a new request or to take a model out of the cache. It is an array of strings or functions from which its cache key is calculated. See the [cacheKey](https://github.com/noahgrant/resourcerer#caching-resources-with-modelcache) section for more info.
47
+
48
+ ### `static` cacheTimeout
49
+ `number`
50
+
51
+ The number of milliseconds to keep all models of this class in the cache after all client components stop referencing it. Note that this is on a model _class_ basis and not an _instance_ basis because the latter can introduce race conditions into your application.
52
+
53
+ ### `static` idAttribute
54
+ `string`. Default: `'id'`.
55
+
56
+ Override this to be the property name of the Model's unique identifier if it something other than `'id'`. Each model instance will get an `id` instance property that will be equal to that value. i.e. if the Model class has `static idAttribute = 'email'` and the Model is instantiated with `{email: 'noah@gmail.com'}`, then `model.id === 'noah@gmail.com'`.
57
+
58
+ ### `static` defaults
59
+ `object|function`
60
+
61
+ An object or function that returns object with attribute keys and their default values. If set, then when the model is instantiated, any missing data get set to these values.
62
+
63
+ ### `static` measure
64
+ `boolean|function`
65
+
66
+ A boolean or function that accepts a [resource configuration object](https://github.com/noahgrant/resourcerer#nomenclature) and returns a boolean, telling resourcerer to track this model's request time and report it via the `track` method setup in [configuration](https://github.com/noahgrant/resourcerer#configuring-resourcerer).
67
+
68
+
69
+
70
+ ## Methods
71
+
72
+ ### constructor
73
+
74
+ ```js
75
+ constructor: void (initialData: Object, options: object)
76
+ ```
77
+
78
+ The Model's constructor gets passed any initial data, as well as the [options](https://github.com/noahgrant/resourcerer#options) from the executor function. Override this to add some custom logic or instance variables for the model&mdash;just be sure to pass the arguments to its `.super()` call, as well:
79
+
80
+ ```js
81
+ class MyModel extends Model {
82
+ constructor(initialData, options={}) {
83
+ super(initialData, options);
84
+
85
+ // custom logic
86
+ }
87
+
88
+ url({category}) {
89
+ return `/todos/${category}/${this.id}`;
90
+ }
91
+ }
92
+ ```
93
+
94
+ Note that `this.id` is automatically set to whichever value is passed in at the [`idAttribute`](#static-idattribute) key (default: 'id'). Pass the `parse: true` option to have the data get run through the Model's `parse` method before getting set. Other [options](https://github.com/noahgrant/resourcerer#options) fields from the executor function are passed to the `url` as shown in the example above.
95
+
96
+
97
+ ### toJSON
98
+ ```js
99
+ toJSON: Object ()
100
+ ```
101
+
102
+ Returns the model's data in a new object.
103
+
104
+ ### get
105
+ ```js
106
+ get: any (attribute: string)
107
+ ```
108
+
109
+ Returns the value at the given attribute key.
110
+
111
+ ### has
112
+ ```js
113
+ has: boolean (attribute: string)
114
+ ```
115
+
116
+ Returns true if the model has a defined value at the given attribute key
117
+
118
+ ### isNew
119
+ ```js
120
+ isNew: boolean ()
121
+ ```
122
+
123
+ By default, a model is considered 'new' if it does not have an id (or a value at the [`idAttribute`](#static-idattribute) proeprty. It is used to determine:
124
+
125
+ 1. Whether to send a POST (new) or a PUT (not new) request when calling [`.save()`](#save)
126
+ 2. Whether to send a request at all when calling [`.destroy()`](#destroy)
127
+
128
+ Use this to your advantage when you inevitably come across some orphan endpoints that are not super REST-y. Override your Model class to force all `.save` calls to POST by, for example:
129
+
130
+ ```js
131
+ isNew() {
132
+ // will always POST
133
+ return true;
134
+ }
135
+ ```
136
+
137
+ ### parse
138
+ ```js
139
+ parse: object (response: any)
140
+ ```
141
+
142
+ This method takes in the raw server data response and should return the data in the form that should be set on the Model. It defaults to the identity function, which might suffice for many endpoints. Override this for your custom needs. For example, maybe your server overly-nests the resource in a `schema` property:
143
+
144
+ ```js
145
+ parse(response) {
146
+ return response.data.schema;
147
+ }
148
+ ```
149
+
150
+ ### set
151
+ ```js
152
+ set: Model (data: object, options: object)
153
+ ```
154
+
155
+ This is the main avenue by which a model's properties get values assigned. It's called internally by several public methods, including `save`, `unset`, and `clear`. Pass a `silent: true` option for this not to trigger a re-render for subscribed components.
156
+
157
+ ### unset
158
+ ```js
159
+ unset: Model (attribute: string, options: object)
160
+ ```
161
+
162
+ Removes the attribute from the model's data. Pass a `silent: true` option for this not to trigger a re-render for subscribed components.
163
+
164
+ ### clear
165
+ ```js
166
+ clear: Model (options: object)
167
+ ```
168
+
169
+ Removes all data from the model. Pass a `silent: true` option for this not to trigger a re-render for subscribed components.
170
+
171
+ ### pick
172
+ ```js
173
+ pick: object (...data: Array<string>)
174
+ ```
175
+
176
+ Handy helper method to only return a subset of a model's data, as opposed to the whole thing like [`.toJSON()`](#tojson) does.
177
+
178
+ ### save
179
+ ```js
180
+ save: Promise<[Model, Response]> (data: object, options: object)
181
+ ```
182
+
183
+ Use this to persist data mutations to the server. If [`.isNew()`](#isnew) is true, the request will be sent as a POST. Otherwise, it will be sent as a PUT with the whole resource, or a PATCH with only `data` sent over if the `patch: true` option is passed. When the request returns, the server data is passed through the [`.parse()`](#parse) method before being set on the model. Pass the `wait: true` option to wait to add the data until after the server responds. Subscribed components will update when the new entry is added as well as when the request returns. If the request errors, all changes will be reverted and components updated.
184
+
185
+ ***All .save() calls must have a .catch attached, even if the rejection is swallowed. Omitting one risks an uncaught Promise rejection exception if the request fails.***
186
+
187
+ ### destroy
188
+ ```js
189
+ destroy: Promise<[Model, Response]> (options: object)
190
+ ```
191
+
192
+ Use this to remove the send a DELETE request at this model's url to the server. The model is removed from its collection if it belongs to one. If [`.isNew()`](#isnew) is false (signifying that the model was never persisted in the first place), a request is not sent, but the model is still removed from its collection. Pass the `wait: true` option to wait to remove the model until after the server responds. Subscribed components will update when the model is removed. If the request errors, the model will get added back to its collection and components will get updated.
193
+
194
+ ***All .destroy() calls must have a .catch attached, even if the rejection is swallowed. Omitting one risks an uncaught Promise rejection exception if the request fails.***
195
+
196
+ ### fetch
197
+ ```js
198
+ fetch: Promise<[Model, Response]> (options: Object)
199
+ ```
200
+
201
+ This is the method that `resourcerer` uses internally to get server data and set its parsed response as models on the collection. This should rarely need to be used in your application. Subscribed components will update when the request returns.
202
+
203
+ ***All .fetch() calls must have a .catch attached, even if the rejection is swallowed. Omitting one risks an uncaught Promise rejection exception if the request fails.***
@@ -0,0 +1,58 @@
1
+ ## Testing Components that Use Resourcerer
2
+
3
+ When writing tests for components that use either the `useResources` hook or the `withResources` HOC, we want to be able to easily avoid any kind of async behavior with the data fetching&mdash;and ideally we don’t even need to stub out the `fetch` requests. One way to get around this is to pass all resources to your test component as props. When this happens, the fetching is bypassed, and the component will render synchronously with the resources present, no stubbing necessary! Here’s an example for a component called `UserTodosList` that requires both a usersCollection and a todosCollection:
4
+
5
+ ```js
6
+ import {Collection} from 'resourcerer';
7
+
8
+ // ...
9
+ const defaultProps = () => ({
10
+ todosCollection: new Collection(mockTodos),
11
+ usersCollection: new Collection(mockUsers),
12
+ userId: 'noah'
13
+ },
14
+
15
+ renderUserTodosList = (props={}) => render(<UserTodosList {...defaultProps()} {...props} />);
16
+
17
+
18
+ it('runs a test', () => {
19
+ // both resources are passed as props, so no fetching takes place, `hasLoaded` is always true,
20
+ // and the component is rendered synchronously!
21
+ var userTodosList = renderUserTodosList();
22
+ });
23
+ ```
24
+
25
+ ### Changing resource loading states
26
+
27
+ When using `resourcerer`, you are using React function components that have no backing instances (and thus whose return from `render` is `null`). Therefore, we can't assert any prop values on components and we can't navigate a DOM tree the way we can when using classes. However, we can simply mock out `useResources` itself to test functionality. Because the `withResources` HOC also uses `useResources` under the hood, this will work when testing both. Here's an example (using [jest](https://jestjs.io/) and [react testing library](https://testing-library.com/docs/react-testing-library/intro/)) for testing how a component that uses `useResources` looks under a loading state:
28
+
29
+ ```jsx
30
+ import * as resourcerer from 'resourcerer';
31
+ import {render} from '@testing-library/react';
32
+
33
+ // ...
34
+ it('shows a loader when in a loading state', () => {
35
+ jest.spyOn(resourcerer, 'useResources').mockImplementation((fn, props) => ({
36
+ ...props,
37
+ hasLoaded: false,
38
+ isLoading: true
39
+ ));
40
+
41
+ const {container} = render(<MyComponent />);
42
+
43
+ expect(container.querySelector('.Loader')).toBeInTheDocument();
44
+ });
45
+ ```
46
+
47
+ This should solve most of your use cases; you can return any mocked info you want, such as a noncritical loading state. You can also mock out `setResourceState`:
48
+
49
+ ```jsx
50
+ var setResourceMock = jest.fn();
51
+
52
+ jest.spyOn(resourcerer, 'useResources').mockImplementation((fn, props) => ({
53
+ ...props,
54
+ setResourceState: setResourceMock
55
+ ));
56
+ ```
57
+
58
+ Keep in mind that in this case the calls to `setResourceState` won't actually go through, and so state won't persist.
@@ -0,0 +1,94 @@
1
+ # Using resourcerer with TypeScript
2
+
3
+ _Note: TypeScript support is in beta. Please file any bugs._
4
+
5
+ Resourcerer is ⚡⚡⚡ with TypeScript, but requires one extra step in your config file:
6
+
7
+ ```ts
8
+ // js/core/resourcerer-config.ts
9
+ import {ModelMap} from 'resourcerer';
10
+ import TodosCollection from 'js/models/todos-collection';
11
+ import UserTodosCollection from 'js/models/users-todos-collection';
12
+
13
+ /**
14
+ * Because the ModelMap is populated in user-land, we have to annotate its types here, as well.
15
+ * Add your model types to this interface declaration, which will be merged with the interface
16
+ * in the library.
17
+ *
18
+ * I wish we didn't have to do this duplication, and maybe there's a way to do it without, but
19
+ * I am not good enough at TypeScript to figure it out myself. If you can, please submit a PR!
20
+ */
21
+ declare module 'resourcerer' {
22
+ export interface ModelMap {
23
+ todos: new () => TodosCollection,
24
+ userTodos: new () => UserTodosCollection,
25
+ // ...etc
26
+ }
27
+ }
28
+
29
+ / now add your models to the model map as normal
30
+ ModelMap.add({
31
+ todos: TodosCollection,
32
+ userTodos: UserTodosCollection,
33
+ // ...etc
34
+ });
35
+ ```
36
+
37
+ Note that you no longer need to add a resource key like `USER_TODOS` in the ModelMap, which would normally get
38
+ auto-magically turned into the camelCase `userTodos`. Since TypeScript will enforce correctness, you can just
39
+ use the string literal `userTodos` instead.
40
+
41
+ When defining your models, you can add schemas as generic types:
42
+
43
+ ```ts
44
+ // js/models/todos-collection.ts
45
+ import {Collection} from 'resourcerer';
46
+
47
+ interface Todo {
48
+ id: string;
49
+ name: string;
50
+ }
51
+
52
+ export default TodosCollection extends Collection<Todo> {
53
+ url() {
54
+ return '/todos';
55
+ }
56
+ }
57
+ ```
58
+
59
+ and now you can use it in your components!
60
+
61
+ ```tsx
62
+ import {type ExecutorFunction, useResources} from 'resourcerer';
63
+
64
+ // you don't need to worry about resourceKeys anymore, you can just use the
65
+ // string literal! TypeScript will enforce correctness
66
+ const getResources: ExecutorFunction = (resourceKeys, props) => ({todos: {}});
67
+
68
+ function MyComponent(props) {
69
+ const {
70
+ isLoading,
71
+ hasErrored,
72
+ hasLoaded,
73
+ // type: TodosCollection
74
+ todosCollection
75
+ } = useResources(getResources, props);
76
+
77
+ return (
78
+ <div className='MyComponent'>
79
+ {isLoading ? <Loader /> : null}
80
+
81
+ {hasErrored ? <ErrorMessage /> : null}
82
+
83
+ {hasLoaded ? (
84
+ <ul>
85
+ {/** id and name are registered as string types, hurray! */}
86
+ {todosCollection.toJSON().map(({id, name}) => (
87
+ <li key={id}>{name}</li>
88
+ ))}
89
+ </ul>
90
+ ) : null}
91
+ </div>
92
+ );
93
+ }
94
+ ```