Shota Shota - 1 year ago 212
React JSX Question

React/Redux - dispatch action on app load/init

I have token authentication from a server, so when my Redux app is loaded initially I need make a request to this server to check whether user is authenticated or not, and if yes I should get token.

I have found that using Redux core INIT actions is not recommended, so how can I dispatch an action, before app is rendered?

Answer Source

I solved this problem using react-router onEnter props. This is how code looks like:

// this function is called only once, before application is initially starts to render routing
// it can be used to add init config settings to the application
function onAppInit(dispatch) {
  return (nextState, replace, callback) => {
      .then(() => {
        // callback is like a "next" function, app initialization is stopped until it is called.

const App = () => (
  <Provider store={store}>
    <IntlProvider locale={language} messages={messages}>
        <Router history={history}>
          <Route path="/" component={MainLayout} onEnter={onAppInit(store.dispatch)}>
            <IndexRoute component={HomePage} />
            <Route path="about" component={AboutPage} />