Micro frontend (2) – How to share redux state?

Method 1

  • Use 1 global shared store between micro frontends
  • Use injectReducer to register each micro frontend reducer into the that store
  • Reference

redux-reducer-injection

Method 2

Use redux-micro-frontend

Install

yarn add redux-micro-frontend

Usage

// App1
import { GlobalStore } from 'redux-micro-frontend';

const ProviderApp1 = ({ children }) => {

  const globalStore = GlobalStore.Get();
  globalStore.RegisterStore('App1', store, [GlobalStore.AllowAll]);

  return (
    <ReduxProvider store={store}>
      <ThemeProvider theme={theme}>{children}</ThemeProvider>
    </ReduxProvider>
  );
};

export default ProviderApp1;
// App2
import { GlobalStore } from 'redux-micro-frontend';

const App2 = () => {

  const globalStore = GlobalStore.Get()
  const app1State = globalStore.GetGlobalState('App1')

  return ...
}

APIs

Register store to global store

// App1
globalStore.RegisterStore('App1', store, [GlobalStore.AllowAll]);

Register actions to global store

globalStore.RegisterGlobalActions("App1", ["Action-1", "Action-2"]);

Get global state

// App2
globalStore.SubscribeToGlobalState('App1', (globalStateChanged) => {
  console.log(globalStateChanged)
})

Dispatch action

// App2
let action = {
    type: 'Action-1',
    payload: 'Some data'
}
this.globalStore.DispatchAction("App1", action); 
// This will dispatch the action to current app's store as well other stores who might have registered 'Action-1' as a global action

Be the first to comment

Leave a Reply

Your email address will not be published.


*