atoms-state v0.8.1

#js#react#flux

git clone https://git.pyrossh.dev/atoms-state

Simple State management for react


a43e611 — Peter John 2021-12-30T14:30:05+05:30
add storage and form

Generated files not shown: package-lock.json

Files changed (3) hide show
  1. index.d.ts +43 -8
  2. index.js +297 -112
  3. package.json +6 -2
index.d.ts CHANGED
@@ -1,20 +1,55 @@
1
1
  export declare type Atom<S> = {
2
- getValue: () => S;
2
+ getValue: () => S;
3
- subscribe: (listener: (value: S) => void) => () => void;
3
+ subscribe: (listener: (value: S) => void) => () => void;
4
- update: (fn: (oldValue: S) => S) => void;
4
+ update: (fn: (oldValue: S) => S) => void;
5
5
  };
6
6
  export declare type AtomGetter = <V>(atom: Atom<V>) => V;
7
7
  export declare type DerivedAtomReader<S> = (read: AtomGetter) => S;
8
8
  export declare const atom: <S>(initial: S | DerivedAtomReader<S>) => Atom<S>;
9
9
  export declare const useAtom: <S>(atom: Atom<S>) => S;
10
10
  export declare type AsyncAtom<P, S> = {
11
- compute: (p: P) => S | Promise<S>;
11
+ compute: (p: P) => S | Promise<S>;
12
- fetch: (p: P) => Promise<S>;
12
+ fetch: (p: P) => Promise<S>;
13
- subscribe: (listener: (value: S) => void) => () => void;
13
+ subscribe: (listener: (value: S) => void) => () => void;
14
- update: (fn: (oldValue: S) => S) => void;
14
+ update: (fn: (oldValue: S) => S) => void;
15
15
  };
16
16
  export declare const asyncAtom: <P, S>(fn: (p: P) => Promise<S>) => AsyncAtom<P, S>;
17
17
  export declare const useAsyncAtom: <P, S>(a: AsyncAtom<P, S>, params: P) => S;
18
18
  declare type PromiseFunc<S, P> = (p: P) => Promise<S>;
19
19
  export declare const usePromise: <S, P>(fn: PromiseFunc<S, P>, params: P) => [S, (v: S) => void];
20
+
21
+ export function useField<T>(name: string): {
22
+ name: string;
20
- export {};
23
+ error: string;
24
+ setError: (v: string | undefined) => void;
25
+ registerField: (f: { get: () => T; set: (v: T) => void; clear: () => void }) => void;
26
+ };
27
+
28
+ export function useForm<T>(
29
+ initial: T,
30
+ submit: (d: T) => Promise<void>,
31
+ ): {
32
+ error: string;
33
+ setError: (v?: string) => void;
34
+ getData: () => T;
35
+ setData: (v: T) => void;
36
+ clear: () => void;
37
+ reset: () => void;
38
+ getFieldValue: (name: string) => any;
39
+ setFieldValue: (name: string, value: any) => void;
40
+ clearFieldValue: (name: string) => void;
41
+ getFieldError: (name: string) => string | undefined;
42
+ setFieldError: (name: string, value: string | undefined) => void;
43
+ onSubmit: (d: T) => Promise<void>;
44
+ };
45
+
46
+ declare module 'Storage' {
47
+ export function setItem<T>(key: string, value: T): boolean;
48
+ export function getItem<T>(key: string): T;
49
+ export function removeItem(key: string): void;
50
+ export function clear(): void;
51
+ export function subscribe<T>(key: string, cb: (v: T) => void): void;
52
+ export function unsubscribe(key: string, cb: Function): void;
53
+ }
54
+
55
+ export function useAsyncStorage<T>(key: string, initial: T): [T, (v: T) => void, boolean];
index.js CHANGED
@@ -1,132 +1,317 @@
1
+ import { useState, useEffect, useRef, useCallback } from 'react';
2
+ import AsyncStorage from '@react-native-async-storage/async-storage';
1
- import React from "react";
3
+ import dot from 'dot-object';
2
4
 
