V
V
Vann Damm2021-05-27 11:40:12
React
Vann Damm, 2021-05-27 11:40:12

How to initialize redux-store with data like mobx example?

How to initialize the redux store with data, as it was done in this example on mobx, so that at the first render, global listeners were already added, some calculations were made, work with cookies, etc.
Implementation example on mobx:

import './styles/global.scss';

import { hydrate } from 'react-dom';
import { loadableReady } from '@loadable/component';

import { App } from 'components/App';
import { TypeStore } from 'models';
import { StoreRoot } from 'store';
import { initAutorun } from 'autorun';
import { StoreGetters } from 'getters';
import { StoreContext } from 'components/StoreContext';
import { actionsCreator } from 'actionsCreator';
import { measureClient, isomorphPolyfills } from 'utils';

if (performance) {
  performance.mark('headParsed-appScriptEvalStart');
  performance.measure('headParsed-appScriptEvalStart', 'headParsed');
}

isomorphPolyfills();

const store = new StoreRoot() as TypeStore;
const getters = new StoreGetters(store);
const { api, actions, extendActions } = actionsCreator(store);
const contextProps = { store, actions, api, getters, extendActions };

Promise.resolve()
  .then(() => loadableReady())

  .then(measureClient('onStoreInitializedClient'))
  .then(() => actions.general.onStoreInitializedClient())
  .then(measureClient('onStoreInitializedClient'))

  .then(() => initAutorun(contextProps))

  .then(() =>
    hydrate(
      <StoreContext.Provider value={contextProps}>
        <App />
      </StoreContext.Provider>,
      document.getElementById('app')
    )
  );

Code example of one of the actions (actions.general.onStoreInitializedClient())
export const onStoreInitializedClient: TypeAction = ({ store, actions }) =>
  

  Promise.resolve()
    .then(() => mergeObservableDeep(store, unescapeAllStrings(window.INITIAL_DATA)))
    .then(() => actions.general.setScreenSize())
    .then(() => actions.general.setScreenSize())
    .then(() => {
      window.addEventListener('popstate', () => actions.general.redirectTo({}));
      window.addEventListener('resize', () => actions.general.setScreenSize());
      window.addEventListener('load', function onLoad() {
        const currentRoute = toJS(store.router.currentRoute);

        printMeasures({ currentRoute });

        store.ui.firstRendered = true;
      });
    });

Thanks in advance!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question