@hyper-fetch/react 6.0.1 → 7.0.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.
Files changed (45) hide show
  1. package/.eslintrc.json +8 -3
  2. package/README.md +5 -5
  3. package/dist/index.d.ts +167 -166
  4. package/dist/{index.esm.js → index.js} +462 -431
  5. package/dist/index.js.map +7 -0
  6. package/package.json +12 -13
  7. package/src/helpers/use-request-events/use-request-events.hooks.ts +79 -80
  8. package/src/helpers/use-request-events/use-request-events.types.ts +24 -22
  9. package/src/helpers/use-socket-state/use-socket-state.constants.ts +4 -1
  10. package/src/helpers/use-socket-state/use-socket-state.hooks.ts +39 -29
  11. package/src/helpers/use-socket-state/use-socket-state.types.ts +4 -1
  12. package/src/helpers/use-tracked-state/use-tracked-state.constants.ts +4 -3
  13. package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +82 -115
  14. package/src/helpers/use-tracked-state/use-tracked-state.types.ts +42 -25
  15. package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +45 -41
  16. package/src/hooks/use-app-manager/use-app-manager.hooks.ts +2 -2
  17. package/src/hooks/use-cache/use-cache.constants.ts +1 -1
  18. package/src/hooks/use-cache/use-cache.hooks.ts +32 -27
  19. package/src/hooks/use-cache/use-cache.types.ts +4 -22
  20. package/src/hooks/use-emitter/use-emitter.hooks.ts +50 -18
  21. package/src/hooks/use-fetch/use-fetch.constants.ts +6 -5
  22. package/src/hooks/use-fetch/use-fetch.hooks.ts +71 -79
  23. package/src/hooks/use-fetch/use-fetch.types.ts +28 -9
  24. package/src/hooks/use-listener/use-listener.hooks.ts +15 -21
  25. package/src/hooks/use-queue/use-queue.constants.ts +2 -1
  26. package/src/hooks/use-queue/use-queue.hooks.ts +123 -42
  27. package/src/hooks/use-queue/use-queue.types.ts +14 -5
  28. package/src/hooks/use-submit/use-submit.constants.ts +3 -3
  29. package/src/hooks/use-submit/use-submit.hooks.ts +39 -53
  30. package/src/hooks/use-submit/use-submit.types.ts +5 -6
  31. package/src/index.ts +1 -3
  32. package/src/provider/index.ts +2 -0
  33. package/src/{config-provider/config-provider.tsx → provider/provider.tsx} +8 -5
  34. package/src/{config-provider/config-provider.types.ts → provider/provider.types.ts} +15 -8
  35. package/src/utils/deep-equal.utils.ts +1 -3
  36. package/tsconfig.json +2 -2
  37. package/dist/index.cjs.js +0 -1550
  38. package/dist/index.cjs.js.map +0 -7
  39. package/dist/index.esm.js.map +0 -7
  40. package/src/config-provider/index.ts +0 -2
  41. package/src/hooks/use-event-messages/index.ts +0 -2
  42. package/src/hooks/use-event-messages/use-event-messages.hooks.ts +0 -69
  43. package/src/hooks/use-event-messages/use-event-messages.types.ts +0 -4
  44. package/src/types/index.ts +0 -1
  45. package/src/types/invalidation.types.ts +0 -3
@@ -4,23 +4,23 @@ import {
4
4
  CacheValueType,
5
5
  ExtractResponseType,
6
6
  RequestInstance,
7
- LoggerType,
8
7
  ExtractAdapterType,
9
8
  ExtractAdapterStatusType,
10
9
  ExtractAdapterExtraType,
11
- ExtractAdapterReturnType,
10
+ ExtractAdapterResolvedType,
12
11
  NullableType,
12
+ CacheSetState,
13
+ LoggerMethods,
13
14
  } from "@hyper-fetch/core";
14
15
 
15
16
  import { isEqual } from "utils";
16
17
 