3
5
  export const atom = (initial) => {
4
- let value;
6
+ let value;
5
- const isDerived = typeof initial === 'function';
7
+ const isDerived = typeof initial === 'function';
6
- const subs = new Set();
8
+ const subs = new Set();
7
- const get = (a) => {
9
+ const get = (a) => {
8
- a.subscribe(compute);
10
+ a.subscribe(compute);
9
- return a.getValue();
11
+ return a.getValue();
10
- };
12
+ };
11
- const compute = () => {
13
+ const compute = () => {
12
- value = initial(get);
14
+ value = initial(get);
13
- subs.forEach(sub => {
15
+ subs.forEach((sub) => {
14
- sub(value);
16
+ sub(value);
15
- });
17
+ });
16
- };
18
+ };
17
- if (isDerived) {
19
+ if (isDerived) {
18
- compute();
20
+ compute();
21
+ } else {
22
+ value = initial;
19
- }
23
+ }
20
- else {
21
- value = initial;
22
- }
23
- return {
24
+ return {
24
- getValue() {
25
+ getValue() {
25
- return value;
26
+ return value;
26
- },
27
+ },
27
- subscribe(fn) {
28
+ subscribe(fn) {
28
- subs.add(fn);
29
+ subs.add(fn);
29
- return () => subs.delete(fn);
30
+ return () => subs.delete(fn);
30
- },
31
+ },
31
- update(fn) {
32
+ update(fn) {
32
- value = fn(value);
33
+ value = fn(value);
33
- subs.forEach(sub => {
34
+ subs.forEach((sub) => {
34
- sub(value);
35
+ sub(value);
35
- });
36
+ });
36
- },
37
+ },
37
- };
38
+ };
38
39
  };
39
40
 
40
41
  export const useAtom = (atom) => {
41
- const [data, setData] = React.useState(atom.getValue());
42
+ const [data, setData] = useState(atom.getValue());
42
- React.useEffect(() => {
43
+ useEffect(() => {
43
- return atom.subscribe(value => {
44
+ return atom.subscribe((value) => {
44
- setData(value);
45
+ setData(value);
45
- });
46
+ });
46
- }, []);
47
+ }, []);
47
- return data;
48
+ return data;
48
49
  };
49
50
 
50
51
  export const asyncAtom = (fn) => {
51
- let value;
52
+ let value;
52
- let params;
53
+ let params;
53
- const subs = new Set();
54
+ const subs = new Set();
54
- return {
55
+ return {
55
- compute(p) {
56
+ compute(p) {
56
- if (JSON.stringify(p) !== JSON.stringify(params)) {
57
+ if (JSON.stringify(p) !== JSON.stringify(params)) {
57
- params = p;
58
+ params = p;
58
- value = fn(p);
59
+ value = fn(p);
59
- value
60
+ value
60
- .then(res => {
61
+ .then((res) => {
61
- value = res;
62
+ value = res;
62
- })
63
+ })
63
- .catch(err => {
64
+ .catch((err) => {
64
- value = err;
65
+ value = err;
65
- });
66
+ });
66
- }
67
+ }
67
- return value;
68
+ return value;
68
- },
69
+ },
69
- fetch(p) {
70
+ fetch(p) {
70
- return fn(p);
71
+ return fn(p);
71
- },
72
+ },
72
- subscribe(fn) {
73
+ subscribe(fn) {
73
- subs.add(fn);
74
+ subs.add(fn);
74
- return () => subs.delete(fn);
75
+ return () => subs.delete(fn);
75
- },
76
+ },
76
- update(updater) {
77
+ update(updater) {
77
- value = updater(value);
78
+ value = updater(value);
78
- subs.forEach(sub => {
79
+ subs.forEach((sub) => {
79
- sub(value);
80
+ sub(value);
80
- });
81
+ });
81
- },
82
+ },
82
- };
83
+ };
83
84
  };
84
85
 
85
86
  export const useAsyncAtom = (a, params) => {
86
- const [, toggle] = React.useState(false);
87
+ const [, toggle] = useState(false);
87
- React.useEffect(() => {
88
+ useEffect(() => {
88
- return a.subscribe(() => toggle(v => !v));
89
+ return a.subscribe(() => toggle((v) => !v));
89
- }, []);
90
+ }, []);
90
- const v = a.compute(params);
91
+ const v = a.compute(params);
91
- if (v instanceof Error) {
92
+ if (v instanceof Error) {
92
- throw v;
93
+ throw v;
94
+ } else if (v instanceof Promise) {
95
+ throw v;
96
+ } else {
97
+ return v;
93
- }
98
+ }
94
- else if (v instanceof Promise) {
95
- throw v;
96
- }
97
- else {
98
- return v;
99
- }
100
99
  };
