supasate / connected-react-router

A Redux binding for React Router v4
MIT License
4.73k stars 593 forks source link

How to use LOCATION_CHANGE in reducer with TypeScript? #118

Open benneq opened 6 years ago

benneq commented 6 years ago

I have some simple reducer and want to use LOCATION_CHANGE. But I can't find a matching ActionType:

import { Reducer } from 'redux';
import { LOCATION_CHANGE } from 'connected-react-router';

const myReducer: Reducer<MyState, MyActions> = (state = initialState, action): MyState => {
    switch (action.type) {
        case ...:
            return ...;

        case LOCATION_CHANGE:
            return {
                ...state,
                someStateProperty: false
            }
      default:
        return state;
    }
}

Maybe it could be useful if you add some LocationChangeAction?

interface LocationChangeAction {
  type: typeof LOCATION_CHANGE
  payload: // ?
}

Or how is it supposed to be used?

At the moment I'm doing this:

export const reducer: Reducer<LayoutState, Actions | { type: typeof LOCATION_CHANGE, payload: any }> = (state = initialState, { type, payload }) => {
  ...
}
aenciso commented 6 years ago

Exactly how you have it on your reducer

import { LOCATION_CHANGE } from 'connected-react-router';

then e.g

case LOCATION_CHANGE: const { pathname } = action.payload.location; ...

benneq commented 6 years ago

But why is there no LocationChangeAction? Then I could simply write:

const reducer: Reducer<MyState, MyActions | LocationChangeAction> = (state = initialState, action) => {

Or maybe some kind of RouterActions which combines all action types from the router:

const reducer: Reducer<MyState, MyActions | RouterActions> = (state = initialState, action) => {
aenciso commented 6 years ago

Actions are implemented by connected-react-router internally but they're not accessible from the outside. What you can do is subscribe to the store and check for that type of action or if you are using sagas you can take all LOCATION_CHANGE events and dispatch actions from there.

benneq commented 6 years ago

I guess it would still be nice, if you could expose the corresponding Actions :)

duvet86 commented 6 years ago

This is what I'm doing:

interface ILocationChangeAction extends Action {
  type: typeof LOCATION_CHANGE;
  payload: RouterState;
}

But it would be nice to have it out of the box.

rboughani commented 5 years ago

until now, I can not recover on each of my pages the location_change

is there a simple tutorial, which explains how to get the current url, and the previous url using LOCATION_CHANGE in each pages of my application ?