resourcerer 1.1.10 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,6 @@
4
4
  1. [Implicit dependent resources](#implicit-dependent-resources)
5
5
  1. [Unfetched Resources](#unfetched-resources)
6
6
  1. [Loading Overlays](#loading-overlays)
7
- 1. [isOrWillBeLoading](#isorwillbeloading)
8
7
  1. [Recaching newly-saved models](#recaching-newly-saved-models)
9
8
 
10
9
  ## Thoughts on the PENDING Resource
@@ -37,10 +36,12 @@ Using `dependsOn` in simple cases like the one highlighted in the [README](https
37
36
  1. We can modify the url in the component’s `componentDidUpdate`/`useEffect` (either url path or query parameter), which will filter the prop down.
38
37
 
39
38
  When we provide using method (a), the dependent prop can be changed but not removed. When we provide using method (b), the dependent prop can be changed or removed.
40
-
41
- So if we use method (b) and remove the dependent prop, we enter a state where `isLoading`, `hasLoaded`, and `hasErrored` are all false. And since we have to wait for a `componentDidUpdate`/`useEffect` to re-update the url with the dependent prop, a lifecycle passes with this state, and there’s really nothing we can do about it.
39
+
40
+ As an example of how we might be able to remove a dependent prop via method (b), consider someone navigating to a `/todos` url that auto-navigates to the first todo item and displays its details. The `todoItem` details resource depends on a `todoId` prop, which it gets in a `useEffect` via changing the url once the `todos` resource loads. So now we’re at `/todos/todo1234`. But if the user clicks the back button, we’ll be back at `/todos` with a cached `todos` resource and `PENDING` `todoItem` resource, and all three loading states set to `false`. (Yes, this is a bit contrived because you should actually replace the history entry in this case, but hopefully it helps to illuminate the issue.)
41
+
42
+ So if we remove the dependent prop, we enter a state where `isLoading`, `hasLoaded`, and `hasErrored` are all false. And since we have to wait for a `useEffect` to re-auto-update the url with the dependent prop, a lifecycle passes with this state, and there’s really nothing we can do about it.
42
43
 
43
- And again—`hasInitiallyLoaded` is still true and the model prop is empty, which can cause layout issues if you use, for example, an overlaid loader over a previously-rendered component. For this reason, if using classes/`withResources`, such a previously-rendered component should use `nextProps.hasLoaded` instead of `!nextProps.isLoading` in its `shouldComponentUpdate`:
44
+ And again—`hasInitiallyLoaded` is still true and the `todoItemModel` model prop is empty, which can cause layout issues if you use, for example, an overlaid loader over a previously-rendered component. For this reason, if using classes/`withResources`, such a previously-rendered component should use `nextProps.hasLoaded` instead of `!nextProps.isLoading` in its `shouldComponentUpdate`:
44
45
 
45
46
  ```js
46
47
  // overlay-wrapped component, where a loader will show over previously-rendered children,
@@ -59,10 +60,24 @@ Using `dependsOn` in simple cases like the one highlighted in the [README](https
59
60
  }
60
61
  ```
61
62
 
62
- As an example of how we might be able to remove a dependent prop, consider someone navigating to a `/todos` url that auto-navigates to the first todo item and displays its details. The `todoItem` details resource depends on a `todoId` prop, which it gets in a `componentWillReceiveProps` via changing the url once the `todos` resource loads. So now we’re at `/todos/todo1234`. But if the user clicks the back button, we’ll be back at `/todos` with a cached `todos` resource and `PENDING` `todoItem` resource, and all three loading states set to `false`. (Yes, this is a bit contrived because you should actually replace the history entry in this case, but hopefully it helps to illuminate the issue.)
63
+ If using `useResources`, we'll want to do the equivalent in our memo:
63
64
 
64
- 3. In the case that the model's `cacheFields` does not include the dependent prop (ie, the prop is used solely for triggering the resource request and doesn't factor into the request data), the model will still exist in the cache when the dependent prop is removed. In this case, the loading state is still returned to PENDING, but the existing model will also be present in the return value.
65
-
65
+ ```js
66
+ const MemoizedComponent = memo(<Component />, (prevProps, nextProps) => !nextProps.hasLoaded);
67
+
68
+ function Parent() {
69
+ return (
70
+ <div>
71
+ {isLoading ? <OverlayLoader /> : null}
72
+ {hasInitiallyLoaded ? <MemoizedComponent /> : null}
73
+ </div>
74
+ );
75
+ }
76
+ ```
77
+
78
+
79
+ 4. In the case that the model's `cacheFields` does not include the dependent prop (ie, the prop is used solely for triggering the resource request and doesn't factor into the request data), the model will still exist in the cache when the dependent prop is removed. In this case, the loading state is still returned to PENDING, but the existing model will also be present in the return value.
80
+
66
81
  ## Implicit dependent resources
67
82
 
68
83
  Another way to effectively have a dependent resource is to use a conditional in your `getResources` method:
@@ -207,48 +222,6 @@ export default function UserTodos(props) {
207
222
  }
208
223
  ```
209
224
 
210
- ## isOrWillBeLoading (`useResources` only)
211
-
212
- Taking the previous example of [Loading Overlays](#loading-overlays) just a bit further, what if the todosCollection was 5000 entries long? Okay, you'd probably paginate. But that's not the point! Let's say it's an `<ExpensiveComponent />`, and as it is now, when we change loading states, the parent `MyComponent` would render `<ExpensiveComponent />` on every change, which will kill your UX. So let's wrap it in a `React.memo`!
213
-
214
- But how do we tell `React.memo` when to not render? This is tricky for a couple of reasons:
215
-
216
- * Because `useEffect`/`componentDidUpdate` occurs _after_ render, we actually have two renders we want to opt out of:
217
- * parent props change
218
- * render is called (opt out!) **See Note**
219
- * resourcerer changes loaded state to loading from the change in props
220
- * render is called (opt out!). parent shows the overlay loader
221
- * request returns and loading state changes back to loaded
222
- * render (we want this update!)
223
-
224
- This is actually the reason why I am sad React did away with `componentWillReceiveProps` and does not offer an equivalent hook&mdash;using that instead would batch the props change and the loaded -> loading state change, and we'd only need to opt out of a single render. *sigh*. I digress.
225
-
226
- * React.memo, unlike `shouldComponentUpdate`, does not change its `prevProps` if it skips a render. This makes sense if you think about `memo` being a higher-order-component&mdash;if the component doesn't update, its props don't change. But that makes it much harder to compare `prevProps` and `nextProps` when needing to skip two update cycles.
227
-
228
- Enter `isOrWillBeLoading`. `isOrWillBeLoading` is a function returned by `useResources`/`withResources` that will take care of all these things for you, and you can invoke it in your `React.memo` [areEqual function](https://reactjs.org/docs/react-api.html#reactmemo). The previous example becomes:
229
-
230
- ```jsx
231
- import ExpensiveComponent from 'components/expensive_component/expensive_component';
232
- import {memo} from 'react';
233
- import {useResources} from 'resourcerer';
234
-
235
- const getResources = ({TODOS}, props) => ({[TODOS]: {}});
236
- const MemoizedExpensiveComponent = memo(ExpensiveComponent, (prevProps, nextProps) => nextProps.isOrWillBeLoading());
237
-
238
- export default function UserTodos(props) {
239
- const {isLoading, isOrWillBeLoading, hasInitiallyLoaded} = useResources(getResources, props);
240
-
241
- return (
242
- <div className='MyComponent'>
243
- {isLoading ? <Loader /> : null}
244
- {hasInitiallyLoaded ? <MemoizedExpensiveComponent {...{isOrWillBeLoading}} /> : null}
245
- </div>
246
- );
247
- }
248
- ```
249
-
250
- **Note:** A future upgrade to this library will utilize a [render bailout](https://react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes) to remove this unnecessary render. The other two will still be required, though.
251
-
252
225
  ## Recaching newly-saved models
253
226
 
254
227
  A common pattern when creating a new instance of a resource is to keep it in state until the user decides to explicitly save it. For example, when setting up a new
package/index.d.ts CHANGED
@@ -28,8 +28,11 @@ declare module 'resourcerer' {
28
28
  silent?: boolean;
29
29
  };
30
30
 
31
- declare class Model<T extends Record<string, any> = {[key: string]: any}> {
32
- constructor(attrs?: T, options?: Record<string, any> & SetOptions): Model;
31
+ declare class Model<
32
+ T extends Record<string, any> = {[key: string]: any},
33
+ O extends Record<string, any> & SetOptions = {[key: string]: any}
34
+ > {
35
+ constructor(attrs?: T, options?: O): Model<T, O>;
33
36
 
34
37
  // TODO: need to reference idAttribute here
35
38
  id: T extends {id: string} ? string : string | undefined;
@@ -61,9 +64,13 @@ declare module 'resourcerer' {
61
64
 
62
65
  toJSON(): T;
63
66
 
64
- url(urlOptions?: Record<string, any>): string;
67
+ url(urlOptions?: this["urlOptions"]): string;
68
+
69
+ urlRoot(urlOptions?: this["urlOptions"]): string;
65
70
 
66
- urlRoot(urlOptions?: Record<string, any>): string;
71
+ collection?: Collection;
72
+
73
+ readonly urlOptions: Omit<O, keyof SetOptions>;
67
74
 
68
75
  static cacheFields: Array<string | ((attrs: T) => Record<string, any>)>;
69
76
 
@@ -85,7 +92,7 @@ declare module 'resourcerer' {
85
92
  constructor(
86
93
  models?: ModelArg<T> | ModelArg<T>[],
87
94
  options?: O
88
- ): Collection<T>;
95
+ ): Collection<T, O>;
89
96
 
90
97
  length: number;
91
98
 
@@ -135,7 +142,9 @@ declare module 'resourcerer' {
135
142
 
136
143
  fetch(options?: {parse?: boolean} & SyncOptions & CSetOptions): Promise<[Collection<T>, Response]>;
137
144
 
138
- url(urlOptions?: O): string;
145
+ url(urlOptions?: this["urlOptions"]): string;
146
+
147
+ readonly urlOptions: Omit<O, keyof CSetOptions>;
139
148
 
140
149
  static cacheFields: Array<string | ((attrs: T) => Record<string, any>)>;
141
150
 
@@ -173,6 +182,7 @@ declare module 'resourcerer' {
173
182
  [key: `${string}LoadingState`]: LoadingTypes;
174
183
  [key: `${string}Collection`]: Collection;
175
184
  [key: `${string}Model`]: Model;
185
+ [key: `${string}Status`]: number;
176
186
  }
177
187
 
178
188
  declare function haveAllLoaded(loadingStates: LoadingTypes | LoadingTypes[]): boolean;
@@ -99,6 +99,13 @@ export const useResources = (getResources, props) => {
99
99
  // renders. using this reference will guarantee that we always remove listeners from the
100
100
  // correct models before attaching new listeners
101
101
  listenedModelsRef = useRef([]),
102
+ // when props change and we have models ready in the cache, we set model state in the render
103
+ // process. that means we re-run this function without calling any useEffect callbacks. since
104
+ // prevProps will not (and should not) have changed, the same models that we're to be updated
105
+ // as state in the first render phase would also be up for update in the next one. so we have
106
+ // to keep track of which models have been updated in state, and then we'll reset this when
107
+ // useEffect is finally called.
108
+ cachedModelsSinceLastEffect = useRef({}),
102
109
 
103
110
  forceUpdate = useForceUpdate(),
104
111
 
@@ -117,51 +124,57 @@ export const useResources = (getResources, props) => {
117
124
  // make sure if we were lazy and are no longer lazy (from the same component) that we
118
125
  // get included in the list to get updated (and vice versa)
119
126
  (prevConfig?.lazy !== config.lazy));
120
- });
121
-
122
- /**
123
- * Fetch things.
124
- * Ideally we would re-run this if any of the cache keys have changed, but
125
- * right now useEffect can't be run in a dynamic loop--it must be top-level.
126
- * So we must manually compare prevProps.
127
- *
128
- * Note also that every time we set a state, whether it be loading states or models, we are
129
- * setting a new object as that state and we will re-render. That means that if a model is cached
130
- * or its loading states haven't changed we should _not_ just go ahead and call fetchResources,
131
- * because that will re-render our components an additional two times.
132
- */
133
- useEffect(() => {
134
- var pendingResources = resources.filter(not(hasAllDependencies.bind(null, props)))
135
- .filter(([, config]) =>
136
- !prevPropsRef.current || hasAllDependencies(prevPropsRef.current, [, config])),
137
- resourcesToUpdate = getResourcesToUpdate(resources),
138
- nextLoadingStates = {
139
- ...buildResourcesLoadingState(pendingResources, props, LoadingStates.PENDING),
140
- // but resourcesToUpdate should get set to LOADING (or LOADED if in the cache)
141
- ...buildResourcesLoadingState(resourcesToUpdate.filter(withoutPrefetch), props)
142
- },
143
-
144
- // separate out those resources to update into those that are already cached and those
145
- // that need to be fetched. the former will get the models updated immediately
146
- [loadedResources, resourcesToFetch] = partitionResources(
147
- resourcesToUpdate,
148
- nextLoadingStates
149
- );
150
-
151
- // first set our updated resources' loading states to LOADING. but don't set if we're already
152
- // in a loading state for that resource, because that's a pointless extra render. also, any
153
- // resources that have lost their dependencies should go back to a pending state
154
- if (Object.keys(nextLoadingStates).some((ky) => nextLoadingStates[ky] !== loadingStates[ky])) {
155
- loaderDispatch({type: LoadingStates.LOADING, payload: nextLoadingStates});
156
- }
127
+ }),
128
+
129
+ // every time we call this, we remove all previous listeners and attach new ones based on the
130
+ // current models used by the component.
131
+ attachModelListeners = () => {
132
+ // only get those from the cache. models in state might can empty models, but even so i
133
+ // think it would be preferable to use state (within a separate useEffect) to determine
134
+ // which models get listened to. but as mentioned, that would require the effect to depend
135
+ // on cache keys, which are dynamic, and effects can't have dynamic dependencies right now
136
+ let listenedModels = resources.map(([, config]) => getModelFromCache(config))
137
+ .filter(Boolean);
138
+
139
+ // remove previous listeners and attach new ones
140
+ listenedModelsRef.current.forEach((model) => model.offUpdate(componentRef.current));
141
+ listenedModels.forEach((model) => model.onUpdate(forceUpdate, componentRef.current));
142
+
143
+ listenedModelsRef.current = listenedModels;
144
+ },
145
+
146
+ // this should be for NEW pending resources only, not ones set in initial loading state
147
+ pendingResources = resources.filter(not(hasAllDependencies.bind(null, props)))
148
+ .filter(([, config]) =>
149
+ prevPropsRef.current && hasAllDependencies(prevPropsRef.current, [, config])),
150
+ resourcesToUpdate = getResourcesToUpdate(resources),
151
+ nextLoadingStates = {
152
+ ...buildResourcesLoadingState(pendingResources, props, LoadingStates.PENDING),
153
+ // but resourcesToUpdate should get set to LOADING (or LOADED if in the cache)
154
+ ...buildResourcesLoadingState(resourcesToUpdate.filter(withoutPrefetch), props)
155
+ },
156
+
157
+ // separate out those resources to update into those that are already cached and those
158
+ // that need to be fetched. the former will get the models updated immediately
159
+ [loadedResources, resourcesToFetch] = partitionResources(
160
+ resourcesToUpdate,
161
+ nextLoadingStates
162
+ ),
157
163
 
158
- // pending resources: need to remove our model state here because it won't happen after a
159
- // request like the others, since no request is being made for pending resources. note that
160
- // this will stay as the requested model if the dependent prop does not affect the cache key.
161
- // loaded resources: we also don't fetch these, so we need to set our models immediately
162
- if (pendingResources.concat(loadedResources).length) {
163
- setModels(modelAggregator(pendingResources.concat(loadedResources).filter(withoutPrefetch)));
164
- }
164
+ // "cached" is a misnomer...
165
+ cachedResources = pendingResources.concat(loadedResources)
166
+ .filter(([name]) => !cachedModelsSinceLastEffect.current[name]);
167
+
168
+ // here we set any newly-pending resources as well as any already-loaded resources as model state,
169
+ // short-circuiting the render cycle since this update happens in the render phase. this is a
170
+ // critical piece of useResources because it means that models, dependent models, and also loading
171
+ // states (next block of code) get updated immediately with no extra 'in-between' blips on the
172
+ // screen.
173
+ if (cachedResources.length) {
174
+ setModels(modelAggregator(cachedResources));
175
+ cachedResources.forEach(([name, config]) => {
176
+ cachedModelsSinceLastEffect.current[name] = true;
177
+ });
165
178
 
166
179
  // because we don't go through the request module for normal-flow resources that are cached,
167
180
  // we need to re-register this component with the resource. this will also clear any timeouts
@@ -170,10 +183,32 @@ export const useResources = (getResources, props) => {
170
183
  var cacheKey = getCacheKey(config);
171
184
 
172
185
  ModelCache.register(cacheKey, componentRef.current);
173
- // make sure we add any provided props for serial requests
186
+ // make sure we add any provided props for serial requests. when this function rerenders any
187
+ // cached dependent models will also trigger a setModels call and an additional re-render
188
+ // without a useEffect
174
189
  provideProps(ModelCache.get(cacheKey), config.provides, props, setResourceState);
175
190
  });
176
191
 
192
+ // make sure if we bypass fetching because of cached models that we attach fresh listeners
193
+ attachModelListeners();
194
+ }
195
+
196
+ // set our updated resources' loading states to LOADING. but don't set if we're already in a
197
+ // loading state for that resource, because that's a pointless extra render. also, any resources
198
+ // that have lost their dependencies should go back to a pending state.
199
+ if (Object.keys(nextLoadingStates).some((ky) => nextLoadingStates[ky] !== loadingStates[ky])) {
200
+ loaderDispatch({type: LoadingStates.LOADING, payload: nextLoadingStates});
201
+ }
202
+
203
+ /**
204
+ * Fetch things.
205
+ *
206
+ * Note also that every time we set a state, whether it be loading states or models, we are
207
+ * setting a new object as that state and we will re-render. That means that if a model is cached
208
+ * or its loading states haven't changed we should _not_ just go ahead and call fetchResources,
209
+ * because that will re-render our components an additional two times.
210
+ */
211
+ useEffect(() => {
177
212
  // NOTE: changing this to resourcesToFetch causes some inexplicable bugs around cached resources
178
213
  // and a UI that wouldn't update. so this is kept as resourcesToUpdate and fetchResources is
179
214
  // given resourcesToFetch. Because we are still only fetching resourcesToFetch and because any
@@ -231,23 +266,14 @@ export const useResources = (getResources, props) => {
231
266
  }
232
267
  }).then(() => {
233
268
  if (isMountedRef.current) {
234
- // only get those from the cache. models in state might can empty models, but even so i
235
- // think it would be preferable to use state (within a separate useEffect) to determine
236
- // which models get listened to. but as mentioned, that would require the effect to depend
237
- // on cache keys, which are dynamic, and effects can't have dynamic dependencies right now
238
- let listenedModels = resources.map(([, config]) => getModelFromCache(config))
239
- .filter(Boolean);
240
-
241
- // remove previous listeners and attach new ones
242
- listenedModelsRef.current.forEach((model) => model.offUpdate(componentRef.current));
243
- listenedModels.forEach((model) => model.onUpdate(forceUpdate, componentRef.current));
244
-
245
- listenedModelsRef.current = listenedModels;
269
+ attachModelListeners();
246
270
  }
247
271
  });
248
272
  }
249
273
 
250
- return () => prevPropsRef.current = props;
274
+ prevPropsRef.current = props;
275
+ // now we can reset this value
276
+ cachedModelsSinceLastEffect.current = {};
251
277
  });
252
278
 
253
279
  // this effect attaches listeners to any bypassed models (ie, those passed in) which don't get
@@ -295,19 +321,6 @@ export const useResources = (getResources, props) => {
295
321
  ...props[ResourcesConfig.queryParamsPropName] || {},
296
322
  ...resourceState,
297
323
 
298
- // helpers
299
- isOrWillBeLoading: () => {
300
- var resourcesToUpdate = getResourcesToUpdate(
301
- resources.filter(withoutNoncritical).filter(withoutPrefetch)
302
- );
303
-
304
- // here we only look at resources to fetch, not loaded ones
305
- return !hasLoaded(criticalLoadingStates) || !!partitionResources(
306
- resourcesToUpdate,
307
- // 'next' loading states
308
- buildResourcesLoadingState(resourcesToUpdate, props)
309
- )[1].length;
310
- },
311
324
  refetch: (fn) => {
312
325
  var refetches = fn(ResourceKeys);
313
326
 
@@ -525,11 +538,11 @@ function findCacheKey(resource, getResources, props) {
525
538
  * @param {object} props - current component props
526
539
  * @param {LoadingStates} defaultState - state to return if resource already exists in cache;
527
540
  * in most circumstances, this should be the LOADED state as you might expect. However, when we
528
- * prep resources to be re-fetched or if models were previously created lazily (without fetching),
529
- * in order to keep the loading state in sync with its model state, even a cached resource should
530
- * be temporarily in a LOADING state (if cached, this will be corrected in the next microtask and
531
- * before the JS stack is completed, so the LOADING state should never be shown in the UI, despite
532
- * render being called multiple times).
541
+ * prep resources to be re-fetched, they should get put into a loading state. Because we use
542
+ * render bailouts to immediately update our loading states, a cached resource that no longer has
543
+ * its dependent props will go back to a PENDING state, but that could be just momentarily if the
544
+ * dependent prop gets added in a bailout, triggering an immediate re-render phase with no
545
+ * painting to screen. Lazy models should always be considered LOADED.
533
546
  * @return {object} state object with resource state keys as keys and the loading
534
547
  * state as values
535
548
  */
@@ -538,7 +551,11 @@ function buildResourcesLoadingState(resources, props, defaultState=LoadingStates
538
551
  [getResourceState(name)]: !config.refetch && (shouldBypassFetch(props, [name, config]) ||
539
552
  (getModelFromCache(config) && !getModelFromCache(config).lazy)) ?
540
553
  defaultState :
541
- (!hasAllDependencies(props, [, config]) ? LoadingStates.PENDING : LoadingStates.LOADING)
554
+ (!hasAllDependencies(props, [, config]) ? LoadingStates.PENDING : config.lazy ?
555
+ // any lazy resource should be considered loaded in its resource state, even
556
+ // though it will temporarily show up in the resourcesToUpdate list
557
+ LoadingStates.LOADED :
558
+ LoadingStates.LOADING)
542
559
  }), {});
543
560
  }
544
561
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "resourcerer",
3
- "version": "1.1.10",
3
+ "version": "1.2.0",
4
4
  "repository": "github.com/noahgrant/resourcerer",
5
5
  "description": "Declarative data-fetching and caching framework for React",
6
6
  "keywords": ["declarative data-fetching framework", "react"],