101
100
 
102
101
  const usePromiseCache = new Map();
103
102
  export const usePromise = (fn, params) => {
104
- const [data, setData] = React.useState(false);
103
+ const [data, setData] = useState(false);
105
- const fnCache = usePromiseCache.get(fn) || new Map();
104
+ const fnCache = usePromiseCache.get(fn) || new Map();
106
- if (!usePromiseCache.get(fn)) {
105
+ if (!usePromiseCache.get(fn)) {
107
- usePromiseCache.set(fn, fnCache);
106
+ usePromiseCache.set(fn, fnCache);
107
+ }
108
+ const key = typeof params === 'string' ? params : JSON.stringify(params);
109
+ const value = fnCache.get(key);
110
+ if (value) {
111
+ if (value instanceof Promise) {
112
+ throw value;
113
+ } else if (value instanceof Error || (value === null || value === void 0 ? void 0 : value.errors)) {
114
+ throw value;
108
115
  }
116
+ return [
117
+ value,
118
+ (v) => {
119
+ fnCache.set(key, v);
120
+ setData(!data);
121
+ },
122
+ ];
123
+ }
124
+ fnCache.set(
125
+ key,
126
+ fn(params)
127
+ .then((res) => {
128
+ fnCache.set(key, res);
129
+ })
109
- const key = typeof params === 'string' ? params : JSON.stringify(params);
130
+ .catch((err) => fnCache.set(key, err)),
131
+ );
110
- const value = fnCache.get(key);
132
+ throw fnCache.get(key);
133
+ };
134
+
135
+ export const Storage = {
136
+ listeners: {},
137
+ async getItem(key) {
138
+ const item = await AsyncStorage.getItem(key);
139
+ return item ? JSON.parse(item) : null;
140
+ },
141
+ async setItem(key, value) {
111
142
  if (value) {
143
+ await AsyncStorage.setItem(key, JSON.stringify(value));
144
+ } else {
112
- if (value instanceof Promise) {
145
+ await AsyncStorage.removeItem(key);
113
- throw value;
114
- }
146
+ }
147
+ if (this.listeners[key]) {
115
- else if (value instanceof Error || (value === null || value === void 0 ? void 0 : value.errors)) {
148
+ for (const cb of this.listeners[key]) {
116
- throw value;
149
+ cb(value);
150
+ }
151
+ }
152
+ },
153
+ async removeItem(key) {
154
+ await AsyncStorage.removeItem(key);
155
+ },
156
+ async clear() {
157
+ await AsyncStorage.clear();
158
+ },
159
+ subscribe(key, cb) {
160
+ if (!this.listeners[key]) {
161
+ this.listeners[key] = new Set();
162
+ }
163
+ this.listeners[key].add(cb);
164
+ return () => {
165
+ this.listeners[key].delete(cb);
166
+ };
167
+ },
168
+ unsubscribe(key, cb) {
169
+ this.listeners[key].delete(cb);
170
+ },
171
+ };
172
+
173
+ export const useAsyncStorage = (key, initialValue) => {
174
+ const [loading, setLoading] = useState(true);
175
+ const [storedValue, setStoredValue] = useState(initialValue);
176
+ const setData = async (v) => {
177
+ await Storage.setItem(key, v);
178
+ };
179
+ useEffect(() => {
180
+ Storage.getItem(key)
181
+ .then((v) => {
182
+ if (v) {
183
+ setData(v);
117
184
  }
185
+ setLoading(false);
186
+ })
187
+ .catch(() => setLoading(false));
188
+ return Storage.subscribe(key, (v) => {
189
+ setStoredValue(v);
190
+ });
191
+ }, [key, JSON.stringify(initialValue)]);
192
+ return [storedValue || initialValue, setData, loading];
193
+ };
194
+
195
+ export const fields = {};
196
+
197
+ export const useField = (name) => {
198
+ const [error, setError] = useState('');
199
+ const errorRef = useRef('');
200
+ if (!name) {
201
+ throw new Error('You need to provide the "name" prop.');
202
+ }
203
+ const setErrorMessage = (message) => {
204
+ errorRef.current = message;
205
+ setError(message);
206
+ };
118
- return [
207
+ return {
119
- value,
208
+ name,
209
+ error,
210
+ setError: setErrorMessage,
211
+ registerField: (f) => {
212
+ fields[name] = {
213
+ ...f,
214
+ getError: () => errorRef.current,
215
+ setError: setErrorMessage,
216
+ };
120
- v => {
217
+ return () => {
121
- fnCache.set(key, v);
122
- setData(!data);
218
+ delete fields[name];
219
+ };
123
- },
220
+ },
124
- ];
221
+ };
222
+ };
223
+
224
+ export const useForm = (initial, submit) => {
225
+ const [error, setError] = useState('');
226
+ const getData = () => {
227
+ const obj = {};
228
+ for (const name of Object.keys(fields)) {
229
+ obj[name] = fields[name].get();
125
230
  }
231
+ return dot.object(obj);
232
+ };
233
+ const setData = useCallback((data) => {
234
+ const dotData = dot.dot(data);
235
+ for (const name of Object.keys(fields)) {
126
- fnCache.set(key, fn(params)
236
+ fields[name].set(dotData[name]);
237
+ }
238
+ }, []);
239
+ useEffect(() => {
240
+ if (initial) {
241
+ setData(initial);
242
+ }
243
+ }, [initial, setData]);
244
+ return {
245
+ error,
246
+ setError,
247
+ getData,
248
+ setData,
249
+ clear: () => {
250
+ for (const name of Object.keys(fields)) {
251
+ fields[name].clear();
252
+ }
253
+ },
127
- .then(res => {
254
+ reset: () => {
255
+ setData(initial);
256
+ },
257
+ getFieldValue: (name) => {
258
+ const field = fields[name];
259
+ if (field) {
260
+ return field.get();
261
+ }
262
+ },
263
+ setFieldValue: (name, value) => {
264
+ const field = fields[name];
265
+ if (field) {
128
- fnCache.set(key, res);
266
+ field.set(value);
267
+ }
268
+ },
269
+ clearFieldValue: (name) => {
270
+ const field = fields[name];
271
+ if (field) {
272
+ field.clear();
273
+ }
274
+ },
275
+ getFieldError: (name) => {
276
+ const field = fields[name];
277
+ if (field) {
278
+ return field.getError();
279
+ }
280
+ return '';
281
+ },
282
+ setFieldError: (name, value) => {
283
+ const field = fields[name];
284
+ if (field) {
285
+ field.setError(value);
286
+ }
287
+ },
288
+ onSubmit: async () => {
289
+ try {
290
+ const data = getData();
291
+ setError('');
292
+ for (const name of Object.keys(fields)) {
293
+ fields[name].setError('');
294
+ }
295
+ const allValid = Object.keys(fields)
296
+ .map((key) => fields[key])
297
+ .reduce((acc, field) => acc && field.getError() === '', true);
298
+ if (allValid) {
299
+ await submit(data);
300
+ }
301
+ } catch (err) {
302
+ // this is for validation errors
303
+ if (err.error && typeof err.error !== 'string') {
304
+ Object.keys(err.error).forEach((k) => {
305
+ const field = fields[k];
306
+ if (field) {
307
+ field.setError(err.error[k]);
308
+ }
129
- })
309
+ });
310
+ setError('Validation failed. Please correct the necessary fields.');
311
+ } else {
130
- .catch(err => fnCache.set(key, err)));
312
+ setError(err.message || err.error);
313
+ }
314
+ }
315
+ },
131
- throw fnCache.get(key);
316
+ };
132
317
  };
package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "atoms-state",
3
3
  "author": "pyros.sh",
4
- "description": "A simple statemanagement library for react",
4
+ "description": "State management and common hooks",
5
- "version": "0.6.0",
5
+ "version": "0.7.0",
6
6
  "license": "MIT",
7
7
  "type": "module",
8
8
  "main": "index.js",
@@ -42,5 +42,9 @@
42
42
  "singleQuote": true,
43
43
  "arrowParens": "always",
44
44
  "trailingComma": "all"
45
+ },
46
+ "dependencies": {
47
+ "@react-native-async-storage/async-storage": "^1.15.14",
48
+ "dot-object": "^2.1.4"
45
49
  }
46
50
  }