-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 578e092
Showing
14 changed files
with
4,783 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
module.exports = { | ||
root: true, | ||
parser: "@typescript-eslint/parser", | ||
plugins: ["@typescript-eslint", "react-hooks"], | ||
extends: [ | ||
"eslint:recommended", | ||
"plugin:@typescript-eslint/recommended", | ||
"plugin:react-hooks/recommended", | ||
], | ||
rules: { | ||
"react-hooks/rules-of-hooks": "error", | ||
"react-hooks/exhaustive-deps": "warn", | ||
"@typescript-eslint/no-explicit-any": 0, | ||
}, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
# Auto detect text files and perform LF normalization | ||
* text=auto |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
node_modules | ||
dist |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2021 jiseop.han | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
# Maru.js | ||
|
||
[![npm version](https://badge.fury.io/js/maru-js.svg)](https://badge.fury.io/js/maru-js) | ||
|
||
A minimal state management library for React | ||
|
||
## Features | ||
|
||
- global state management with few codes. | ||
- easily fetch data and sync to state | ||
- ESLint supported with [eslint-plugin-maru](https://github.com/jshan2017/eslint-plugin-maru) | ||
|
||
## Installation | ||
|
||
```bash | ||
npm i --save maru-js | ||
``` | ||
|
||
or using yarn, | ||
|
||
```bash | ||
yarn add maru-js | ||
``` | ||
|
||
## useMaruInit - initialize states from root component | ||
``` | ||
useMaruInit({key: value}) | ||
``` | ||
```typescript | ||
// App.tsx | ||
|
||
import { useMaruInit } from "maru-js"; | ||
|
||
const App = () => { | ||
useMaruInit({ count: 0, inputValue: "" }); | ||
|
||
return ( | ||
<div> | ||
<CounterA /> | ||
<CounterB /> | ||
<Input /> | ||
</div> | ||
); | ||
}; | ||
``` | ||
|
||
## useMaru - use state globally | ||
``` | ||
[state, setState] = useMaru<T>(key: string) | ||
``` | ||
|
||
```tsx | ||
import { useMaru } from "maru-js"; | ||
|
||
const CounterA = () => { | ||
const [count, setCount] = useMaru("count"); | ||
return ( | ||
<button type="button" onClick={() => setCount(count + 1)}> | ||
A: {count} | ||
</button> | ||
); | ||
}; | ||
|
||
const Input = () => { | ||
// pass type parameter 'number' to get correct type for the return value. | ||
const [inputValue, setInputValue] = useMaru<string>("inputValue"); | ||
return ( | ||
<input | ||
type="text" | ||
value={inputValue} | ||
onChange={({ target }) => setInputValue(target.value)} | ||
/> | ||
); | ||
}; | ||
``` | ||
|
||
## useMaruUpdater - easily fetch data and update state | ||
``` | ||
useMaruUpdater(key: string, updater: () => Promise<T>, dependencies: any[]) | ||
``` | ||
|
||
```tsx | ||
import { useMaru, useMaruUpdater } from "maru-js"; | ||
|
||
// define async fetcher function | ||
const fetcher = async (id: number) => { | ||
const res = await fetch(`https://maru-api-test.com/count/${id}`); | ||
const { count } = await res.json(); | ||
return count; | ||
}; | ||
|
||
const CounterA = () => { | ||
const [id, setId] = useMaru("id"); | ||
const [count, setCount] = useMaru("count"); | ||
// updater is re-called if dependency changes | ||
useMaruUpdater("count", () => fetcher(id), [id]); | ||
|
||
return ( | ||
<button type="button" onClick={() => setId(id + 1)}> | ||
A: {count} | ||
</button> | ||
); | ||
}; | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
module.exports = { | ||
preset: "ts-jest", | ||
testEnvironment: "node", | ||
globals: { | ||
window: {}, | ||
}, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
import { DependencyList, useCallback, useEffect, useState } from "react"; | ||
|
||
import { Store, InitialData, UseMaruReturn, Maru, MaruUpdater } from "./types"; | ||
import { isServerSide } from "./utils"; | ||
|
||
const store: Store = {}; | ||
|
||
let initialized = false; | ||
|
||
export const useMaruInit = (initialData: InitialData): void => { | ||
const [mount, setMount] = useState(false); | ||
|
||
useEffect(() => { | ||
if (mount) { | ||
return; | ||
} | ||
if (initialized) { | ||
throw "You called 'useMaruInit' more than once."; | ||
} | ||
initialized = true; | ||
setMount(true); | ||
}, [mount]); | ||
|
||
if (!mount) { | ||
if (isServerSide()) { | ||
return; | ||
} | ||
Object.keys(initialData).forEach((key) => { | ||
store[key] = { value: initialData[key], triggers: {} }; | ||
return; | ||
}); | ||
} | ||
}; | ||
|
||
export const useMaru = <T>(key: string): UseMaruReturn<T> => { | ||
const [id] = useState(Math.floor(Math.random() * 100000000000).toString()); | ||
const [shouldUpdate, setShouldUpdate] = useState(false); | ||
|
||
useEffect(() => { | ||
if (shouldUpdate) { | ||
setShouldUpdate(false); | ||
} | ||
}, [shouldUpdate]); | ||
|
||
useEffect(() => { | ||
return () => { | ||
delete store[key].triggers[id]; | ||
}; | ||
}, [key, id]); | ||
|
||
const maru = store[key] as Maru<T>; | ||
|
||
const setMaruState = useCallback( | ||
(value: T) => { | ||
maru.value = value; | ||
const { triggers } = maru; | ||
setTimeout(() => { | ||
Object.keys(triggers).forEach((triggerId) => triggers[triggerId]()); | ||
}, 0); | ||
}, | ||
[maru] | ||
); | ||
|
||
if (isServerSide()) { | ||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment | ||
// @ts-ignore for serverside | ||
return [undefined, undefined]; | ||
} | ||
if (!store[key]) { | ||
throw `The state for key '${key}' has not been initialized.`; | ||
} | ||
|
||
if (!maru.triggers[id]) { | ||
maru.triggers[id] = () => { | ||
setShouldUpdate(true); | ||
}; | ||
} | ||
return [maru.value, setMaruState]; | ||
}; | ||
|
||
export const useMaruUpdater = <T>( | ||
key: string, | ||
updater: MaruUpdater<T>, | ||
dependencies: DependencyList | ||
): void => { | ||
const maru = store[key] as Maru<T>; | ||
if (maru === undefined) { | ||
throw `The state for key '${key}' has not been initialized.`; | ||
} | ||
useEffect(() => { | ||
(async () => { | ||
const data = await updater(); | ||
maru.value = data; | ||
const { triggers } = maru; | ||
setTimeout(() => { | ||
Object.keys(triggers).forEach((triggerId) => triggers[triggerId]()); | ||
}, 0); | ||
})(); | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, dependencies); | ||
}; | ||
|
||
// for testing purpose | ||
export const clearStore = (): void => { | ||
Object.keys(store).forEach((key) => delete store[key]); | ||
initialized = false; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
type Trigger = () => void; | ||
export interface Store { | ||
[key: string]: Maru; | ||
} | ||
|
||
export interface Maru<T = any> { | ||
value: T; | ||
triggers: { | ||
[id: string]: Trigger; | ||
}; | ||
} | ||
|
||
export interface InitialData<T = any> { | ||
[key: string]: T; | ||
} | ||
|
||
export type UseMaruReturn<T> = [T, (value: T) => void]; | ||
|
||
export type MaruUpdater<T> = () => Promise<T>; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
export const isServerSide = (): boolean => { | ||
return typeof window === "undefined"; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
{ | ||
"name": "maru-js", | ||
"version": "1.0.0", | ||
"description": "A minimal global state management library for React", | ||
"main": "dist/index.js", | ||
"types": "dist/index.d.ts", | ||
"scripts": { | ||
"prepare": "yarn build", | ||
"build": "tsc", | ||
"test": "jest" | ||
}, | ||
"author": "Jiseop Han <jshan2017@gmail.com>", | ||
"license": "MIT", | ||
"repository": { | ||
"type": "git", | ||
"url": "git+https://github.com/jshan2017/maru-js.git" | ||
}, | ||
"devDependencies": { | ||
"@testing-library/react-hooks": "^5.1.0", | ||
"@types/deep-equal": "^1.0.1", | ||
"@types/jest": "^26.0.20", | ||
"@types/react": "^17.0.2", | ||
"@typescript-eslint/eslint-plugin": "^4.16.1", | ||
"@typescript-eslint/parser": "^4.16.1", | ||
"eslint": "^7.21.0", | ||
"eslint-plugin-react-hooks": "^4.2.0", | ||
"jest": "^26.6.3", | ||
"react": ">=16.13.1", | ||
"react-test-renderer": "^17.0.1", | ||
"ts-jest": "^26.5.2", | ||
"typescript": "^4.2.2" | ||
}, | ||
"dependencies": {}, | ||
"peerDependencies": { | ||
"react": ">=16.13.1" | ||
}, | ||
"files": [ | ||
"dist", | ||
"lib", | ||
"README.md" | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import { renderHook } from "@testing-library/react-hooks"; | ||
import { clearStore, useMaru, useMaruInit } from "../lib"; | ||
|
||
describe("useMaru", () => { | ||
afterEach(() => clearStore()); | ||
|
||
test("should be initialized", () => { | ||
renderHook(() => useMaruInit({ count: 0 })); | ||
const { result } = renderHook(() => useMaru("count")); | ||
expect(result.current[0]).toBe(0); | ||
}); | ||
|
||
test("should throw on multiple initialization", () => { | ||
renderHook(() => useMaruInit({ count: 0 })); | ||
const { result } = renderHook(() => useMaruInit({ count: 0 })); | ||
expect(result.error).toEqual("You called 'useMaruInit' more than once."); | ||
}); | ||
|
||
test("should be updated on setState", async () => { | ||
renderHook(() => useMaruInit({ count: 0 })); | ||
const { result, waitForNextUpdate } = renderHook(() => useMaru("count")); | ||
|
||
result.current[1](1); | ||
await waitForNextUpdate(); | ||
|
||
expect(result.current[0]).toBe(1); | ||
}); | ||
|
||
test("should return same initialValue", () => { | ||
renderHook(() => useMaruInit({ count: 0 })); | ||
const { result: resultA } = renderHook(() => useMaru("count")); | ||
const { result: resultB } = renderHook(() => useMaru("count")); | ||
|
||
expect(resultB.current[0]).toEqual(resultA.current[0]); | ||
}); | ||
|
||
test("should update other components on setState", async () => { | ||
renderHook(() => useMaruInit({ count: 0 })); | ||
const { result: resultA } = renderHook(() => useMaru("count")); | ||
const { | ||
result: resultB, | ||
waitForNextUpdate: waitForNextUpdateB, | ||
} = renderHook(() => useMaru("count")); | ||
|
||
resultA.current[1](1); | ||
await waitForNextUpdateB(); | ||
|
||
expect(resultB.current[0]).toBe(1); | ||
}); | ||
}); |
Oops, something went wrong.