@umituz/react-native-storage 1.5.0 → 2.3.2
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 +0 -0
- package/package.json +28 -10
- package/src/__tests__/integration.test.ts +391 -0
- package/src/__tests__/mocks/asyncStorage.mock.ts +52 -0
- package/src/__tests__/performance.test.ts +351 -0
- package/src/__tests__/setup.ts +63 -0
- package/src/application/ports/IStorageRepository.ts +0 -12
- package/src/domain/constants/CacheDefaults.ts +64 -0
- package/src/domain/entities/CachedValue.ts +86 -0
- package/src/domain/entities/StorageResult.ts +1 -3
- package/src/domain/entities/__tests__/CachedValue.test.ts +149 -0
- package/src/domain/entities/__tests__/StorageResult.test.ts +122 -0
- package/src/domain/errors/StorageError.ts +0 -2
- package/src/domain/errors/__tests__/StorageError.test.ts +127 -0
- package/src/domain/factories/StoreFactory.ts +33 -0
- package/src/domain/types/Store.ts +18 -0
- package/src/domain/utils/CacheKeyGenerator.ts +66 -0
- package/src/domain/utils/__tests__/devUtils.test.ts +97 -0
- package/src/domain/utils/devUtils.ts +37 -0
- package/src/domain/value-objects/StorageKey.ts +27 -29
- package/src/index.ts +59 -1
- package/src/infrastructure/adapters/StorageService.ts +8 -6
- package/src/infrastructure/repositories/AsyncStorageRepository.ts +27 -108
- package/src/infrastructure/repositories/BaseStorageOperations.ts +101 -0
- package/src/infrastructure/repositories/BatchStorageOperations.ts +42 -0
- package/src/infrastructure/repositories/StringStorageOperations.ts +44 -0
- package/src/infrastructure/repositories/__tests__/AsyncStorageRepository.test.ts +169 -0
- package/src/infrastructure/repositories/__tests__/BaseStorageOperations.test.ts +200 -0
- package/src/presentation/hooks/CacheStorageOperations.ts +95 -0
- package/src/presentation/hooks/__tests__/usePersistentCache.test.ts +404 -0
- package/src/presentation/hooks/__tests__/useStorage.test.ts +246 -0
- package/src/presentation/hooks/__tests__/useStorageState.test.ts +292 -0
- package/src/presentation/hooks/useCacheState.ts +55 -0
- package/src/presentation/hooks/usePersistentCache.ts +154 -0
- package/src/presentation/hooks/useStorage.ts +4 -3
- package/src/presentation/hooks/useStorageState.ts +24 -8
- package/src/presentation/hooks/useStore.ts +15 -0
- package/src/types/global.d.ts +40 -0
- package/LICENSE +0 -22
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* useStorageState Hook Tests
|
|
3
|
+
*
|
|
4
|
+
* Unit tests for useStorageState hook
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { renderHook, act } from '@testing-library/react-hooks';
|
|
8
|
+
import { useStorageState } from '../useStorageState';
|
|
9
|
+
import { AsyncStorage } from '../../__tests__/mocks/asyncStorage.mock';
|
|
10
|
+
|
|
11
|
+
describe('useStorageState Hook', () => {
|
|
12
|
+
beforeEach(() => {
|
|
13
|
+
(AsyncStorage as any).__clear();
|
|
14
|
+
jest.clearAllMocks();
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
describe('Initial Load', () => {
|
|
18
|
+
it('should load initial value from storage', async () => {
|
|
19
|
+
const key = 'test-key';
|
|
20
|
+
const defaultValue = 'default';
|
|
21
|
+
const storedValue = 'stored-value';
|
|
22
|
+
|
|
23
|
+
await AsyncStorage.setItem(key, JSON.stringify(storedValue));
|
|
24
|
+
|
|
25
|
+
const { result, waitForNextUpdate } = renderHook(() =>
|
|
26
|
+
useStorageState(key, defaultValue)
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
// Initial state
|
|
30
|
+
expect(result.current[0]).toBe(defaultValue);
|
|
31
|
+
expect(result.current[2]).toBe(true); // isLoading
|
|
32
|
+
|
|
33
|
+
// Wait for load
|
|
34
|
+
await act(async () => {
|
|
35
|
+
await waitForNextUpdate();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
expect(result.current[0]).toBe(storedValue);
|
|
39
|
+
expect(result.current[2]).toBe(false); // isLoading
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('should use default value for missing key', async () => {
|
|
43
|
+
const key = 'missing-key';
|
|
44
|
+
const defaultValue = 'default';
|
|
45
|
+
|
|
46
|
+
const { result, waitForNextUpdate } = renderHook(() =>
|
|
47
|
+
useStorageState(key, defaultValue)
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
await act(async () => {
|
|
51
|
+
await waitForNextUpdate();
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
expect(result.current[0]).toBe(defaultValue);
|
|
55
|
+
expect(result.current[2]).toBe(false);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('should handle StorageKey enum', async () => {
|
|
59
|
+
const key = '@ui_preferences';
|
|
60
|
+
const defaultValue = 'default';
|
|
61
|
+
const storedValue = 'stored-value';
|
|
62
|
+
|
|
63
|
+
await AsyncStorage.setItem(key, JSON.stringify(storedValue));
|
|
64
|
+
|
|
65
|
+
const { result, waitForNextUpdate } = renderHook(() =>
|
|
66
|
+
useStorageState(key as any, defaultValue)
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
await act(async () => {
|
|
70
|
+
await waitForNextUpdate();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
expect(result.current[0]).toBe(storedValue);
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
describe('Update State', () => {
|
|
78
|
+
it('should update state and persist to storage', async () => {
|
|
79
|
+
const key = 'test-key';
|
|
80
|
+
const defaultValue = 'default';
|
|
81
|
+
const newValue = 'new-value';
|
|
82
|
+
|
|
83
|
+
const { result, waitForNextUpdate } = renderHook(() =>
|
|
84
|
+
useStorageState(key, defaultValue)
|
|
85
|
+
);
|
|
86
|
+
|
|
87
|
+
await act(async () => {
|
|
88
|
+
await waitForNextUpdate();
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
// Update state
|
|
92
|
+
await act(async () => {
|
|
93
|
+
await result.current[1](newValue);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
expect(result.current[0]).toBe(newValue);
|
|
97
|
+
|
|
98
|
+
// Verify storage
|
|
99
|
+
const stored = await AsyncStorage.getItem(key);
|
|
100
|
+
expect(JSON.parse(stored!)).toBe(newValue);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it('should handle update during loading', async () => {
|
|
104
|
+
const key = 'test-key';
|
|
105
|
+
const defaultValue = 'default';
|
|
106
|
+
const newValue = 'new-value';
|
|
107
|
+
|
|
108
|
+
// Mock slow storage
|
|
109
|
+
let resolveStorage: (value: string) => void;
|
|
110
|
+
(AsyncStorage.getItem as jest.Mock).mockImplementation(() =>
|
|
111
|
+
new Promise(resolve => {
|
|
112
|
+
resolveStorage = resolve;
|
|
113
|
+
})
|
|
114
|
+
);
|
|
115
|
+
|
|
116
|
+
const { result } = renderHook(() =>
|
|
117
|
+
useStorageState(key, defaultValue)
|
|
118
|
+
);
|
|
119
|
+
|
|
120
|
+
// Update while loading
|
|
121
|
+
await act(async () => {
|
|
122
|
+
await result.current[1](newValue);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
expect(result.current[0]).toBe(newValue);
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
describe('Memory Leak Prevention', () => {
|
|
130
|
+
it('should cleanup on unmount', async () => {
|
|
131
|
+
const key = 'test-key';
|
|
132
|
+
const defaultValue = 'default';
|
|
133
|
+
|
|
134
|
+
// Mock slow storage
|
|
135
|
+
let resolveStorage: (value: string) => void;
|
|
136
|
+
(AsyncStorage.getItem as jest.Mock).mockImplementation(() =>
|
|
137
|
+
new Promise(resolve => {
|
|
138
|
+
resolveStorage = resolve;
|
|
139
|
+
})
|
|
140
|
+
);
|
|
141
|
+
|
|
142
|
+
const { result, unmount } = renderHook(() =>
|
|
143
|
+
useStorageState(key, defaultValue)
|
|
144
|
+
);
|
|
145
|
+
|
|
146
|
+
// Unmount before load completes
|
|
147
|
+
unmount();
|
|
148
|
+
|
|
149
|
+
// Resolve storage after unmount
|
|
150
|
+
await act(async () => {
|
|
151
|
+
resolveStorage!('stored-value');
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
// State should not be updated after unmount
|
|
155
|
+
expect(result.current[0]).toBe(defaultValue);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it('should handle unmount during update', async () => {
|
|
159
|
+
const key = 'test-key';
|
|
160
|
+
const defaultValue = 'default';
|
|
161
|
+
const newValue = 'new-value';
|
|
162
|
+
|
|
163
|
+
// Mock slow storage
|
|
164
|
+
let resolveStorage: () => void;
|
|
165
|
+
(AsyncStorage.setItem as jest.Mock).mockImplementation(() =>
|
|
166
|
+
new Promise(resolve => {
|
|
167
|
+
resolveStorage = resolve;
|
|
168
|
+
})
|
|
169
|
+
);
|
|
170
|
+
|
|
171
|
+
const { result, unmount } = renderHook(() =>
|
|
172
|
+
useStorageState(key, defaultValue)
|
|
173
|
+
);
|
|
174
|
+
|
|
175
|
+
// Start update
|
|
176
|
+
const updatePromise = act(async () => {
|
|
177
|
+
await result.current[1](newValue);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
// Unmount before update completes
|
|
181
|
+
unmount();
|
|
182
|
+
|
|
183
|
+
// Complete update
|
|
184
|
+
await act(async () => {
|
|
185
|
+
resolveStorage!();
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
await updatePromise;
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
describe('Performance', () => {
|
|
193
|
+
it('should not re-run effect when defaultValue changes', async () => {
|
|
194
|
+
const key = 'test-key';
|
|
195
|
+
const defaultValue1 = 'default1';
|
|
196
|
+
const defaultValue2 = 'default2';
|
|
197
|
+
|
|
198
|
+
await AsyncStorage.setItem(key, JSON.stringify('stored-value'));
|
|
199
|
+
|
|
200
|
+
const { result, rerender, waitForNextUpdate } = renderHook(
|
|
201
|
+
({ defaultValue }) => useStorageState(key, defaultValue),
|
|
202
|
+
{ initialProps: { defaultValue: defaultValue1 } }
|
|
203
|
+
);
|
|
204
|
+
|
|
205
|
+
await act(async () => {
|
|
206
|
+
await waitForNextUpdate();
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
const getItemCalls = (AsyncStorage.getItem as jest.Mock).mock.calls.length;
|
|
210
|
+
|
|
211
|
+
// Rerender with different default value
|
|
212
|
+
rerender({ defaultValue: defaultValue2 });
|
|
213
|
+
|
|
214
|
+
// Should not trigger another storage read
|
|
215
|
+
expect((AsyncStorage.getItem as jest.Mock).mock.calls.length).toBe(getItemCalls);
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
it('should re-run effect when key changes', async () => {
|
|
219
|
+
const key1 = 'key1';
|
|
220
|
+
const key2 = 'key2';
|
|
221
|
+
const defaultValue = 'default';
|
|
222
|
+
|
|
223
|
+
await AsyncStorage.setItem(key1, JSON.stringify('value1'));
|
|
224
|
+
await AsyncStorage.setItem(key2, JSON.stringify('value2'));
|
|
225
|
+
|
|
226
|
+
const { result, rerender, waitForNextUpdate } = renderHook(
|
|
227
|
+
({ key }) => useStorageState(key, defaultValue),
|
|
228
|
+
{ initialProps: { key: key1 } }
|
|
229
|
+
);
|
|
230
|
+
|
|
231
|
+
await act(async () => {
|
|
232
|
+
await waitForNextUpdate();
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
expect(result.current[0]).toBe('value1');
|
|
236
|
+
|
|
237
|
+
// Change key
|
|
238
|
+
rerender({ key: key2 });
|
|
239
|
+
|
|
240
|
+
await act(async () => {
|
|
241
|
+
await waitForNextUpdate();
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
expect(result.current[0]).toBe('value2');
|
|
245
|
+
});
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
describe('Error Handling', () => {
|
|
249
|
+
it('should handle storage read error', async () => {
|
|
250
|
+
const key = 'test-key';
|
|
251
|
+
const defaultValue = 'default';
|
|
252
|
+
|
|
253
|
+
// Mock storage error
|
|
254
|
+
(AsyncStorage.getItem as jest.Mock).mockRejectedValue(new Error('Storage error'));
|
|
255
|
+
|
|
256
|
+
const { result, waitForNextUpdate } = renderHook(() =>
|
|
257
|
+
useStorageState(key, defaultValue)
|
|
258
|
+
);
|
|
259
|
+
|
|
260
|
+
await act(async () => {
|
|
261
|
+
await waitForNextUpdate();
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
expect(result.current[0]).toBe(defaultValue);
|
|
265
|
+
expect(result.current[2]).toBe(false); // isLoading should be false
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
it('should handle storage write error', async () => {
|
|
269
|
+
const key = 'test-key';
|
|
270
|
+
const defaultValue = 'default';
|
|
271
|
+
const newValue = 'new-value';
|
|
272
|
+
|
|
273
|
+
// Mock storage error
|
|
274
|
+
(AsyncStorage.setItem as jest.Mock).mockRejectedValue(new Error('Storage error'));
|
|
275
|
+
|
|
276
|
+
const { result, waitForNextUpdate } = renderHook(() =>
|
|
277
|
+
useStorageState(key, defaultValue)
|
|
278
|
+
);
|
|
279
|
+
|
|
280
|
+
await act(async () => {
|
|
281
|
+
await waitForNextUpdate();
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
// State should still update even if storage fails
|
|
285
|
+
await act(async () => {
|
|
286
|
+
await result.current[1](newValue);
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
expect(result.current[0]).toBe(newValue);
|
|
290
|
+
});
|
|
291
|
+
});
|
|
292
|
+
});
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cache State Manager
|
|
3
|
+
*
|
|
4
|
+
* Manages cache state following Single Responsibility Principle
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { useState, useCallback, useMemo } from 'react';
|
|
8
|
+
import type { CachedValue } from '../../domain/entities/CachedValue';
|
|
9
|
+
import { createCachedValue, isCacheExpired } from '../../domain/entities/CachedValue';
|
|
10
|
+
|
|
11
|
+
export interface CacheState<T> {
|
|
12
|
+
data: T | null;
|
|
13
|
+
isLoading: boolean;
|
|
14
|
+
isExpired: boolean;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface CacheActions<T> {
|
|
18
|
+
setData: (value: T) => void;
|
|
19
|
+
clearData: () => void;
|
|
20
|
+
setLoading: (loading: boolean) => void;
|
|
21
|
+
setExpired: (expired: boolean) => void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Hook for managing cache state
|
|
26
|
+
*/
|
|
27
|
+
export function useCacheState<T>(): [CacheState<T>, CacheActions<T>] {
|
|
28
|
+
const [data, setDataState] = useState<T | null>(null);
|
|
29
|
+
const [isLoading, setIsLoading] = useState(true);
|
|
30
|
+
const [isExpired, setIsExpired] = useState(false);
|
|
31
|
+
|
|
32
|
+
const setData = useCallback((value: T) => {
|
|
33
|
+
setDataState(value);
|
|
34
|
+
setIsExpired(false);
|
|
35
|
+
}, []);
|
|
36
|
+
|
|
37
|
+
const clearData = useCallback(() => {
|
|
38
|
+
setDataState(null);
|
|
39
|
+
setIsExpired(true);
|
|
40
|
+
}, []);
|
|
41
|
+
|
|
42
|
+
const setLoading = useCallback((loading: boolean) => {
|
|
43
|
+
setIsLoading(loading);
|
|
44
|
+
}, []);
|
|
45
|
+
|
|
46
|
+
const setExpired = useCallback((expired: boolean) => {
|
|
47
|
+
setIsExpired(expired);
|
|
48
|
+
}, []);
|
|
49
|
+
|
|
50
|
+
// Memoize state and actions objects for performance
|
|
51
|
+
const state: CacheState<T> = useMemo(() => ({ data, isLoading, isExpired }), [data, isLoading, isExpired]);
|
|
52
|
+
const actions: CacheActions<T> = useMemo(() => ({ setData, clearData, setLoading, setExpired }), [setData, clearData, setLoading, setExpired]);
|
|
53
|
+
|
|
54
|
+
return [state, actions];
|
|
55
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* usePersistentCache Hook
|
|
3
|
+
* Presentation layer - Hook for persistent caching with TTL
|
|
4
|
+
*
|
|
5
|
+
* General-purpose cache hook for any app
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { useEffect, useCallback, useMemo } from 'react';
|
|
9
|
+
import { useCacheState } from './useCacheState';
|
|
10
|
+
import { CacheStorageOperations } from './CacheStorageOperations';
|
|
11
|
+
import { isCacheExpired } from '../../domain/entities/CachedValue';
|
|
12
|
+
import { DEFAULT_TTL } from '../../domain/constants/CacheDefaults';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Options for persistent cache
|
|
16
|
+
*/
|
|
17
|
+
export interface PersistentCacheOptions {
|
|
18
|
+
/**
|
|
19
|
+
* Time-to-live in milliseconds
|
|
20
|
+
* @default DEFAULT_TTL.MEDIUM (30 minutes)
|
|
21
|
+
*/
|
|
22
|
+
ttl?: number;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Cache version for invalidation
|
|
26
|
+
* Increment to invalidate existing caches
|
|
27
|
+
*/
|
|
28
|
+
version?: number;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Whether cache is enabled
|
|
32
|
+
* @default true
|
|
33
|
+
*/
|
|
34
|
+
enabled?: boolean;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Result from usePersistentCache hook
|
|
39
|
+
*/
|
|
40
|
+
export interface PersistentCacheResult<T> {
|
|
41
|
+
/**
|
|
42
|
+
* Cached data (null if not loaded or expired)
|
|
43
|
+
*/
|
|
44
|
+
data: T | null;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Whether data is being loaded from storage
|
|
48
|
+
*/
|
|
49
|
+
isLoading: boolean;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Whether cached data is expired
|
|
53
|
+
*/
|
|
54
|
+
isExpired: boolean;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Set data to cache
|
|
58
|
+
*/
|
|
59
|
+
setData: (value: T) => Promise<void>;
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Clear cached data
|
|
63
|
+
*/
|
|
64
|
+
clearData: () => Promise<void>;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Refresh cache (reload from storage)
|
|
68
|
+
*/
|
|
69
|
+
refresh: () => Promise<void>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Hook for persistent caching with TTL support
|
|
74
|
+
*
|
|
75
|
+
* @example
|
|
76
|
+
* ```typescript
|
|
77
|
+
* const { data, setData, isExpired } = usePersistentCache<Post[]>('posts-page-1', {
|
|
78
|
+
* ttl: TIME_MS.HOUR,
|
|
79
|
+
* version: 1,
|
|
80
|
+
* });
|
|
81
|
+
*
|
|
82
|
+
* // Check if need to fetch
|
|
83
|
+
* if (!data || isExpired) {
|
|
84
|
+
* const freshData = await fetchPosts();
|
|
85
|
+
* await setData(freshData);
|
|
86
|
+
* }
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
export function usePersistentCache<T>(
|
|
90
|
+
key: string,
|
|
91
|
+
options: PersistentCacheOptions = {},
|
|
92
|
+
): PersistentCacheResult<T> {
|
|
93
|
+
const { ttl = DEFAULT_TTL.MEDIUM, version, enabled = true } = options;
|
|
94
|
+
const [state, actions] = useCacheState<T>();
|
|
95
|
+
|
|
96
|
+
// Use singleton pattern to prevent memory leaks
|
|
97
|
+
const cacheOps = useMemo(() => CacheStorageOperations.getInstance(), []);
|
|
98
|
+
|
|
99
|
+
const loadFromStorage = useCallback(async () => {
|
|
100
|
+
if (!enabled) {
|
|
101
|
+
actions.setLoading(false);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
actions.setLoading(true);
|
|
106
|
+
|
|
107
|
+
try {
|
|
108
|
+
const cached = await cacheOps.loadFromStorage<T>(key, version);
|
|
109
|
+
|
|
110
|
+
if (cached) {
|
|
111
|
+
const expired = isCacheExpired(cached, version);
|
|
112
|
+
actions.setData(cached.value);
|
|
113
|
+
actions.setExpired(expired);
|
|
114
|
+
} else {
|
|
115
|
+
actions.clearData();
|
|
116
|
+
}
|
|
117
|
+
} catch {
|
|
118
|
+
actions.clearData();
|
|
119
|
+
} finally {
|
|
120
|
+
actions.setLoading(false);
|
|
121
|
+
}
|
|
122
|
+
}, [key, version, enabled, actions, cacheOps]);
|
|
123
|
+
|
|
124
|
+
const setData = useCallback(
|
|
125
|
+
async (value: T) => {
|
|
126
|
+
await cacheOps.saveToStorage(key, value, { ttl, version, enabled });
|
|
127
|
+
actions.setData(value);
|
|
128
|
+
},
|
|
129
|
+
[key, ttl, version, enabled, actions, cacheOps],
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
const clearData = useCallback(async () => {
|
|
133
|
+
await cacheOps.clearFromStorage(key, enabled);
|
|
134
|
+
actions.clearData();
|
|
135
|
+
}, [key, enabled, actions, cacheOps]);
|
|
136
|
+
|
|
137
|
+
const refresh = useCallback(async () => {
|
|
138
|
+
await loadFromStorage();
|
|
139
|
+
}, [loadFromStorage]);
|
|
140
|
+
|
|
141
|
+
// Prevent infinite loops by only running when key or enabled changes
|
|
142
|
+
useEffect(() => {
|
|
143
|
+
loadFromStorage();
|
|
144
|
+
}, [key, enabled]);
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
data: state.data,
|
|
148
|
+
isLoading: state.isLoading,
|
|
149
|
+
isExpired: state.isExpired,
|
|
150
|
+
setData,
|
|
151
|
+
clearData,
|
|
152
|
+
refresh,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* Provides clean API for components to interact with storage domain
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import { useCallback } from 'react';
|
|
8
|
+
import { useCallback, useMemo } from 'react';
|
|
9
9
|
import { storageRepository } from '../../infrastructure/repositories/AsyncStorageRepository';
|
|
10
10
|
import type { StorageResult } from '../../domain/entities/StorageResult';
|
|
11
11
|
import { unwrap } from '../../domain/entities/StorageResult';
|
|
@@ -88,7 +88,8 @@ export const useStorage = () => {
|
|
|
88
88
|
return storageRepository.getItem(keyString, defaultValue);
|
|
89
89
|
}, []);
|
|
90
90
|
|
|
91
|
-
return
|
|
91
|
+
// Memoize return object to prevent unnecessary re-renders
|
|
92
|
+
return useMemo(() => ({
|
|
92
93
|
getItem,
|
|
93
94
|
setItem,
|
|
94
95
|
getString,
|
|
@@ -97,5 +98,5 @@ export const useStorage = () => {
|
|
|
97
98
|
hasItem,
|
|
98
99
|
clearAll,
|
|
99
100
|
getItemWithResult,
|
|
100
|
-
};
|
|
101
|
+
}), [getItem, setItem, getString, setString, removeItem, hasItem, clearAll, getItemWithResult]);
|
|
101
102
|
};
|
|
@@ -3,8 +3,6 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Domain-Driven Design: Presentation layer hook for state + storage sync
|
|
5
5
|
* Combines React state with automatic storage persistence
|
|
6
|
-
*
|
|
7
|
-
* Theme: {{THEME_NAME}} ({{CATEGORY}} category)
|
|
8
6
|
*/
|
|
9
7
|
|
|
10
8
|
import { useState, useEffect, useCallback } from 'react';
|
|
@@ -18,7 +16,7 @@ import type { StorageKey } from '../../domain/value-objects/StorageKey';
|
|
|
18
16
|
*
|
|
19
17
|
* @example
|
|
20
18
|
* ```typescript
|
|
21
|
-
* const [
|
|
19
|
+
* const [settings, setSettings] = useStorageState('user_settings', { theme: 'light' });
|
|
22
20
|
* // State is automatically persisted to storage
|
|
23
21
|
* ```
|
|
24
22
|
*/
|
|
@@ -32,15 +30,33 @@ export const useStorageState = <T>(
|
|
|
32
30
|
|
|
33
31
|
// Load initial value from storage
|
|
34
32
|
useEffect(() => {
|
|
33
|
+
let isMounted = true;
|
|
34
|
+
|
|
35
35
|
const loadFromStorage = async () => {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
36
|
+
try {
|
|
37
|
+
const result = await storageRepository.getItem(keyString, defaultValue);
|
|
38
|
+
const value = unwrap(result, defaultValue);
|
|
39
|
+
|
|
40
|
+
// Memory leak önlemek için component mount kontrolü
|
|
41
|
+
if (isMounted) {
|
|
42
|
+
setState(value);
|
|
43
|
+
setIsLoading(false);
|
|
44
|
+
}
|
|
45
|
+
} catch {
|
|
46
|
+
// Hata durumunda bile cleanup yap
|
|
47
|
+
if (isMounted) {
|
|
48
|
+
setIsLoading(false);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
40
51
|
};
|
|
41
52
|
|
|
42
53
|
loadFromStorage();
|
|
43
|
-
|
|
54
|
+
|
|
55
|
+
// Cleanup function
|
|
56
|
+
return () => {
|
|
57
|
+
isMounted = false;
|
|
58
|
+
};
|
|
59
|
+
}, [keyString]); // defaultValue'ı dependency array'den çıkar
|
|
44
60
|
|
|
45
61
|
// Update state and persist to storage
|
|
46
62
|
const updateState = useCallback(
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* useStore Hook
|
|
3
|
+
* Helper for creating stores in components
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { useMemo } from 'react';
|
|
7
|
+
import { createStore } from '../../domain/factories/StoreFactory';
|
|
8
|
+
import type { StoreConfig } from '../../domain/types/Store';
|
|
9
|
+
|
|
10
|
+
export function useStore<T extends object>(config: StoreConfig<T>) {
|
|
11
|
+
// Config objesini stabilize et ki sonsuz re-render olmasın
|
|
12
|
+
const stableConfig = useMemo(() => config, [config.name, JSON.stringify(config)]);
|
|
13
|
+
const store = useMemo(() => createStore(stableConfig), [stableConfig]);
|
|
14
|
+
return store;
|
|
15
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/// <reference types="jest" />
|
|
2
|
+
/// <reference types="node" />
|
|
3
|
+
|
|
4
|
+
declare module '@react-native-async-storage/async-storage' {
|
|
5
|
+
export interface AsyncStorageStatic {
|
|
6
|
+
getItem(key: string): Promise<string | null>;
|
|
7
|
+
setItem(key: string, value: string): Promise<void>;
|
|
8
|
+
removeItem(key: string): Promise<void>;
|
|
9
|
+
clear(): Promise<void>;
|
|
10
|
+
getAllKeys(): Promise<readonly string[]>;
|
|
11
|
+
multiGet(keys: readonly string[]): Promise<readonly (readonly [string, string | null])[]>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const AsyncStorage: AsyncStorageStatic;
|
|
15
|
+
export default AsyncStorage;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
declare module 'react' {
|
|
19
|
+
export function useState<T>(initialState: T | (() => T)): [T, (value: T | ((prev: T) => T)) => void];
|
|
20
|
+
export function useEffect(effect: () => void | (() => void), deps?: readonly any[]): void;
|
|
21
|
+
export function useCallback<T extends (...args: any[]) => any>(callback: T, deps: readonly any[]): T;
|
|
22
|
+
export function useMemo<T>(factory: () => T, deps: readonly any[]): T;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
declare module 'react-native' {
|
|
26
|
+
// Add React Native specific types if needed
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
declare global {
|
|
30
|
+
namespace jest {
|
|
31
|
+
interface Matchers<R> {
|
|
32
|
+
toBeValidStorageKey(): R;
|
|
33
|
+
toBeExpired(): R;
|
|
34
|
+
toHaveValidCache(): R;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
var __DEV__: boolean | undefined;
|
|
39
|
+
var global: any;
|
|
40
|
+
}
|
package/LICENSE
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2024 Ümit UZ
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
22
|
-
|