resourcerer 1.2.2 → 1.2.3

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
@@ -139,6 +139,7 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
139
139
  1. [prefetches](#prefetches)
140
140
  1. [data](#data)
141
141
  1. [lazy](#lazy)
142
+ 1. [minDuration](#minduration)
142
143
  1. [dependsOn](#dependson)
143
144
  1. [provides](#provides)
144
145
  1. [Data mutations](#data-mutations)
@@ -627,6 +628,10 @@ function TodoSearchItem(props) {
627
628
 
628
629
  If the todo model has been fetched already, we'll read straight from that. And if it gets updated, this component, via resourcerer, is listening for updates and will re-render to keep our entire UI in sync. Otherwise, we'll just fall back to our read-only search results. WIN!
629
630
 
631
+ ### minDuration
632
+
633
+ Sometimes requests can be _too_ fast for certain UIs. In these cases, spinners and other loading states can appear more like a jarring flicker than a helpful status indicator. For these, you can pass a `minDuration` equal to the minimum number of milliseconds that a request should take. This is great for [save and destroy](#data-mutations) requests. It will work for fetch requests via `useResources`, as well, but beware: if multiple components use the same resource and there are different (or missing) values for `minDuration`, this will cause a race condition.
634
+
630
635
  ### dependsOn
631
636
 
632
637
  See the section on [serial requests](#serial-requests).
package/index.d.ts CHANGED
@@ -13,6 +13,7 @@ declare module 'resourcerer' {
13
13
  method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
14
14
  params?: Record<string, any>;
15
15
  url?: string;
16
+ minDuration?: number;
16
17
  // they are free to add any other options they like
17
18
  [key: string]: any;
18
19
  };
@@ -106,6 +106,7 @@ export const useResources = (getResources, props) => {
106
106
  // to keep track of which models have been updated in state, and then we'll reset this when
107
107
  // useEffect is finally called.
108
108
  cachedModelsSinceLastEffect = useRef({}),
109
+ refetchedModelsSinceLastEffect = useRef({}),
109
110
 
110
111
  forceUpdate = useForceUpdate(),
111
112
 
@@ -123,7 +124,13 @@ export const useResources = (getResources, props) => {
123
124
  previousCacheKey = prevConfig && getCacheKey(prevConfig);
124
125
 
125
126
  return (!previousCacheKey || previousCacheKey !== getCacheKey(config) ||
126
- !hasAllDependencies(prevPropsRef.current, [, config]) || config.refetch ||
127
+ !hasAllDependencies(prevPropsRef.current, [, config]) ||
128
+ // we only want to refetch if the resource is currently in a loaded state. but then
129
+ // we'll move to a loading state and short-circuit the render cycle, and it won't be
130
+ // loaded in the next cycle. that's why we use the ref, as well
131
+ (config.refetch &&
132
+ (hasLoaded(loadingStates[getResourceState(name)]) ||
133
+ refetchedModelsSinceLastEffect.current[name])) ||
127
134
  // make sure if we were lazy and are no longer lazy (from the same component) that we
128
135
  // get included in the list to get updated (and vice versa)
129
136
  (prevConfig?.lazy !== config.lazy));
@@ -202,6 +209,14 @@ export const useResources = (getResources, props) => {
202
209
  attachModelListeners();
203
210
  }
204
211
 
212
+ // register any refetched items in the ref so that when we short-circuit the render we still
213
+ // know which ones we need to fetch
214
+ resourcesToFetch.forEach(([name, config]) => {
215
+ if (config.refetch) {
216
+ refetchedModelsSinceLastEffect.current[name] = true;
217
+ }
218
+ });
219
+
205
220
  // set our updated resources' loading states to LOADING. but don't set if we're already in a
206
221
  // loading state for that resource, because that's a pointless extra render. also, any resources
207
222
  // that have lost their dependencies should go back to a pending state.
@@ -263,7 +278,7 @@ export const useResources = (getResources, props) => {
263
278
  onRequestFailure: (status, [name, config]) => {
264
279
  ReactDOM.unstable_batchedUpdates(() => {
265
280
  // request failed, which means this model should not be in the cache. but we still want
266
- // to // set our model state so that when we go back into a loading state, the empty
281
+ // to set our model state so that when we go back into a loading state, the empty
267
282
  // model is present instead of any previously-loaded model
268
283
  setModels(modelAggregator([[name, config]]));
269
284
 
@@ -281,8 +296,9 @@ export const useResources = (getResources, props) => {
281
296
  }
282
297
 
283
298
  prevPropsRef.current = props;
284
- // now we can reset this value
299
+ // now we can reset these values
285
300
  cachedModelsSinceLastEffect.current = {};
301
+ refetchedModelsSinceLastEffect.current = {};
286
302
  });
287
303
 
288
304
  // this effect attaches listeners to any bypassed models (ie, those passed in) which don't get
@@ -307,17 +323,6 @@ export const useResources = (getResources, props) => {
307
323
  };
308
324
  }, []);
309
325
 
310
- /**
311
- * This effect promptly removes any entries placed in the `refetches` resources state array.
312
- * Doing this here ensures that we don't have repeated effects with refetches, since that passes
313
- * them through the `resourcesToUpdate` path.
314
- */
315
- useEffect(() => {
316
- if ((props.refetches || []).length) {
317
- setResourceState(({refetches, ...state}) => state);
318
- }
319
- }, [(props.refetches || []).join()]);
320
-
321
326
  currentPropsRef.current = props;
322
327
 
323
328
  return {
@@ -331,11 +336,22 @@ export const useResources = (getResources, props) => {
331
336
  ...resourceState,
332
337
 
333
338
  refetch: (fn) => {
334
- var refetches = fn(ResourceKeys);
335
-
336
- if (refetches.length) {
337
- setResourceState((state) => ({...state, refetches}));
338
- }
339
+ ReactDOM.unstable_batchedUpdates(() => {
340
+ fn(ResourceKeys).forEach((name) => {
341
+ var model = getModelFromCache(
342
+ findConfig([name, {}], getResources, props)
343
+ );
344
+
345
+ /**
346
+ * Set a refetching flag on the model and re-render. This will cause all components
347
+ * that use this model to re-render and put it back in a loading state.
348
+ */
349
+ if (model) {
350
+ model.refetching = true;
351
+ model.triggerUpdate();
352
+ }
353
+ });
354
+ });
339
355
  },
340
356
 
341
357
  setResourceState,
@@ -397,7 +413,7 @@ function generateResources(getResources, props) {
397
413
  .reduce((memo, [name, config={}]) =>
398
414
  memo.concat([[name, {
399
415
  modelKey: config.modelKey || name,
400
- refetch: props.refetches?.includes(name),
416
+ refetch: !!getModelFromCache({...config, modelKey: config.modelKey || name})?.refetching,
401
417
  ...config
402
418
  }]].concat(
403
419
  // expand prefetched resources with their own options based on
@@ -898,6 +914,8 @@ function fetchResources(resources, props, {
898
914
  trackRequestTime(name, config);
899
915
  }
900
916
 
917
+ delete model.refetching;
918
+
901
919
  // add unfetched resources that a model might provide
902
920
  if (ModelMap[modelKey].providesModels) {
903
921
  ModelMap[modelKey].providesModels(model, ResourceKeys).forEach((uConfig) => {
@@ -929,6 +947,10 @@ function fetchResources(resources, props, {
929
947
 
930
948
  // error callback
931
949
  (status) => {
950
+ // if a refetching request errors, we still want to remove the refetching flag
951
+ // before going into an error state
952
+ delete getModelFromCache(config)?.refetching;
953
+
932
954
  // this catch block gets called _only_ for request errors.
933
955
  // don't set error state unless resource is current
934
956
  if (isCurrentResource([name, config], cacheKey)) {
package/lib/sync.js CHANGED
@@ -50,7 +50,24 @@ export default function(model, options={}) {
50
50
  */
51
51
  export function ajax(options) {
52
52
  var hasParams = !!Object.keys(options.params || {}).length,
53
- hasBodyContent = !/^(?:GET|HEAD)$/.test(options.method) && hasParams;
53
+ hasBodyContent = !/^(?:GET|HEAD)$/.test(options.method) && hasParams,
54
+ startTime = Date.now(),
55
+ onRequestComplete = (json, response) => {
56
+ var requestDuration = Date.now() - startTime,
57
+ routeRequest = (
58
+ resolve=Promise.resolve.bind(Promise),
59
+ reject=Promise.reject.bind(Promise)
60
+ ) => response.ok ?
61
+ resolve([json, response]) :
62
+ reject(Object.assign(response, {json}));
63
+
64
+ return !options.minDuration || requestDuration >= options.minDuration ?
65
+ routeRequest() :
66
+ new Promise((resolve, reject) => window.setTimeout(
67
+ () => routeRequest(resolve, reject),
68
+ options.minDuration - requestDuration
69
+ ));
70
+ };
54
71
 
55
72
  if (options.method === 'GET' && hasParams) {
56
73
  options.url += (options.url.indexOf('?') > -1 ? '&' : '?') +
@@ -80,7 +97,7 @@ export function ajax(options) {
80
97
  }).then(
81
98
  (res) => res.json()
82
99
  .catch(() => ({}))
83
- .then((json) => res.ok ? [json, res] : Promise.reject(Object.assign(res, {json})))
100
+ .then((json) => onRequestComplete(json, res))
84
101
  ).catch(options.error);
85
102
  }
86
103
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "resourcerer",
3
- "version": "1.2.2",
3
+ "version": "1.2.3",
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"],
package/test/sync.test.js CHANGED
@@ -227,6 +227,18 @@ describe('sync', () => {
227
227
  }
228
228
  });
229
229
 
230
+ it('waits minDuration to resolve if one is passed', async() => {
231
+ var resolved;
232
+
233
+ library.fetch({minDuration: 150}).then(() => resolved = true);
234
+ await new Promise((res) => window.setTimeout(res, 50));
235
+ expect(resolved).not.toBeDefined();
236
+ await new Promise((res) => window.setTimeout(res, 50));
237
+ expect(resolved).not.toBeDefined();
238
+ await new Promise((res) => window.setTimeout(res, 50));
239
+ expect(resolved).toBe(true);
240
+ });
241
+
230
242
  describe('headers', () => {
231
243
  it('can override contentType in options', async() => {
232
244
  setRequestPrefilter((options) => ({