react-storio
v0.0.1
Published
State-management library for React
Maintainers
Readme
React-Storio
React state management library.
How to use
- Create new store instance
const store = createStore({
...initState,
...actions,
...effects,
...entities,
sliceA,
sliceB,
});- Create new slice
const sliceA = {
// init state
key: 'value',
otherKey: { counter: 0 },
// actions
setValue,
// effects
sendApiRequest,
// entities
api,
// slices
};- Create action
export const setValue = action(({ store, slice, payload }) => {
slice.key = 'new-value';
store.otherKey.counter = payload.counter;
});- Create effect
export const sendApiRequest = effect(async ({ store, slice, payload }) => {
const { newCounter } = payload;
const [api] = slice.getEntities((slice) => slice.api);
const setValue = store.getActions((store) => store.sliceA.setValue);
try {
const responce = await api.sendRequest(newCounter);
setValue({ counter: responce });
} catch (e) {
console.log(e);
}
});- Create entity
const createApi = () => {
const innerState = {};
const sendRequest = async (formValues) => {
const responce = await fetch('some reqeust');
return responce;
};
return {
sendRequest,
};
};
export const api = entity(async ({ store, slice, payload }) => {
const api = createApi();
return api;
});- Connect store to React
<StoreProvider store={store}>
<App />
</StoreProvider>- Use in the component
export const Component = () => {
const counter = useStoreState((store) => store.otherKey.counter);
const sendApiRequest = useStoreEffect((store) => store.sendApiRequest);
const onClick = () => {
sendApiRequest({ newCounter: counter + 1 });
};
return (
<div>
<p>{counter}</p>
<button onClick={onClick}>Click</button>
</div>
);
};Future Features
- Passing an array of selectors into hooks / effects like store.getWhatever
- Remove spread operators from slices. This will allow having effects, actions, and entities with the same name.
- Add useSliceState / useSliceActions…
- Add reset store / slice
