How to get the params from react-router v4 into my redux-store


November 2018


623 time


We previously added all the routing params into the redux-store running v2 of react-router. This is referenced troughout our application, and changing the use of it contains to much of a risk. We are aiming at upgrading to v4, and i am looking for a way to sync the params into the store.

Previously, we used a match-check from react-router, to do this, just tapping into the react-redux-router action dispatched when the location changed. From what i can see in the react-router docs, there is still a function that can do path-matching.

Given routing like:

<Route path="/foo/:id/:id2" render={() => <div />} />

I tried something like this in my reducer:

import {matchPath} from 'react-router';

const initialState = {};

export default function(state = initialState, action){
    case "@@router/LOCATION_CHANGE": {
      const {pathname} = action.payload.location;
      return {...state, params: matchPath(pathname).params}
    case default: return state;

This didnt work at all, since it seems like the matchPath function actually doesnt run trough all registered routes, it just matches whatever route you put in, with whatever else route you put in as a second param. So ex:

const pathname = '/foo/1/2';
const findRoute = matchPath(pathname, {exact: true, path: '/foo/:id/:id2'});
//would return {..., params: {id: 1, id2: 2}};

This doesnt help me though, since i dont know which route it matched with in the first place, only which location i am currently on. Has anyone else found a good solution for this? Is there a way of getting all routes registered in react-redux v4, then i could just traverse through them to find the matching.

0 answers