resourcerer 1.0.2 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  <img src="https://user-images.githubusercontent.com/1355779/61337603-f9fffd80-a7ea-11e9-9cb3-fa82e044c86e.png" alt="Resourcerer Icon" height="200" width="200" />
2
2
 
3
- # resourcerer (now in 1.0-beta!)
3
+ # resourcerer
4
4
 
5
5
  `resourcerer` is a library for declaratively fetching and caching your application's data. Its powerful [`useResources`](#useresources) React hook or [`withResources`](#withresources) higher-order React component (HOC) allows you to easily construct a component's data flow, including:
6
6
 
package/lib/request.js CHANGED
@@ -69,11 +69,14 @@ export default (key, Model, options={}) => {
69
69
  if (options.fetch && !options.lazy) {
70
70
  addToLoadingCache = true;
71
71
 
72
- delete model.lazy;
73
-
74
72
  model.fetch({params: options.params}).then(
75
73
  ([newModel, response]) => {
76
74
  delete loadingCache[key];
75
+ // waiting to delete lazy property until after fetch completes ensures multiple
76
+ // components that call non-lazy version of the resource all get put into a
77
+ // loading state
78
+ delete model.lazy;
79
+
77
80
  ModelCache.put(key, newModel, options.component);
78
81
  resolve([newModel, response?.status]);
79
82
  },
@@ -83,7 +86,7 @@ export default (key, Model, options={}) => {
83
86
  }
84
87
  );
85
88
  } else {
86
- // lazy means resolove but don't fetch yet; it will get updates from other components
89
+ // lazy means resolve but don't fetch yet; it will get updates from other components
87
90
  // we only want to do this if a model is not yet in the cache
88
91
  options.lazy && !ModelCache.get(key) ? model.lazy = true : null;
89
92
 
@@ -101,17 +101,21 @@ export const useResources = (getResources, props) => {
101
101
  listenedModelsRef = useRef([]),
102
102
 
103
103
  forceUpdate = useForceUpdate(),
104
- getPrevCacheKey = (rsrc) => findCacheKey(rsrc, getResources, prevPropsRef.current),
104
+
105
105
  // note that this only tells when cache keys have changed. if a resource has already been
106
106
  // cached, this will still return its resource when the component mounts. that's why we
107
107
  // partition these out later into loaded and not loaded resources
108
108
  getResourcesToUpdate = (rsrcs) => rsrcs.filter(hasAllDependencies.bind(null, props))
109
109
  .filter(not(shouldBypassFetch.bind(null, props)))
110
110
  .filter(([name, config]) => {
111
- var previousCacheKey = prevPropsRef.current && getPrevCacheKey([name, config]);
111
+ var prevConfig = findConfig([name, config], getResources, prevPropsRef.current || {}),
112
+ previousCacheKey = prevPropsRef.current && getCacheKey(prevConfig);
112
113
 
113
114
  return (!previousCacheKey || previousCacheKey !== getCacheKey(config) ||
114
- !hasAllDependencies(prevPropsRef.current, [, config]) || config.refetch);
115
+ !hasAllDependencies(prevPropsRef.current, [, config]) || config.refetch ||
116
+ // make sure if we were lazy and are no longer lazy (from the same component) that we
117
+ // get included in the list to get updated
118
+ (prevConfig.lazy && !config.lazy));
115
119
  });
116
120
 
117
121
  /**
@@ -499,19 +503,20 @@ function findCacheKey(resource, getResources, props) {
499
503
  * @param {object} props - current component props
500
504
  * @param {LoadingStates} defaultState - state to return if resource already exists in cache;
501
505
  * in most circumstances, this should be the LOADED state as you might expect. However, when we
502
- * prep resources to be re-fetched, in order to keep the loading state in sync with its model
503
- * state, even a cached resource should be temporarily in a LOADING state (if cached, this will
504
- * be corrected in the next microtask and before the JS stack is completed, so the LOADING state
505
- * should never be shown in the UI, despite render being called multiple times).
506
+ * prep resources to be re-fetched or if models were previously created lazily (without fetching),
507
+ * in order to keep the loading state in sync with its model state, even a cached resource should
508
+ * be temporarily in a LOADING state (if cached, this will be corrected in the next microtask and
509
+ * before the JS stack is completed, so the LOADING state should never be shown in the UI, despite
510
+ * render being called multiple times).
506
511
  * @return {object} state object with resource state keys as keys and the loading
507
512
  * state as values
508
513
  */
509
514
  function buildResourcesLoadingState(resources, props, defaultState=LoadingStates.LOADED) {
510
515
  return resources.reduce((state, [name, config]) => Object.assign(state, {
511
- [getResourceState(name)]:
512
- !config.refetch && (shouldBypassFetch(props, [name, config]) || getModelFromCache(config)) ?
513
- defaultState :
514
- (!hasAllDependencies(props, [, config]) ? LoadingStates.PENDING : LoadingStates.LOADING)
516
+ [getResourceState(name)]: !config.refetch && (shouldBypassFetch(props, [name, config]) ||
517
+ (getModelFromCache(config) && !getModelFromCache(config).lazy)) ?
518
+ defaultState :
519
+ (!hasAllDependencies(props, [, config]) ? LoadingStates.PENDING : LoadingStates.LOADING)
515
520
  }), {});
516
521
  }
517
522
 
@@ -683,10 +688,10 @@ function modelAggregator(resources) {
683
688
 
684
689
  /**
685
690
  * Separates out resources between those that are loading and those that have loaded. The latter
686
- * won't need to get passed to fetchResources, but the former will. Make sure that prefetched
687
- * resources get added to those that are loading so that the request gets made. Since prefetched
688
- * models don't factor into loading states, there's no concern that they get passed to
689
- * fetchResources even if they have been cached.
691
+ * won't need to get passed to fetchResources, but the former will. Make sure that prefetched,
692
+ * refetched, and lazy resources get added to those that are loading so that the request gets made.
693
+ * Since prefetched models don't factor into loading states, there's no concern that they get passed
694
+ * to fetchResources even if they have been cached.
690
695
  *
691
696
  * @param {array[]} resourcesToUpdate - resource configs to partition
692
697
  * @param {object} loadingStates - contains upcoming loading states for each resource
@@ -695,7 +700,8 @@ function modelAggregator(resources) {
695
700
  */
696
701
  function partitionResources(resourcesToUpdate, loadingStates) {
697
702
  return resourcesToUpdate.reduce((memo, [name, config]) =>
698
- config.refetch || config.prefetch || !hasLoaded(loadingStates[getResourceState(name)]) ?
703
+ config.refetch || config.prefetch || !hasLoaded(loadingStates[getResourceState(name)]) ||
704
+ getModelFromCache(config)?.lazy ?
699
705
  [memo[0], memo[1].concat([[name, config]])] :
700
706
  [memo[0].concat([[name, config]]), memo[1]],
701
707
  [[], []]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "resourcerer",
3
- "version": "1.0.2",
3
+ "version": "1.0.5",
4
4
  "repository": "github.com/noahgrant/resourcerer",
5
5
  "description": "Declarative data-fetching and caching framework for React",
6
6
  "keywords": [
@@ -306,12 +306,17 @@ describe('Request', () => {
306
306
  });
307
307
 
308
308
  it('fetches when another component requests the same model without lazy option', async() => {
309
- var [model] = await request('lazy', Model, {component, lazy: true});
309
+ var [model] = await request('lazy', Model, {component, lazy: true}),
310
+ requestPromise;
310
311
 
311
312
  expect(model.lazy).toBe(true);
312
313
  expect(Model.prototype.fetch).not.toHaveBeenCalled();
313
314
 
314
- [model] = await request('lazy', Model, {component});
315
+ requestPromise = request('lazy', Model, {component});
316
+
317
+ expect(model.lazy).toBeDefined();
318
+ await requestPromise;
319
+
315
320
  expect(model.lazy).not.toBeDefined();
316
321
  expect(Model.prototype.fetch).toHaveBeenCalled();
317
322