0.0.26 • Published 1 year ago
global-state-manager v0.0.26
global-state-manager
Global State Manager for React
Installation
npm install --save-dev global-state-manager
Usage
In React Project
In index.tsx
:
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'global-state-manager';
import { getDispatch, stateStore } from './store/Global';
import App from './App';
const root = createRoot(document.getElementById('app-root')!);
getDispatch().init();
root.render(
<Provider store={stateStore}>
<App />
</Provider>
);
In App.tsx
:
import React from "react";
import { getDispatch, useAppGlobal } from "./store/Global";
const App = () => {
const count = useAppGlobal(e => e.count);
const { setCount } = getDispatch();
const handleIncrement = () => setCount(count + 1);
const handleDecrement = () => setCount(count - 1);
console.log('>>render main')
return (
<div className="app">
<h1>state: {count}</h1>
<button onClick={handleIncrement}>+</button>
<button onClick={handleDecrement}>-</button>
</div>
);
};
export default App;
In store/Global.ts
:
import { StateStore, TypedUseSelectorHook, useGlobal } from 'global-state-manager';
export type GlobalState = {
count: number
}
export interface ActionPayloads {
init: undefined;
setCount: number;
};
const INITIAL_STATE: GlobalState = { count: 0 };
export const stateStore = StateStore<GlobalState, ActionPayloads>();
stateStore.addReducer("init", () => {
return Object.assign({}, INITIAL_STATE);
});
stateStore.addReducer("setCount", (global, _actions, payload) => {
return {
...global,
count: payload,
};
});
export const useAppGlobal: TypedUseSelectorHook<GlobalState> = useGlobal;
export const getDispatch = stateStore.getDispatch;
export const getState = stateStore.getState;
export const setState = stateStore.setState;
export const withState = stateStore.withState;
export const addReducer = stateStore.addReducer;
export const removeReducer = stateStore.removeReducer;
export const addCallback = stateStore.addCallback;
export const removeCallback = stateStore.removeCallback;
0.0.25
1 year ago
0.0.26
1 year ago
0.0.24
1 year ago
0.0.21
1 year ago
0.0.22
1 year ago
0.0.23
1 year ago
0.0.20
1 year ago
0.0.17
2 years ago
0.0.18
2 years ago
0.0.19
2 years ago
0.0.15
2 years ago
0.0.16
2 years ago
0.0.14
2 years ago
0.0.13
2 years ago
0.0.12
2 years ago
0.0.11
2 years ago
0.0.10
2 years ago
0.0.9
2 years ago
0.0.8
2 years ago
0.0.7
2 years ago
0.0.6
2 years ago
0.0.5
2 years ago
0.0.4
2 years ago
0.0.3
2 years ago
0.0.2
2 years ago
0.0.1
2 years ago