0

I am building a multilingual website and need to display currently selected language in URL query params (not only the language but for the sake of KISS I will consider only this).

I'm using react-intl for website translation as well as store currently selected language in redux.

Here's how my current router (HashRouter) looks:

  return (
    <div className="App">
      <Provider store={store}>
        <Router hashType="noslash">
          <Content />
        </Router>
      </Provider>
    </div>
  );
}

let Content = connect(state => ({ language: state.common.language }))(props => {
  const lang = props.language;

  return (
    <IntlProvider locale={lang} messages={messages[lang]}>
      <Switch>
        <Route path='/station_forecasts'>
          <StationForecastsPage />
        </Route>
        <Route path="/">
          <Redirect
            to={{
              pathname: "/station_forecasts",
              search: "?sid=76"
            }}
          />
        </Route>
      </Switch>
    </IntlProvider>
  );
});

My current approach is adding the following lines to StationForecastsPage component:

  useEffect(() => {
    history.push({
      pathname: `${window.location.href}`,
      search: `?lang=${lang}`
    });
  });

where lang is language code taken from redux store. However, it results into infinite loop and React throws a maximal depth exceeded error.

I could as well use window.location.href trick but it would cause a page refresh which apparently doesn't work for me.

My question is what is the best way to implement aforementioned query params update?

John Nash
  • 127
  • 6

1 Answers1

0

You are missing the dependencies of the useEffect, should work if you add history as a dependency of the useEffect:

useEffect(() => {
  history.push({
    pathname: `${window.location.href}`,
    search: `?lang=${lang}`
  })
}, [history]);

Now it will only run when history changes.