atoms-state v0.8.1

#js#react#flux

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

Simple State management for react


fcb6563 — Peter John 2021-08-13T08:48:45+05:30
Revert "make it work with hauntedjs"

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

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