0.0.26 • Published 4 months ago

global-state-manager v0.0.26

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

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

4 months ago

0.0.26

4 months ago

0.0.24

4 months ago

0.0.21

4 months ago

0.0.22

4 months ago

0.0.23

4 months ago

0.0.20

5 months ago

0.0.17

5 months ago

0.0.18

5 months ago

0.0.19

5 months ago

0.0.15

5 months ago

0.0.16

5 months ago

0.0.14

5 months ago

0.0.13

5 months ago

0.0.12

5 months ago

0.0.11

5 months ago

0.0.10

5 months ago

0.0.9

5 months ago

0.0.8

5 months ago

0.0.7

5 months ago

0.0.6

5 months ago

0.0.5

5 months ago

0.0.4

5 months ago

0.0.3

5 months ago

0.0.2

5 months ago

0.0.1

5 months ago