$ npm install --save sagen
$ yarn add sagen
sagen is a state management library that uses a combination of individual repositories without root repositories.
You can create a store
to manage the state. The store offers the following features:
-Detect changes in status when used in React -Combine multiple repositories to create one repository -Store management standardized with reducer and pattern -Store state comparison operation is managed to minimize the operation of unused state
You can display values that are not functions in store
.
import { createStore } from 'sagen';
const numberStore = createStore(0);
const multipleStore = createStore({ num: 0, str: '' });
The createStore
function returns getState
,setState
functions.
In React, you can use useGlobalStore
, useSagenState
, and useSetSagenState
to manage values.
The useGlobalStore
Hook returns getter
and setter
as an array.
The usage method is the same as the React.useState
Hook.
Changes from other configurations can be received as getter
.
import { createStore, useGlobalStore } from 'sagen';
const store = createStore(0);
function Test() {
const [num, setNum] = useGlobalStore(store);
const incrementNum = () => {
setNum(curr => curr + 1);
};
return (
<div>
<p>num: {num}</p>
<button onClick={incrementNum}>
Increment
</button>
</div>
);
}
useSagenState
Hook returns getter
of store
.
import { createStore, useSagenState } from 'sagen';
const store = createStore(0);
function Test() {
const num = useSagenState(store);
return (
<p>num: {num}</p>
);
}
useSetSagenState
Hook returns setter
of store
.
import { createStore, useSetSagenState } from 'sagen';
const store = createStore(0);
function Test() {
const setNum = useSagenState(store);
const incrementNum = () => {
setNum(curr => curr + 1);
};
return (
<button onClick={incrementNum}>
Increment
</button>
);
}
You can add arguments to useGlobalStore
and useSagenState
that return getter
.
This is used for performance optimization.
You can pass selector
to useGlobalStore
and useSagenState
.
This is mainly used for object stores, and allows you to subscribe only to the desired value of the object values.
The subscribed value only affects getter
, and setter
has information about the original value.
Since sagen operates only on the values that the component subscribes to,
it is not recommended to subscribe to values that are not being used.
import { createStore, useGlobalStore } from 'sagen';
const infoStore = createStore({
name: 'jungpaeng',
age: 22,
});
const ageSelector = store => store.age;
function Test() {
// Pass the ageSelector as the component uses only the age value.
const [age, setInfo] = useGlobalStore(infoStore, ageSelector);
const incrementAge = () => {
setInfo(curr => ({ ...curr, age: curr.age + 1 }));
};
return (
<div>
<p>age: {age}</p>
<button onClick={incrementAge}>
Increment
</button>
</div>
);
}
You can pass equalityFn
to useGlobalStore
and useSagenState
.
Used to detect if a component's subscribed value has changed.
Basically, ===
is used to compare, and shallowEqual
is provided for comparing arrays, objects, etc.
import { createStore, useGlobalStore, shallowEqual } from 'sagen';
const infoStore = createStore({
name: 'jungpaeng',
use: 'typescript',
age: 22,
});
const selector = store => ({ name: store.name, age: store.age });
function Test() {
// Even if the unsubscribed use value changes, the component does not react.
const [info, setInfo] = useGlobalStore(infoStore, selector, shallowEqual);
const incrementAge = () => {
setInfo(curr => ({ ...curr, age: curr.age + 1 }));
};
return (
<div>
<p>name: {info.name}</p>
<p>age: {info.age}</p>
<button onClick={incrementAge}>
Increment
</button>
</div>
);
}
You can manage it by adding a action
to the store
created with the createStore
function.
Before using Dispatch
, you need to define Action
.
const store = createStore(0);
const storeAction = store.setAction((getter) => ({
INCREMENT: () => getter() + 1,
ADD: (num) => getter() + num,
}));
The dispatch
function passes the value created through action
as an argument.
const store = createStore(0);
const storeDispatch = createDispatch(store);
const storeAction = store.setAction((getter) => ({
INCREMENT: () => getter() + 1,
ADD: (num) => getter() + num,
}));
storeDispatch(storeAction.INCREMENT)
storeDispatch(storeAction.ADD, 100)
sagen is compatible with Redux middleware.
Here is a simple logger middleware.
You can combine multiple middleware
using composeMiddleware
,
and pass it to the second argument of createStore
.
import { createStore, composeMiddleware } from 'sagen';
const loggerMiddleware = store => next => action => {
console.log('Current state', store.getState());
console.log('Action', action);
next(action);
console.log('Next state', store.getState());
}
const store = createStore(0, composeMiddleware(loggerMiddleware));
// In Component ...
const [state, setState] = useGlobalStore(store);
setState(1);
console log
Current state, 0
Action, 1
Next state, 1
You can trigger an event when an update occurs.
This event cannot affect the state value.
import { createStore } from 'sagen';
const store = createStore(0);
// Returns a function that unsubscribes from event.
const removeEvent = store.onSubscribe((newState, prevState) => {
console.log(`prev: ${prevState}, new: ${newState}`);
});
// In Component ...
const [state, setState] = useGlobalStore(store);
setState(1);
// [console.log] prev: 0, new: 1
removeEvent();
setState(0);
// [console.log] Empty
Multiple stores' can be combined and managed as a single
store`.
If you wish, you can also create and manage a single Root Store.
With composeStore
, you can group store
into a single store
.
The integrated store is in a state of subscribing to the original store.
Changing values in one store affects values in other stores.
import { createStore, composeStore, useGlobalStore } from 'sagen';
const numStoreA = createStore(0);
const numStoreB = createStore(0);
const { store: numStoreAB } = composeStore({
a: numStoreA,
b: numStoreB,
});
function Test() {
const [store, setStore] = useGlobalStore(store);
const incrementA = () => {
setStore(curr => ({
...curr,
a: curr.a + 1,
}));
};
const incrementB = () => {
setStore(curr => ({
...curr,
b: curr.b + 1,
}));
};
return (
<div>
<p>A num: {store.a}</p>
<button onClick={incrementA}>
A Increment
</button>
<p>B num: {store.b}</p>
<button onClick={incrementB}>
B Increment
</button>
</div>
);
}
sagen
can be used without React.
Try the sagen-core library.
sagen is released under the MIT license.
Copyright (c) 2020 jungpaeng
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.