How to bind react-router query params with mobx global state?

Viewed 1031

I'm creating a web client using create-react-app, mobx-react-lite and react-router-dom. How can i connect routes query params to mobx state?

Im using hooks, so i've tried using useEffect() hook with mobx autorun() function and wrapped my components props in useAsObservableSource() hook (just as suggested here https://mobx-react.js.org/recipes-effects ), and it works fine as long as i use simple params, but if it is an array, effect goes into infinite loop.

const Index = props => {
  const store = useStore(); // my mobx global state store
  const source = useAsObservableSource(props);

  useEffect(() => autorun(() => {
    // extracting url query params
    const params = new URLSearchParams(source.location.search);
    const tags = params.getAll('tags'); // an array ['4', '6', etc.]
    const orderBy = params.get('orderBy') || 'date'; // a string
    store.orderBy = orderBy; // works fine
    store.tags = tags; // works only first time, when open in new browser window, if query string changes, causes infinite rerenders

    store.fetchSomeData();
  }),
  []);

  return (
    <Observer>{() => (
      <div>
        // render components based on store
      </div>
    )}</Observer>
  );
};

Expect effect to only run once every time query string changes, but it runs infinite amount of times on every query string change.

0 Answers
Related