Map a route parameter to under a Redux store's key
Asked Answered
F

2

0

There is a "location" key in the state object which is used by multiple components as data source. In the URL (very similar to google maps) I have a parameter called "location" which is a coordinate. My goal is to map that value (with some modification) to the state's "location" key. How to do that?

UPDATE The only way I could imagine is to create a middleware and react to route actions, extract the parameters from the URL somehow, then dispatch a new action that will be processed by a reducer. Or just use a reducer, not necessary having an extra middleware. But I guess this is not a good approach...

Filibertofilibuster answered 1/7, 2016 at 12:20 Comment(0)
P
2

You can get location variable params from onEnter callback of your route, and then dispatch action to store.

See example above:

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import App from './App';
import { Route, Router, browserHistory } from 'react-router';

const store = createStore(rootReducer);

const routes = (
  <Route
    path="/location/:location"
    component={App}
    onEnter={handleEnter}
  />
);

function rootReducer(state = {
  location: {},
}, action) {
  switch (action.type) {
    case 'ADD_TO_LOCATION':
      return {
        ...state,
        location: action.location,
      };
    default:
      return state;
  }
  return state;
}

function handleEnter(nextState) {
  // Map location data here.
  // Next, we are dispatching mapped location to store.
  store.dispatch({
    type: 'ADD_TO_LOCATION',
    location: nextState.params.location,
  });
}

ReactDOM.render(<Router routes={routes} history={browserHistory} />, document.getElementById('root'));
Petrochemistry answered 1/7, 2016 at 13:56 Comment(0)
M
-1

I've created container for the root route which takes router params on componentWillReceiveProps event and dispatch them to the store if window.location.href doesn't much previous state. You can see the code on github repo. I use redux-saga. Therefore it's better for me just to listen to my custom event: @@routerParams/URL_UPDATE and take all params from action.payload.

Midsummer answered 26/1, 2017 at 16:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.