atoms-state v0.8.1

#js#react#flux

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

Simple State management for react


551beab — Peter John 2021-08-13T09:15:50+05:30
simplify library

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

.github/workflows/main.yml CHANGED
@@ -1,32 +1,12 @@
1
- name: CI
1
+ name: Test
2
2
  on: [push]
3
3
  jobs:
4
- build:
4
+ Test:
5
- name: Build, lint, and test on Node ${{ matrix.node }} and ${{ matrix.os }}
6
-
7
- runs-on: ${{ matrix.os }}
5
+ runs-on: ubuntu-latest
8
- strategy:
9
- matrix:
10
- node: ['10.x', '12.x', '14.x']
11
- os: [ubuntu-latest, windows-latest, macOS-latest]
12
-
13
6
  steps:
14
- - name: Checkout repo
15
- uses: actions/checkout@v2
7
+ - uses: actions/checkout@v2
16
-
17
- - name: Use Node ${{ matrix.node }}
18
- uses: actions/setup-node@v1
8
+ - uses: actions/setup-node@v1
19
9
  with:
20
- node-version: ${{ matrix.node }}
10
+ node-version: 14.x
21
-
22
- - name: Install deps and build (with cache)
23
- uses: bahmutov/npm-install@v1
11
+ - uses: bahmutov/npm-install@v1
24
-
25
- - name: Lint
26
- run: yarn lint
27
-
28
- - name: Test
12
+ - run: npm test
29
- run: yarn test --ci --coverage --maxWorkers=2
30
-
31
- - name: Build
32
- run: yarn build
index.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ export declare type Atom<S> = {
2
+ getValue: () => S;
3
+ subscribe: (listener: (value: S) => void) => () => void;
4
+ update: (fn: (oldValue: S) => S) => void;
5
+ };
6
+ export declare type AtomGetter = <V>(atom: Atom<V>) => V;
7
+ export declare type DerivedAtomReader<S> = (read: AtomGetter) => S;
8
+ export declare const atom: <S>(initial: S | DerivedAtomReader<S>) => Atom<S>;
9
+ export declare const useAtom: <S>(atom: Atom<S>) => S;
10
+ export declare type AsyncAtom<P, S> = {
11
+ compute: (p: P) => S | Promise<S>;
12
+ fetch: (p: P) => Promise<S>;
13
+ subscribe: (listener: (value: S) => void) => () => void;
14
+ update: (fn: (oldValue: S) => S) => void;
15
+ };
16
+ export declare const asyncAtom: <P, S>(fn: (p: P) => Promise<S>) => AsyncAtom<P, S>;
17
+ export declare const useAsyncAtom: <P, S>(a: AsyncAtom<P, S>, params: P) => S;
18
+ declare type PromiseFunc<S, P> = (p: P) => Promise<S>;
19
+ export declare const usePromise: <S, P>(fn: PromiseFunc<S, P>, params: P) => [S, (v: S) => void];
20
+ export {};
index.js ADDED
@@ -0,0 +1,132 @@
1
+ import React from "react";
2
+
3
+ export const atom = (initial) => {
4
+ let value;
5
+ const isDerived = typeof initial === 'function';
6
+ const subs = new Set();
7
+ const get = (a) => {
8
+ a.subscribe(compute);
9
+ return a.getValue();
10
+ };
11
+ const compute = () => {
12
+ value = initial(get);
13
+ subs.forEach(sub => {
14
+ sub(value);
15
+ });
16
+ };
17
+ if (isDerived) {
18
+ compute();
19
+ }
20
+ else {
21
+ value = initial;
22
+ }
23
+ return {
24
+ getValue() {
25
+ return value;
26
+ },
27
+ subscribe(fn) {
28
+ subs.add(fn);
29
+ return () => subs.delete(fn);
30
+ },
31
+ update(fn) {
32
+ value = fn(value);
33
+ subs.forEach(sub => {
34
+ sub(value);
35
+ });
36
+ },
37
+ };
38
+ };
39
+
40
+ export const useAtom = (atom) => {
41
+ const [data, setData] = React.useState(atom.getValue());
42
+ React.useEffect(() => {
43
+ return atom.subscribe(value => {
44
+ setData(value);
45
+ });
46
+ }, []);
47
+ return data;
48
+ };
49
+
50
+ export const asyncAtom = (fn) => {
51
+ let value;
52
+ let params;
53
+ const subs = new Set();
54
+ return {
55
+ compute(p) {
56
+ if (JSON.stringify(p) !== JSON.stringify(params)) {
57
+ params = p;
58
+ value = fn(p);
59
+ value
60
+ .then(res => {
61
+ value = res;
62
+ })
63
+ .catch(err => {
64
+ value = err;
65
+ });
66
+ }
67
+ return value;
68
+ },
69
+ fetch(p) {
70
+ return fn(p);
71
+ },
72
+ subscribe(fn) {
73
+ subs.add(fn);
74
+ return () => subs.delete(fn);
75
+ },
76
+ update(updater) {
77
+ value = updater(value);
78
+ subs.forEach(sub => {
79
+ sub(value);
80
+ });
81
+ },
82
+ };
83
+ };
84
+
85
+ export const useAsyncAtom = (a, params) => {
86
+ const [, toggle] = React.useState(false);
87
+ React.useEffect(() => {
88
+ return a.subscribe(() => toggle(v => !v));
89
+ }, []);
90
+ const v = a.compute(params);
91
+ if (v instanceof Error) {
92
+ throw v;
93
+ }
94
+ else if (v instanceof Promise) {
95
+ throw v;
96
+ }
97
+ else {
98
+ return v;
99
+ }
100
+ };
101
+
102
+ const usePromiseCache = new Map();
103
+ export const usePromise = (fn, params) => {
104
+ const [data, setData] = React.useState(false);
105
+ const fnCache = usePromiseCache.get(fn) || new Map();
106
+ if (!usePromiseCache.get(fn)) {
107
+ usePromiseCache.set(fn, fnCache);
108
+ }
109
+ const key = typeof params === 'string' ? params : JSON.stringify(params);
110
+ const value = fnCache.get(key);
111
+ if (value) {
112
+ if (value instanceof Promise) {
113
+ throw value;
114
+ }
115
+ else if (value instanceof Error || (value === null || value === void 0 ? void 0 : value.errors)) {
116
+ throw value;
117
+ }
118
+ return [
119
+ value,
120
+ v => {
121
+ fnCache.set(key, v);
122
+ setData(!data);
123
+ },
124
+ ];
125
+ }
126
+ fnCache.set(key, fn(params)
127
+ .then(res => {
128
+ fnCache.set(key, res);
129
+ })
130
+ .catch(err => fnCache.set(key, err)));
131
+ throw fnCache.get(key);
132
+ };
test/index.test.ts → index.test.js RENAMED
@@ -1,4 +1,4 @@
1
- import { atom } from '../src';
1
+ import { atom } from './index';
2
2
 
