Skip to content

Instantly share code, notes, and snippets.

@marcelaraujo
Forked from mksarge/actions.js
Created June 30, 2017 14:58
Show Gist options
  • Save marcelaraujo/f10fbb1d2074737f5a0fddda5b611ccc to your computer and use it in GitHub Desktop.
Save marcelaraujo/f10fbb1d2074737f5a0fddda5b611ccc to your computer and use it in GitHub Desktop.
A minimal Redux-first routing implementation in <100 lines of code. Learn more: https://medium.com/@mksarge/98926ebf53cb
import { PUSH, REPLACE, GO, GO_BACK, GO_FORWARD, LOCATION_CHANGE } from './constants';
export const push = (href) => ({
type: PUSH,
payload: href,
});
export const replace = (href) => ({
type: REPLACE,
payload: href,
});
export const go = (index) => ({
type: GO,
payload: index,
});
export const goBack = () => ({
type: GO_BACK,
});
export const goForward = () => ({
type: GO_FORWARD,
});
export const locationChange = ({ pathname, search, hash }) => ({
type: LOCATION_CHANGE,
payload: {
pathname,
search,
hash,
},
});
export const PUSH = 'ROUTER/PUSH';
export const REPLACE = 'ROUTER/REPLACE';
export const GO = 'ROUTER/GO';
export const GO_BACK = 'ROUTER/GO_BACK';
export const GO_FORWARD = 'ROUTER/GO_FORWARD';
export const LOCATION_CHANGE = 'ROUTER/LOCATION_CHANGE';
import { locationChange } from './actions';
export function startListener(history, store) {
store.dispatch(locationChange({
pathname: history.location.pathname,
search: history.location.search,
hash: history.location.hash,
}));
history.listen((location) => {
store.dispatch(locationChange({
pathname: location.pathname,
search: location.search,
hash: location.hash,
}));
});
}
import { PUSH, REPLACE, GO, GO_BACK, GO_FORWARD } from './constants';
export const routerMiddleware = (history) => () => (next) => (action) => {
switch (action.type) {
case PUSH:
history.push(action.payload);
break;
case REPLACE:
history.replace(action.payload);
break;
case GO:
history.go(action.payload);
break;
case GO_BACK:
history.goBack();
break;
case GO_FORWARD:
history.goForward();
break;
default:
return next(action);
}
};
import { LOCATION_CHANGE } from './constants';
const getInitialState = {
pathname: '/',
search: '',
hash: '',
};
export const routerReducer = (state = getInitialState, action) => {
switch (action.type) {
case LOCATION_CHANGE:
return {
...state,
...action.payload,
};
default:
return state;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment