atoms-state v0.8.1

#js#react#flux

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

Simple State management for react


9887477 — pyros2097 2021-06-09T22:31:49+05:30
make it work with hauntedjs

Generated files not shown: package-lock.json, yarn.lock

Files changed (4) hide show
  1. README.md +9 -3
  2. package.json +2 -7
  3. src/index.ts +63 -61
  4. test/index.test.ts +0 -7
README.md CHANGED
@@ -4,14 +4,18 @@
4
4
 
5
5
  A simple statemanagement library for react.
6
6
 
7
+ ```sh
7
- `npm i atoms-state`
8
+ npm i atoms-state
9
+ ```
8
10
 
9
11
  ## Usage
10
12
 
11
13
  ```js
12
14
  import React from 'react';
13
15
  import ReactDOM from 'react-dom';
14
- import { atom, useAtom } from 'atoms-state';
16
+ import { atom, createUseAtom } from 'atoms-state';
17
+
18
+ const useAtom = createUseAtom({ useState, useEffect });
15
19
 
16
20
  const countAtom = atom(10);
17
21
  const sumAtom = atom(get => get(countAtom) + 10);
@@ -46,7 +50,9 @@ ReactDOM.render(<Counter />, document.getElementById('root'));
46
50
  ```js
47
51
  import React, { Suspense } from 'react';
48
52
  import ReactDOM from 'react-dom';
49
- import { asyncAtom, useAsyncAtom } from 'atoms-state';
53
+ import { asyncAtom, createUseAsyncAtomSuspend } from 'atoms-state';
54
+
55
+ const useAsyncAtom = createUseAsyncAtomSuspend({ useState, useEffect });
50
56
 
51
57
  const todoAtom = asyncAtom(async ({ id }) => {
52
58
  const res = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);
package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "atoms-state",
3
3
  "author": "pyros.sh",
4
4
  "description": "A simple statemanagement library for react",
5
- "version": "0.4.1",
5
+ "version": "0.5.0",
6
6
  "license": "MIT",
7
7
  "main": "dist/index.js",
8
8
  "typings": "dist/index.d.ts",
@@ -30,9 +30,6 @@
30
30
  "lint": "tsdx lint --fix",
31
31
  "prepare": "npm run build"
32
32
  },
33
- "peerDependencies": {
34
- "react": "*"
35
- },
36
33
  "husky": {
37
34
  "hooks": {
38
35
  "pre-commit": "tsdx lint"
@@ -45,9 +42,7 @@
45
42
  "trailingComma": "es5"
46
43
  },
47
44
  "devDependencies": {
48
- "@types/react": "17.0.2",
49
45
  "husky": "^6.0.0",
50
- "react": "17.0.2",
51
46
  "tsdx": "^0.14.1",
52
47
  "tslib": "^2.1.0",
53
48
  "typescript": "^4.2.3"
@@ -56,4 +51,4 @@
56
51
  "**/@typescript-eslint/eslint-plugin": "^4.1.1",
57
52
  "**/@typescript-eslint/parser": "^4.1.1"
58
53
  }
59
- }
54
+ }
src/index.ts CHANGED
@@ -1,5 +1,3 @@
1
- import { useState, useEffect } from 'react';
2
-
3
1
  export type Atom<S> = {
4
2
  getValue: () => S;
5
3
  subscribe: (listener: (value: S) => void) => () => void;
@@ -8,6 +6,16 @@ export type Atom<S> = {
8
6
  export type AtomGetter = <V>(atom: Atom<V>) => V;
9
7
  export type DerivedAtomReader<S> = (read: AtomGetter) => S;
10
8
 
9
+ export type Destructor = () => void | undefined;
10
+ export type EffectCallback = () => (void | Destructor);
11
+ export type SetStateAction<S> = S | ((prevState: S) => S);
12
+ export type Dispatch<A> = (value: A) => void;
13
+ export type DependencyList = ReadonlyArray<any>;
14
+ export type StateContainerProps = {
15
+ useState: <S>(initialState: S | (() => S)) => [S, Dispatch<SetStateAction<S>>];
16
+ useEffect: (effect: EffectCallback, deps?: DependencyList) => void;
17
+ };
18
+
11
19
  export const atom = <S>(initial: S | DerivedAtomReader<S>): Atom<S> => {
12
20
  let value: S;
13
21
  const isDerived = typeof initial === 'function';
@@ -44,16 +52,6 @@ export const atom = <S>(initial: S | DerivedAtomReader<S>): Atom<S> => {
44
52
  };
45
53
  };
46
54
 
47
- export const useAtom = <S>(atom: Atom<S>): S => {
48
- const [data, setData] = useState<S>(atom.getValue());
49
- useEffect(() => {
50
- return atom.subscribe(value => {
51
- setData(value);
52
- });
53
- }, []);
54
- return data;
55
- };
56
-
57
55
  export type AsyncAtom<P, S> = {
58
56
  compute: (p: P) => S | Promise<S>;
59
57
  fetch: (p: P) => Promise<S>;
@@ -61,21 +59,35 @@ export type AsyncAtom<P, S> = {
61
59
  update: (fn: (oldValue: S) => S) => void;
62
60
  };
63
61
 
62
+ export const asyncAtomCache = new Map();
63
+
64
64
  export const asyncAtom = <P, S>(fn: (p: P) => Promise<S>): AsyncAtom<P, S> => {
65
65
  let value: S | Promise<S>;
66
66
  let params: any;
67
67
  const subs = new Set<(value: S) => void>();
68
+ const fnCache = asyncAtomCache.get(fn) || new Map();
69
+ if (!asyncAtomCache.get(fn)) {
70
+ asyncAtomCache.set(fn, fnCache);
71
+ }
68
72
  return {
69
73
  compute(p: P): S | Promise<S> {
74
+ const key = JSON.stringify(p);
75
+ const cacheValue = fnCache.get(key);
76
+ if (typeof cacheValue !== 'undefined') {
77
+ return cacheValue;
78
+ }
70
- if (JSON.stringify(p) !== JSON.stringify(params)) {
79
+ if (key !== JSON.stringify(params)) {
71
80
  params = p;
72
81
  value = fn(p);
82
+ fnCache.set(key, value);
73
83
  value
74
84
  .then(res => {
75
85
  value = res;
86
+ fnCache.set(key, res);
76
87
  })
77
88
  .catch(err => {
78
89
  value = err;
90
+ fnCache.set(key, err);
79
91
  });
80
92
  }
81
93
  return value;
@@ -88,7 +100,9 @@ export const asyncAtom = <P, S>(fn: (p: P) => Promise<S>): AsyncAtom<P, S> => {
88
100
  return () => subs.delete(fn);
89
101
  },
90
102
  update(updater: (oldValue: S) => S) {
103
+ const key = JSON.stringify(params);
91
104
  value = updater(value as S);
105
+ fnCache.set(key, value);
92
106
  subs.forEach(sub => {
93
107
  sub(value as S);
94
108
  });
@@ -96,54 +110,42 @@ export const asyncAtom = <P, S>(fn: (p: P) => Promise<S>): AsyncAtom<P, S> => {
96
110
  };
97
111
  };
98
112
 
113
+ export const createUseAtom =
114
+ ({ useState, useEffect }: StateContainerProps) =>
99
- export const useAsyncAtom = <P, S>(a: AsyncAtom<P, S>, params: P) => {
115
+ <S>(atom: Atom<S>): S => {
100
- const [, toggle] = useState(false);
116
+ const [data, setData] = useState(atom.getValue());
101
- useEffect(() => {
117
+ useEffect(() => {
102
- return a.subscribe(() => toggle(v => !v));
118
+ return atom.subscribe((value) => {
119
+ setData(value);
120
+ });
103
- }, []);
121
+ }, []);
104
- const v = a.compute(params);
105
- if (v instanceof Error) {
106
- throw v;
107
- } else if (v instanceof Promise) {
108
- throw v;
109
- } else {
110
- return v;
122
+ return data;
111
- }
112
- };
123
+ };
113
124
 
114
- type PromiseFunc<S, P> = (p: P) => Promise<S>;
115
125
 
126
+ export const createUseAsyncAtom =
116
- const usePromiseCache: Map<Function, Map<string, any>> = new Map();
127
+ ({ useState, useEffect }: StateContainerProps) =>
117
- export const usePromise = <S, P>(fn: PromiseFunc<S, P>, params: P): [S | null, (v: S) => void] => {
128
+ <P, S>(a: AsyncAtom<P, S>, params: P) => {
118
- const [data, setData] = useState<boolean>(false);
129
+ const [, toggle] = useState(false);
119
- const fnCache = usePromiseCache.get(fn) || new Map();
120
- if (!usePromiseCache.get(fn)) {
121
- usePromiseCache.set(fn, fnCache);
122
- }
123
- const key = typeof params === 'string' ? params : JSON.stringify(params);
124
- const value = fnCache.get(key);
125
- if (value) {
126
- if (value instanceof Promise) {
127
- throw value;
128
- } else if (value instanceof Error || value?.errors) {
129
- throw value;
130
- }
131
- return [
132
- value,
133
- v => {
130
+ useEffect(() => {
131
+ return a.subscribe(() => toggle((v) => !v));
132
+ }, []);
134
- fnCache.set(key, v);
133
+ return a.compute(params);
135
- setData(!data);
136
- },
134
+ };
137
- ];
138
- }
139
135
 
136
+ export const createUseAsyncAtomSuspend =
137
+ ({ useState, useEffect }: StateContainerProps) =>
138
+ <P, S>(a: AsyncAtom<P, S>, params: P) => {
140
- fnCache.set(
139
+ const [, toggle] = useState(false);
141
- key,
142
- fn(params)
143
- .then(res => {
140
+ useEffect(() => {
141
+ return a.subscribe(() => toggle((v) => !v));
142
+ }, []);
144
- fnCache.set(key, res);
143
+ const v = a.compute(params);
144
+ if (v instanceof Error) {
145
+ return { err: v, data: null, loading: false };
146
+ } else if (v instanceof Promise) {
147
+ return { err: null, data: null, loading: true };
148
+ } else {
149
+ return { err: null, data: null, loading: true };
145
- })
150
+ }
146
- .catch(err => fnCache.set(key, err))
147
- );
148
- throw fnCache.get(key);
149
- };
151
+ };
test/index.test.ts CHANGED
@@ -25,11 +25,4 @@ describe('atom', () => {
25
25
  sumAtom.subscribe(newValue => expect(newValue).toEqual(20));
26
26
  atomOne.update(v => v + 5);
27
27
  });
28
-
29
- // it('useAtom', async () => {
30
- // })
31
28
  });
32
-
33
- describe('asyncAtom', () => {});
34
-
35
- describe('usePromise', () => {});