React Redux Router Intl keep locale synced between intl state and router state

757 views Asked by At

I have an app using React, Redux, React-Router and Intl (also react-intl, react-intl-redux, react-router-redux, react-redux). The basic setup, nothing fancy, I guess.

<Provider store={store}>
  <IntlProvider>
    <Router history={history}>
      <Route path="/:language" component={App}>
        ...
      </Route>
    </Router>
  </IntlProvider>
</Provider>

import { intlReducer } from 'react-intl-redux';
import { routerReducer } from 'react-router-redux';

const rootReducer = combineReducers({
  routing: routerReducer,
  intl: intlReducer,
  ...
});

(language = locale here) In the header, I have a dropdown from which you can control the language of the app. The url of the app also contains info about the current language.

If the url is http://example.com/en/post the header language menu has en as the selected option.

Whenever I change the dropdown value, both the url and header menu should change accordingly.

The reverse should also be available: navigating or simply opening a page at a certain path (also having the language included) would be reflected in the intl state.

Normally I would do it like this:

  • for the url change I use dispatch(push('/{newLanguage}/...

  • for the intl state change I use dispatch(updateIntl({ locale, messages })) - the action creator updateIntl is provided by react-intl-redux

But triggering these 2 actions would not be viable for my app, since it would trigger 2 state changes which would generate 2 renders (+some api interactions)

The question is how do I trigger only one action in order to have both the intl state and the router state in sync? Or if maybe I'm wrong about one action solving this issue, then what would an elegant solution be?


possible solution: create an action CHANGE_LANGUAGE and rewrite both intlReducer and routerReducer to adjust the state when it is triggered?

0

There are 0 answers