3
3
  describe('atom', () => {
4
4
  it('getValue', () => {
package.json CHANGED
@@ -2,16 +2,17 @@
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
+ "type": "module",
7
- "main": "dist/index.js",
8
+ "main": "index.js",
8
- "typings": "dist/index.d.ts",
9
+ "typings": "index.d.ts",
9
10
  "files": [
10
- "dist",
11
+ "index.js",
11
- "src"
12
+ "index.d.ts"
12
13
  ],
13
14
  "engines": {
14
- "node": ">=10"
15
+ "node": ">=14"
15
16
  },
16
17
  "keywords": [
17
18
  "react",
@@ -24,36 +25,22 @@
24
25
  "pyros.sh"
25
26
  ],
26
27
  "scripts": {
27
- "start": "tsdx watch",
28
- "build": "tsc src/*.* -d --target es6 --module commonjs --moduleResolution node --outDir dist",
29
- "test": "tsdx test",
28
+ "test": "NODE_OPTIONS=--experimental-vm-modules jest"
30
- "lint": "tsdx lint --fix",
31
- "prepare": "npm run build"
32
29
  },
33
30
  "peerDependencies": {
34
31
  "react": "*"
35
32
  },
33
+ "devDependencies": {
34
+ "jest": "^27.0.5",
35
+ "react": "17.0.2"
36
+ },
36
- "husky": {
37
+ "jest": {
37
- "hooks": {
38
+ "transform": {}
38
- "pre-commit": "tsdx lint"
39
- }
40
39
  },
41
40
  "prettier": {
42
41
  "printWidth": 160,
43
- "semi": true,
44
42
  "singleQuote": true,
43
+ "arrowParens": "always",
45
- "trailingComma": "es5"
44
+ "trailingComma": "all"
46
- },
47
- "devDependencies": {
48
- "@types/react": "17.0.2",
49
- "husky": "^6.0.0",
50
- "react": "17.0.2",
51
- "tsdx": "^0.14.1",
52
- "tslib": "^2.1.0",
53
- "typescript": "^4.2.3"
54
- },
55
- "resolutions": {
56
- "**/@typescript-eslint/eslint-plugin": "^4.1.1",
57
- "**/@typescript-eslint/parser": "^4.1.1"
58
45
  }
59
46
  }
src/index.ts DELETED
@@ -1,149 +0,0 @@
1
- import { useState, useEffect } from 'react';
2
-
3
- export type Atom<S> = {
4
- getValue: () => S;
5
- subscribe: (listener: (value: S) => void) => () => void;
6
- update: (fn: (oldValue: S) => S) => void;
7
- };
8
- export type AtomGetter = <V>(atom: Atom<V>) => V;
9
- export type DerivedAtomReader<S> = (read: AtomGetter) => S;
10
-
11
- export const atom = <S>(initial: S | DerivedAtomReader<S>): Atom<S> => {
12
- let value: S;
13
- const isDerived = typeof initial === 'function';
14
- const subs = new Set<(value: S) => void>();
15
- const get = <A>(a: Atom<A>) => {
16
- a.subscribe(compute);
17
- return a.getValue();
18
- };
19
- const compute = () => {
20
- value = (initial as DerivedAtomReader<S>)(get);
21
- subs.forEach(sub => {
22
- sub(value);
23
- });
24
- };
25
- if (isDerived) {
26
- compute();
27
- } else {
28
- value = initial as S;
29
- }
30
- return {
31
- getValue(): S {
32
- return value;
33
- },
34
- subscribe(fn) {
35
- subs.add(fn);
36
- return () => subs.delete(fn);
37
- },
38
- update(fn: (oldValue: S) => S) {
39
- value = fn(value);
40
- subs.forEach(sub => {
41
- sub(value);
42
- });
43
- },
44
- };
45
- };
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
-
57
- export type AsyncAtom<P, S> = {
58
- compute: (p: P) => S | Promise<S>;
59
- fetch: (p: P) => Promise<S>;
60
- subscribe: (listener: (value: S) => void) => () => void;
61
- update: (fn: (oldValue: S) => S) => void;
62
- };
63
-
64
- export const asyncAtom = <P, S>(fn: (p: P) => Promise<S>): AsyncAtom<P, S> => {
65
- let value: S | Promise<S>;
66
- let params: any;
67
- const subs = new Set<(value: S) => void>();
68
- return {
69
- compute(p: P): S | Promise<S> {
70
- if (JSON.stringify(p) !== JSON.stringify(params)) {
71
- params = p;
72
- value = fn(p);
73
- value
74
- .then(res => {
75
- value = res;
76
- })
77
- .catch(err => {
78
- value = err;
79
- });
80
- }
81
- return value;
82
- },
83
- fetch(p: P): Promise<S> {
84
- return fn(p);
85
- },
86
- subscribe(fn) {
87
- subs.add(fn);
88
- return () => subs.delete(fn);
89
- },
90
- update(updater: (oldValue: S) => S) {
91
- value = updater(value as S);
92
- subs.forEach(sub => {
93
- sub(value as S);
94
- });
95
- },
96
- };
97
- };
98
-
99
- export const useAsyncAtom = <P, S>(a: AsyncAtom<P, S>, params: P) => {
100
- const [, toggle] = useState(false);
101
- useEffect(() => {
102
- return a.subscribe(() => toggle(v => !v));
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 {
110
- return v;
111
- }
112
- };
113
-
114
- type PromiseFunc<S, P> = (p: P) => Promise<S>;
115
-
116
- const usePromiseCache: Map<Function, Map<string, any>> = new Map();
117
- export const usePromise = <S, P>(fn: PromiseFunc<S, P>, params: P): [S | null, (v: S) => void] => {
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,
133
- v => {
134
- fnCache.set(key, v);
135
- setData(!data);
136
- },
137
- ];
138
- }
139
-
140
- fnCache.set(
141
- key,
142
- fn(params)
143
- .then(res => {
144
- fnCache.set(key, res);
145
- })
146
- .catch(err => fnCache.set(key, err))
147
- );
148
- throw fnCache.get(key);
149
- };
tsconfig.json DELETED
@@ -1,35 +0,0 @@
1
- {
2
- // see https://www.typescriptlang.org/tsconfig to better understand tsconfigs
3
- "include": ["src", "types"],
4
- "compilerOptions": {
5
- "module": "esnext",
6
- "lib": ["dom", "esnext"],
7
- "importHelpers": true,
8
- // output .d.ts declaration files for consumers
9
- "declaration": true,
10
- // output .js.map sourcemap files for consumers
11
- "sourceMap": true,
12
- // match output dir to input dir. e.g. dist/index instead of dist/src/index
13
- "rootDir": "./src",
14
- // stricter type-checking for stronger correctness. Recommended by TS
15
- "strict": true,
16
- // linter checks for common issues
17
- "noImplicitReturns": true,
18
- "noFallthroughCasesInSwitch": true,
19
- // noUnused* overlap with @typescript-eslint/no-unused-vars, can disable if duplicative
20
- "noUnusedLocals": true,
21
- "noUnusedParameters": true,
22
- // use Node's module resolution algorithm, instead of the legacy TS one
23
- "moduleResolution": "node",
24
- // transpile JSX to React.createElement
25
- "jsx": "react",
26
- // interop between ESM and CJS modules. Recommended by TS
27
- "esModuleInterop": true,
28
- // significant perf increase by skipping checking .d.ts files, particularly those in node_modules. Recommended by TS
29
- "skipLibCheck": true,
30
- // error out if import and file system have a casing mismatch. Recommended by TS
31
- "forceConsistentCasingInFileNames": true,
32
- // `tsdx build` ignores this option, but it is commonly used when type-checking separately with `tsc`
33
- "noEmit": true,
34
- }
35
- }