https://github.com/jinmayamashita/enclosed
https://github.com/jinmayamashita/enclosed
closures states usestate
Last synced: 8 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/jinmayamashita/enclosed
- Owner: jinmayamashita
- License: mit
- Created: 2020-02-24T11:45:32.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2022-03-26T13:51:28.000Z (about 4 years ago)
- Last Synced: 2023-10-20T21:00:16.749Z (over 2 years ago)
- Topics: closures, states, usestate
- Language: TypeScript
- Size: 9.77 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Enclosed
Enclosed is a easy way of managing your small state in plain JavaScript.
you can think of Enclosed as [`React.useState`](https://reactjs.org/docs/hooks-reference.html#usestate).
(JavaScript closures have always been a bit of a mystery to me.)
## Examples
```js
import { enclosed } from "./src/enclosed";
const [getState, setState] = enclosed(10);
getState();
// 10
setState(s => s + 10);
getState();
// 100
```
### More examples
```ts
import { enclosed } from "./src/enclosed";
type Todo = { id: number; name: string };
const [getState, setState] = enclosed([{ id: 1, name: "foo" }]);
// your custom functions
const push = (t: Todo) => setState(s => [...s, t]);
const update = (t: Todo) => setState(s => s.map(e => (t.id === e.id ? t : e)));
const remove = (id: Todo["id"]) => setState(s => s.filter(e => id !== e.id));
getState();
// [{id: 1, name: "foo"}]
push({ id: 9, name: "foo9" });
getState();
// [{id: 1, name: "foo"}, { id: 9, name: "foo9" }]
update({ id: 1, name: "boo" });
getState();
// [{id: 1, name: "boo"}, { id: 9, name: "foo9" }]
remove(9);
getState();
// [{id: 1, name: "foo"}]
```
## Todos
- [ ] Add a test spec later :pray:
- [ ] Documenting APIs