Storing Filters to URL in React and Redux App
Recently, I was tasked to store some filter options into URL in a React + Redux app. It felt pretty simple as I’ve done it many times in other frameworks without any obstacles. As I was new to React, I started with research on Google how this should be done best in the most React way. I didn’t find much, only one article that used deprecated react-router-redux and for newer versions of react-router I needed to use connected-react-router. So I decided to write some guidelines on how I solved this task.
First, let’s discuss where to place URL-related functionality. I thought I would add it to the component and listen on componentDidUpdate
event and change the URL in its handler. Similarly, I could listen on componentDidMount
to load values from the URL on initialization of the component. But I did not like this solution. What if I have multiple places where this data will be set? Why should I really care where the current state is stored in component? So the only logical place to me was to place this functionality somewhere into Redux.
As a first step, I decided to skip router and just find the relevant places where the code should be placed. Let’s look at how to store data into URL. Redux has great functionality built-in -> middlewares. What it basically does is that it triggers your specified function that has action as a parameter and once…