17
18
  export type UseTrackedStateProps<T extends RequestInstance> = {
18
19
  request: T;
19
- logger: LoggerType;
20
- initialData: NullableType<Partial<ExtractAdapterReturnType<T>>>;
21
- dispatcher: Dispatcher;
20
+ logger: LoggerMethods;
21
+ initialResponse: NullableType<Partial<ExtractAdapterResolvedType<T>>>;
22
+ dispatcher: Dispatcher<ExtractAdapterType<T>>;
22
23
  dependencyTracking: boolean;
23
- defaultCacheEmitting?: boolean;
24
24
  deepCompare: boolean | typeof isEqual;
25
25
  disabled?: boolean;
26
26
  revalidate?: boolean;
@@ -53,11 +53,11 @@ export type UseTrackedStateType<T extends RequestInstance = RequestInstance> = {
53
53
  /**
54
54
  * Request status
55
55
  */
56
- status: ExtractAdapterStatusType<ExtractAdapterType<T>>;
56
+ status: null | ExtractAdapterStatusType<ExtractAdapterType<T>> | null;
57
57
  /**
58
58
  * Request additional response data
59
59
  */
60
- extra: ExtractAdapterExtraType<ExtractAdapterType<T>>;
60
+ extra: null | ExtractAdapterExtraType<ExtractAdapterType<T>>;
61
61
  /**
62
62
  * Information whether request succeeded
63
63
  */
@@ -69,40 +69,57 @@ export type UseTrackedStateType<T extends RequestInstance = RequestInstance> = {
69
69
  /**
70
70
  * Request response timestamp
71
71
  */
72
- timestamp: null | Date;
72
+ responseTimestamp: null | Date;
73
+ /**
74
+ * Request response timestamp
75
+ */
76
+ requestTimestamp: null | Date;
73
77
  };
74
78
 
75
79
  export type UseTrackedStateActions<T extends RequestInstance> = {
76
80
  /**
77
- * Action to set custom data. We can do it locally(inside hook state) or in cache(all related sources) with 'emitToCache' option.
81
+ * Action to set custom data. We can do it locally(inside hook state).
82
+ * If you need to update cache data use client.cache.update(). method.
83
+ */
84
+ setData: (data: CacheSetState<ExtractResponseType<T> | null>) => void;
85
+ /**
86
+ * Action to set custom error. We can do it locally(inside hook state).
87
+ * If you need to update cache data use client.cache.update() method.
78
88
  */
79
- setData: (data: ExtractResponseType<T>, emitToCache?: boolean) => void;
89
+ setError: (error: CacheSetState<ExtractErrorType<T> | null>) => void;
80
90
  /**
81
- * Action to set custom error. We can do it locally(inside hook state) or in all hooks with 'emitToCache' option.
91
+ * Action to set custom loading. We can do it locally(inside hook state).
92
+ * If you need to update cache data use client.cache.update() method.
82
93
  */
83
- setError: (error: ExtractErrorType<T>, emitToCache?: boolean) => void;
94
+ setLoading: (loading: CacheSetState<boolean>) => void;
84
95
  /**
85
- * Action to set custom loading. We can do it locally(inside hook state) or in cache(all related sources) with 'emitToCache' option
96
+ * Action to set custom status. We can do it locally(inside hook state).
97
+ * If you need to turn on loading for all listening hooks use client.requestManager.events.emitLoading() method.
86
98
  */
87
- setLoading: (loading: boolean, emitToHooks?: boolean) => void;
99
+ setStatus: (status: CacheSetState<ExtractAdapterStatusType<ExtractAdapterType<T>>>) => void;
88
100
  /**
89
- * Action to set custom status. We can do it locally(inside hook state) or in cache(all related sources) with 'emitToCache' option
101
+ * Action to set custom success. We can do it locally(inside hook state).
102
+ * If you need to update cache data use client.cache.update() method.
90
103
  */
91
- setStatus: (status: ExtractAdapterStatusType<ExtractAdapterType<T>>, emitToCache?: boolean) => void;
104
+ setSuccess: (success: CacheSetState<boolean>) => void;
92
105
  /**
93
- * Action to set custom success. We can do it locally(inside hook state) or in cache(all related sources) with 'emitToCache' option
106
+ * Action to set custom additional data. We can do it locally(inside hook state).
107
+ * If you need to update cache data use client.cache.update() method.
94
108
  */
95
- setSuccess: (success: boolean, emitToCache?: boolean) => void;
109
+ setExtra: (extra: CacheSetState<ExtractAdapterExtraType<ExtractAdapterType<T>> | null>) => void;
96
110
  /**
97
- * Action to set custom additional data. We can do it locally(inside hook state) or in cache(all related sources) with 'emitToCache' option
111
+ * Action to set custom retries count. We can do it locally(inside hook state).
112
+ * If you need to update cache data use client.cache.update() method.
98
113
  */
99
- setExtra: (extra: ExtractAdapterExtraType<ExtractAdapterType<T>>, emitToCache?: boolean) => void;
114
+ setRetries: (retries: CacheSetState<number>) => void;
100
115
  /**
101
- * Action to set custom retries count. We can do it locally(inside hook state) or in cache(all related sources) with 'emitToCache' option
116
+ * Action to set custom timestamp. We can do it locally(inside hook state).
117
+ * If you need to update cache data use client.cache.update() method.
102
118
  */
103
- setRetries: (retries: number, emitToCache?: boolean) => void;
119
+ setResponseTimestamp: (timestamp: CacheSetState<Date>) => void;
104
120
  /**
105
- * Action to set custom timestamp. We can do it locally(inside hook state) or in cache(all related sources) with 'emitToCache' option
121
+ * Action to set custom timestamp. We can do it locally(inside hook state).
122
+ * If you need to update cache data use client.cache.update() method.
106
123
  */
107
- setTimestamp: (timestamp: Date, emitToCache?: boolean) => void;
124
+ setRequestTimestamp: (timestamp: CacheSetState<Date>) => void;
108
125
  };
@@ -1,14 +1,17 @@
1
+ /* eslint-disable @typescript-eslint/naming-convention */
1
2
  import {
2
3
  CacheValueType,
3
4
  NullableType,
4
5
  RequestInstance,
5
6
  ExtractResponseType,
6
7
  ExtractErrorType,
7
- ExtractAdapterReturnType,
8
+ ExtractAdapterResolvedType,
8
9
  Dispatcher,
9
10
  ExtractAdapterType,
10
11
  ExtractAdapterExtraType,
11
12
  ResponseDetailsType,
13
+ ExtractAdapterStatusType,
14
+ ResponseType,
12
15
  } from "@hyper-fetch/core";
13
16
 
14
17
  import { initialState, UseTrackedStateType } from "helpers";
@@ -19,41 +22,48 @@ export const getDetailsState = (
19
22
  ): ResponseDetailsType => {
20
23
  return {
21
24
  retries: state?.retries || 0,
22
- timestamp: +new Date(),
23
25
  isCanceled: false,
24
26
  isOffline: false,
27
+ addedTimestamp: +new Date(),
28
+ triggerTimestamp: +new Date(),
29
+ requestTimestamp: +new Date(),
30
+ responseTimestamp: +new Date(),
25
31
  ...details,
26
32
  };
27
33
  };
28
34
 
29
- export const isStaleCacheData = (cacheTime: number, cacheTimestamp: NullableType<Date | number>) => {
30
- if (!cacheTimestamp) return true;
31
- return +new Date() > +cacheTimestamp + cacheTime;
35
+ export const isStaleCacheData = (staleTime: number, staleTimestamp: NullableType<Date | number>) => {
36
+ if (!staleTimestamp) return true;
37
+ return +new Date() > +staleTimestamp + staleTime;
32
38
  };
33
39
 
34
40
  export const getValidCacheData = <T extends RequestInstance>(
35
41
  request: T,
36
- initialData: NullableType<Partial<ExtractAdapterReturnType<T>>>,
37
- cacheData: NullableType<CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>>>,
38
- ): CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>> | null => {
39
- const isStale = isStaleCacheData(request.cacheTime, cacheData?.timestamp);
42
+ initialResponse: NullableType<Partial<ExtractAdapterResolvedType<T>>>,
43
+ cacheData: NullableType<CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>>,
44
+ ): CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>> | null => {
45
+ const isStale = isStaleCacheData(request.staleTime, cacheData?.responseTimestamp);
40
46
 
41
47
  if (!isStale && cacheData) {
42
48
  return cacheData;
43
49
  }
44
50
 
45
- if (initialData) {
51
+ if (initialResponse) {
46
52
  return {
47
53
  data: null,
48
54
  error: null,
49
55
  status: null,
50
- success: null,
56
+ success: true,
51
57
  extra: null,
52
- ...((initialData || {}) as Partial<ExtractAdapterReturnType<T>>),
58
+ cached: !!request.cache,
59
+ ...(initialResponse as Partial<ExtractAdapterResolvedType<T>>),
53
60
  ...getDetailsState(),
54
- cacheTime: 1000,
55
- clearKey: request.client.cache.clearKey,
56
- garbageCollection: request.garbageCollection,
61
+ staleTime: 1000,
62
+ version: request.client.cache.version,
63
+ cacheKey: request.cacheKey,
64
+ cacheTime: request.cacheTime,
65
+ requestTimestamp: initialResponse?.requestTimestamp ?? +new Date(),
66
+ responseTimestamp: initialResponse?.responseTimestamp ?? +new Date(),
57
67
  };
58
68
  }
59
69
 
@@ -64,7 +74,7 @@ export const getTimestamp = (timestamp?: NullableType<number | Date>) => {
64
74
  return timestamp ? new Date(timestamp) : null;
65
75
  };
66
76
 
67
- export const getIsInitiallyLoading = ({
77
+ export const getIsInitiallyLoading = <T extends RequestInstance>({
68
78
  queryKey,
69
79
  dispatcher,
70
80
  hasState,
@@ -72,7 +82,7 @@ export const getIsInitiallyLoading = ({
72
82
  disabled,
73
83
  }: {
74
84
  queryKey: string;
75
- dispatcher: Dispatcher;
85
+ dispatcher: Dispatcher<ExtractAdapterType<T>>;
76
86
  hasState: boolean;
77
87
  revalidate?: boolean;
78
88
  disabled?: boolean;
@@ -94,30 +104,20 @@ export const getInitialState = <T extends RequestInstance>({
94
104
  disabled,
95
105
  revalidate,
96
106
  }: {
97
- initialResponse: NullableType<Partial<ExtractAdapterReturnType<T>>>;
98
- dispatcher: Dispatcher;
107
+ initialResponse: NullableType<Partial<ExtractAdapterResolvedType<T>>>;
108
+ dispatcher: Dispatcher<ExtractAdapterType<T>>;
99
109
  request: T;
100
- /**
101
- * useFetch only
102
- */
103
- disabled?: boolean;
104
- /**
105
- * useFetch only
106
- */
107
- revalidate?: boolean;
110
+ disabled?: boolean; // useFetch only
111
+ revalidate?: boolean; // useFetch only
108
112
  }): UseTrackedStateType<T> => {
109
- const { client, cacheKey, responseMapper } = request;
113
+ const { client, cacheKey, unstable_responseMapper } = request;
110
114
  const { cache } = client;
111
115
 
112
- const cacheData = cache.get<
113
- ExtractResponseType<T>,
114
- ExtractErrorType<T>,
115
- ExtractAdapterExtraType<ExtractAdapterType<T>>
116
- >(cacheKey);
116
+ const cacheData = cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(cacheKey);
117
117
  const cacheState = getValidCacheData<T>(request, initialResponse, cacheData);
118
118
 
119
119
  const initialLoading = getIsInitiallyLoading({
120
- queryKey: request.queueKey,
120
+ queryKey: request.queryKey,
121
121
  dispatcher,
122
122
  disabled,
123
123
  revalidate,
@@ -125,7 +125,9 @@ export const getInitialState = <T extends RequestInstance>({
125
125
  });
126
126
 
127
127
  if (cacheState) {
128
- const mappedData = responseMapper ? responseMapper(cacheState) : cacheState;
128
+ const mappedData = unstable_responseMapper
129
+ ? unstable_responseMapper(cacheState as ResponseType<any, any, ExtractAdapterType<T>>)
130
+ : cacheState;
129
131
  if (mappedData instanceof Promise) {
130
132
  // For the async mapper we cannot return async values
131
133
  // So we have return the initial state instead
@@ -134,11 +136,12 @@ export const getInitialState = <T extends RequestInstance>({
134
136
  return {
135
137
  data: mappedData.data,
136
138
  error: mappedData.error,
137
- status: mappedData.status,
139
+ status: mappedData.status as ExtractAdapterStatusType<ExtractAdapterType<T>>,
138
140
  success: mappedData.success,
139
- extra: mappedData.extra,
141
+ extra: (mappedData.extra || client.adapter.defaultExtra) as ExtractAdapterExtraType<ExtractAdapterType<T>>,
140
142
  retries: cacheState.retries,
141
- timestamp: getTimestamp(cacheState.timestamp),
143
+ requestTimestamp: getTimestamp(cacheState.requestTimestamp),
144
+ responseTimestamp: getTimestamp(cacheState.responseTimestamp),
142
145
  loading: initialLoading,
143
146
  };
144
147
  }
@@ -146,11 +149,12 @@ export const getInitialState = <T extends RequestInstance>({
146
149
  return {
147
150
  data: initialState.data,
148
151
  error: initialState.error,
149
- status: initialState.status,
152
+ status: initialState.status as ExtractAdapterStatusType<ExtractAdapterType<T>>,
150
153
  success: initialState.success,
151
- extra: request.client.defaultExtra,
154
+ extra: request.client.adapter.defaultExtra as ExtractAdapterExtraType<ExtractAdapterType<T>>,
152
155
  retries: initialState.retries,
153
- timestamp: getTimestamp(initialState.timestamp),
156
+ requestTimestamp: getTimestamp(initialState.requestTimestamp),
157
+ responseTimestamp: getTimestamp(initialState.responseTimestamp),
154
158
  loading: initialLoading,
155
159
  };
156
160
  };
@@ -1,10 +1,10 @@
1
- import { useState } from "react";
2
1
  import { useDidMount } from "@better-hooks/lifecycle";
3
2
  import { ClientInstance } from "@hyper-fetch/core";
3
+ import { useState } from "react";
4
4
 
5
5
  import { UseAppManagerReturnType } from "hooks/use-app-manager";
6
6
 
7
- export const useAppManager = <B extends ClientInstance>(client: B): UseAppManagerReturnType => {
7
+ export const useAppManager = <Client extends ClientInstance>(client: Client): UseAppManagerReturnType => {
8
8
  const [online, setIsOnline] = useState(client.appManager.isOnline);
9
9
  const [focused, setIsFocused] = useState(client.appManager.isFocused);
10
10
 
@@ -1,5 +1,5 @@
1
1
  export const useCacheDefaultOptions = {
2
2
  dependencyTracking: true,
3
- initialData: null,
3
+ initialResponse: null,
4
4
  deepCompare: true,
5
5
  };
@@ -1,25 +1,25 @@
1
- import { useRef } from "react";
2
1
  import { useDidUpdate } from "@better-hooks/lifecycle";
3
- import { getRequestDispatcher, RequestInstance, Request, getRequestKey } from "@hyper-fetch/core";
2
+ import { getRequestDispatcher, RequestInstance } from "@hyper-fetch/core";
3
+ import { useRef } from "react";
4
4
 
5
5
  import { UseCacheOptionsType, useCacheDefaultOptions, UseCacheReturnType } from "hooks/use-cache";
6
6
  import { useRequestEvents, useTrackedState } from "helpers";
7
- import { useConfigProvider } from "config-provider";
7
+ import { useProvider } from "provider";
8
8
 
9
9
  export const useCache = <T extends RequestInstance>(
10
10
  request: T,
11
- options: UseCacheOptionsType<T> = useCacheDefaultOptions,
11
+ options?: UseCacheOptionsType<T>,
12
12
  ): UseCacheReturnType<T> => {
13
13
  const { cacheKey, client } = request;
14
14
 
15
15
  const { cache, loggerManager } = client;
16
- const logger = useRef(loggerManager.init("useCache")).current;
16
+ const logger = useRef(loggerManager.initialize(client, "useCache")).current;
17
17
  const [dispatcher] = getRequestDispatcher(request);
18
18
  const updateKey = JSON.stringify(request.toJSON());
19
19
 
20
20
  // Build the configuration options
21
- const [globalConfig] = useConfigProvider();
22
- const { dependencyTracking, initialData, deepCompare } = {
21
+ const { config: globalConfig } = useProvider();
22
+ const { dependencyTracking, initialResponse, deepCompare } = {
23
23
  ...useCacheDefaultOptions,
24
24
  ...globalConfig.useCacheConfig,
25
25
  ...options,
@@ -32,7 +32,7 @@ export const useCache = <T extends RequestInstance>(
32
32
  logger,
33
33
  request,
34
34
  dispatcher,
35
- initialData,
35
+ initialResponse,
36
36
  deepCompare,
37
37
  dependencyTracking,
38
38
  });
@@ -40,7 +40,7 @@ export const useCache = <T extends RequestInstance>(
40
40
  /**
41
41
  * Handles the data exchange with the core logic - responses, loading, downloading etc
42
42
  */
43
- const [callbacks, listeners] = useRequestEvents({
43
+ const [, listeners] = useRequestEvents({
44
44
  logger,
45
45
  actions,
46
46
  request,
@@ -52,20 +52,24 @@ export const useCache = <T extends RequestInstance>(
52
52
  const { addCacheDataListener, addLifecycleListeners } = listeners;
53
53
 
54
54
  const handleMountEvents = () => {
55
- addCacheDataListener(request);
56
- addLifecycleListeners(request);
55
+ const unmountDataListener = addCacheDataListener(request);
56
+ const unmountLifecycleListener = addLifecycleListeners(request);
57
+ return () => {
58
+ unmountDataListener();
59
+ unmountLifecycleListener();
60
+ };
57
61
  };
58
62
 
59
- useDidUpdate(handleMountEvents, [updateKey], true);
63
+ useDidUpdate(
64
+ () => {
65
+ return handleMountEvents();
66
+ },
67
+ [updateKey],
68
+ true,
69
+ );
60
70
 
61
- const refetch = (invalidateKey?: string | RequestInstance | RegExp) => {
62
- if (invalidateKey instanceof Request) {
63
- cache.invalidate(getRequestKey(invalidateKey, true));
64
- } else if (invalidateKey) {
65
- cache.invalidate(invalidateKey);
66
- } else {
67
- cache.invalidate(cacheKey);
68
- }
71
+ const invalidate = (cacheKeys?: string | RegExp | RequestInstance | Array<string | RegExp | RequestInstance>) => {
72
+ cache.invalidate(cacheKeys ?? cacheKey);
69
73
  };
70
74
 
71
75
  return {
@@ -97,14 +101,15 @@ export const useCache = <T extends RequestInstance>(
97
101
  setRenderKey("retries");
98
102
  return state.retries;
99
103
  },
100
- get timestamp() {
101
- setRenderKey("timestamp");
102
- return state.timestamp;
104
+ get responseTimestamp() {
105
+ setRenderKey("responseTimestamp");
106
+ return state.responseTimestamp;
107
+ },
108
+ get requestTimestamp() {
109
+ setRenderKey("requestTimestamp");
110
+ return state.requestTimestamp;
103
111
  },
104
- onCacheError: callbacks.onError,
105
- onCacheSuccess: callbacks.onSuccess,
106
- onCacheChange: callbacks.onFinished,
107
112
  ...actions,
108
- refetch,
113
+ invalidate,
109
114
  };
110
115
  };
@@ -1,13 +1,7 @@
1
1
  import { RequestInstance, ExtractResponseType, ExtractErrorType, CacheValueType } from "@hyper-fetch/core";
2
2
 
3
3
  import { isEqual } from "utils";
4
- import {
5
- OnErrorCallbackType,
6
- OnFinishedCallbackType,
7
- OnSuccessCallbackType,
8
- UseTrackedStateActions,
9
- UseTrackedStateType,
10
- } from "helpers";
4
+ import { UseTrackedStateActions, UseTrackedStateType } from "helpers";
11
5
 
12
6
  export type UseCacheOptionsType<T extends RequestInstance> = {
13
7
  /**
@@ -17,7 +11,7 @@ export type UseCacheOptionsType<T extends RequestInstance> = {
17
11
  /**
18
12
  * If cache is empty we can use placeholder data.
19
13
  */
20
- initialData?: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>>["data"] | null;
14
+ initialResponse?: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>>["data"] | null;
21
15
  /**
22
16
  * Deep comparison function for hook to check for equality in incoming data, to limit rerenders.
23
17
  */
@@ -27,19 +21,7 @@ export type UseCacheOptionsType<T extends RequestInstance> = {
27
21
  export type UseCacheReturnType<T extends RequestInstance> = UseTrackedStateType<T> &
28
22
  UseTrackedStateActions<T> & {
29
23
  /**
30
- * Helper hook listener for success response
24
+ * Invalidate cache for the current request or pass custom key to trigger it by invalidationKey(Regex / cacheKey).
31
25
  */
32
- onCacheSuccess: (callback: OnSuccessCallbackType<T>) => void;
33
- /**
34
- * Helper hook listener for error response
35
- */
36
- onCacheError: (callback: OnErrorCallbackType<T>) => void;
37
- /**
38
- * Helper hook listener for response
39
- */
40
- onCacheChange: (callback: OnFinishedCallbackType<T>) => void;
41
- /**
42
- * Refetch current request resource or pass custom key to trigger it by invalidationKey(Regex / cacheKey).
43
- */
44
- refetch: (invalidateKey?: string | RegExp | RequestInstance) => void;
26
+ invalidate: (cacheKeys?: string | RegExp | RequestInstance | Array<string | RegExp | RequestInstance>) => void;
45
27
  };
@@ -1,30 +1,66 @@
1
+ import { EmitterInstance, EmitterCallbackErrorType, EmitType } from "@hyper-fetch/sockets";
2
+ import { useDidUpdate } from "@better-hooks/lifecycle";
1
3
  import { useRef } from "react";
2
- import { EmitterInstance } from "@hyper-fetch/sockets";
3
4
 
4
5
  import { UseEmitterOptionsType } from "hooks/use-emitter";
5
6
  import { useSocketState } from "helpers";
6
- import { useConfigProvider } from "config-provider";
7
+ import { useProvider } from "provider";
7
8
 
8
9
  export const useEmitter = <EmitterType extends EmitterInstance>(
9
10
  emitter: EmitterType,
10
- options: UseEmitterOptionsType,
11
+ options?: UseEmitterOptionsType,
11
12
  ) => {
12
- const [globalConfig] = useConfigProvider();
13
+ const { config: globalConfig } = useProvider();
13
14
  const { dependencyTracking } = { ...globalConfig.useEmitter, ...options };
14
15
 
15
- const onEventCallback = useRef<null | ((emitter: EmitterType) => void)>(null);
16
16
  const [state, actions, callbacks, { setRenderKey }] = useSocketState(emitter.socket, { dependencyTracking });
17
17
 
18
- const additionalCallbacks = {
19
- onEvent: (callback: (emitter: EmitterType) => void) => {
20
- onEventCallback.current = callback;
18
+ /**
19
+ * Callbacks
20
+ */
21
+ const onEventStartCallback = useRef<null | ((emitter: EmitterType) => void)>(null);
22
+ const onEventErrorCallback = useRef<null | EmitterCallbackErrorType>(null);
23
+
24
+ useDidUpdate(
25
+ () => {
26
+ const onEventStart = () => {
27
+ return emitter.socket.events.onEmitterStartEventByTopic(emitter, () => {
28
+ onEventStartCallback.current?.(emitter);
29
+ });
30
+ };
31
+
32
+ const onEventError = () => {
33
+ return emitter.socket.events.onEmitterErrorByTopic(emitter, ({ error }) => {
34
+ onEventErrorCallback.current?.({ error });
35
+ });
36
+ };
37
+
38
+ const unmountEventStart = onEventStart();
39
+ const unmountEventError = onEventError();
40
+
41
+ return () => {
42
+ unmountEventStart();
43
+ unmountEventError();
44
+ };
21
45
  },
46
+ [emitter.topic, onEventStartCallback.current, onEventErrorCallback.current],
47
+ true,
48
+ );
49
+
50
+ /**
51
+ * Emitter
52
+ */
53
+
54
+ const emit: EmitType<EmitterType> = (emitOptions: Parameters<EmitType<EmitterType>>[0]) => {
55
+ return emitter.emit(emitOptions as any);
56
+ };
57
+
58
+ const onEmit = (callback: (emitter: EmitterType) => void) => {
59
+ onEventStartCallback.current = callback;
22
60
  };
23
61
 
24
- const emit: typeof emitter.emit = (emitOptions) => {
25
- actions.setTimestamp(+new Date());
26
- onEventCallback.current?.(emitter);
27
- return emitter.emit(emitOptions);
62
+ const onEmitError = (callback: EmitterCallbackErrorType) => {
63
+ onEventErrorCallback.current = callback;
28
64
  };
29
65
 
30
66
  return {
@@ -36,14 +72,10 @@ export const useEmitter = <EmitterType extends EmitterInstance>(
36
72
  setRenderKey("connecting");
37
73
  return state.connecting;
38
74
  },
39
- get timestamp() {
40
- setRenderKey("timestamp");
41
- return state.timestamp;
42
- },
43
75
  ...actions,
44
76
  ...callbacks,
45
- ...additionalCallbacks,
77
+ onEmit,
78
+ onEmitError,
46
79
  emit,
47
- reconnect: emitter.socket.reconnect,
48
80
  };
49
81
  };
@@ -1,9 +1,9 @@
1
- import { DateInterval, RequestInstance, RequiredKeys } from "@hyper-fetch/core";
1
+ import { Time, RequestInstance, RequiredKeys } from "@hyper-fetch/core";
2
2
 
3
3
  import { UseFetchOptionsType } from "hooks/use-fetch";
4
4
 
5
- type DefaultOptionsType = RequiredKeys<Omit<UseFetchOptionsType<RequestInstance>, "initialData">> & {
6
- initialData: null;
5
+ type DefaultOptionsType = RequiredKeys<Omit<UseFetchOptionsType<RequestInstance>, "initialResponse">> & {
6
+ initialResponse: null;
7
7
  };
8
8
 
9
9
  export const useFetchDefaultOptions: DefaultOptionsType = {
@@ -11,9 +11,9 @@ export const useFetchDefaultOptions: DefaultOptionsType = {
11
11
  disabled: false,
12
12
  dependencyTracking: true,
13
13
  revalidate: true,
14
- initialData: null,
14
+ initialResponse: null,
15
15
  refresh: false,
16
- refreshTime: DateInterval.hour,
16
+ refreshTime: Time.HOUR,
17
17
  refetchBlurred: true,
18
18
  refetchOnBlur: false,
19
19
  refetchOnFocus: false,
@@ -21,5 +21,6 @@ export const useFetchDefaultOptions: DefaultOptionsType = {
21
21
  bounce: false,
22
22
  bounceType: "debounce",
23
23
  bounceTime: 400,
24
+ bounceTimeout: 400,
24
25
  deepCompare: true,
25
26
  };