Skip to content

Commit

Permalink
Add capability to overwrite session storage key
Browse files Browse the repository at this point in the history
  • Loading branch information
fum4 committed Feb 8, 2023
1 parent 5ea57df commit ca7ecff
Show file tree
Hide file tree
Showing 7 changed files with 41 additions and 26 deletions.
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,15 @@ Pass the `history` object as an argument to `configureRouterHistory`. The return

```javascript
// store.js
import { configureRouterHistory } from 'react-router-redux-history'
import { configureRouterHistory } from 'react-redux-history'

const { routerReducer, routerMiddleware } = configureRouterHistory(history)
// optional, defaults are listed below
const options = {
// what key to use for session storage entry
storageKey: 'routerState'
}

const { routerReducer, routerMiddleware } = configureRouterHistory(history, options)
```

<br>
Expand Down
4 changes: 2 additions & 2 deletions src/LocationListener.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { useLayoutEffect } from 'react';
import { useDispatch } from 'react-redux';
import type { BrowserHistory, Update } from 'history';
import type { History, Update } from 'history';

import { LOCATION_CHANGE, type LocationListenerProps } from './types';

export const useLocationListener = (history: BrowserHistory) => {
export const useLocationListener = (history: History) => {
const dispatch = useDispatch();

useLayoutEffect(() => {
Expand Down
5 changes: 3 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import type { History } from 'history';

import createRouterMiddleware from './middleware';
import createRouterSlice from './slice';
import type { Options } from './types';

export const configureRouterHistory = (history: History) => {
const { routerReducer, routerActions } = createRouterSlice(history);
export const configureRouterHistory = (history: History, { storageKey = 'routerState' } = {} as Partial<Options>) => {
const { routerReducer, routerActions } = createRouterSlice(history, { storageKey });
const routerMiddleware = createRouterMiddleware(history, routerActions);

return {
Expand Down
10 changes: 5 additions & 5 deletions src/initialState.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { BrowserHistory } from 'history';
import type { History } from 'history';

import { persistOnPageHide, getSessionState } from './persist';
import { ActionTypes, type AppRouterState } from './types';
import { ActionTypes, type AppRouterState, type Options } from './types';

import {
parseLocation,
Expand All @@ -10,7 +10,7 @@ import {
isNextRoute
} from './helpers'

const getInitialState = (history: BrowserHistory): AppRouterState => {
const getInitialState = (history: History, { storageKey }: Options): AppRouterState => {
const location = parseLocation(history.location);
const defaultState: AppRouterState = {
action: ActionTypes.Push,
Expand All @@ -19,7 +19,7 @@ const getInitialState = (history: BrowserHistory): AppRouterState => {
isSkipping: false,
};

const sessionRouterState = getSessionState();
const sessionRouterState = getSessionState(storageKey);
const initialState = sessionRouterState || defaultState;

if (sessionRouterState) {
Expand Down Expand Up @@ -50,7 +50,7 @@ const getInitialState = (history: BrowserHistory): AppRouterState => {
initialState.isSkipping = false;
}

persistOnPageHide(initialState);
persistOnPageHide(initialState, { storageKey });

return initialState;
};
Expand Down
14 changes: 8 additions & 6 deletions src/persist.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import type { AppRouterState } from './types';
import type { AppRouterState, Options } from './types';

let pageHideListener;

const saveToSessionStorage = (state: Readonly<AppRouterState>): void => sessionStorage.setItem('routerState', JSON.stringify(state));
const saveToSessionStorage = (state: Readonly<AppRouterState>, { storageKey }: Options) => {
sessionStorage.setItem(storageKey, JSON.stringify(state));
};

export const persistOnPageHide = (state: Readonly<AppRouterState>): void => {
export const persistOnPageHide = (state: Readonly<AppRouterState>, { storageKey }: Options) => {
if (pageHideListener) {
window.removeEventListener('pagehide', pageHideListener);
}

pageHideListener = () => saveToSessionStorage(state);
pageHideListener = () => saveToSessionStorage(state, { storageKey });
window.addEventListener('pagehide', pageHideListener, { once: true });
};

export const getSessionState = (): AppRouterState => {
export const getSessionState = (storageKey: string): AppRouterState => {
let sessionRouterState: AppRouterState;

try {
const serializedSessionRouterState = sessionStorage.getItem('routerState');
const serializedSessionRouterState = sessionStorage.getItem(storageKey);

sessionRouterState = serializedSessionRouterState && JSON.parse(serializedSessionRouterState);

Expand Down
16 changes: 9 additions & 7 deletions src/slice.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createSlice, current, type PayloadAction } from '@reduxjs/toolkit';
import type { History } from 'history';

import getInitialState from './initialState';
import { persistOnPageHide } from './persist';
Expand All @@ -8,13 +9,14 @@ import {
type AppRouterState,
type LocationChangeAction,
type LocationChangePayload,
type Options,
ActionTypes
} from './types';

const createRouterSlice = (history) => {
const createRouterSlice = (history: History, { storageKey }: Options) => {
const routerSlice = createSlice({
name: 'router',
initialState: getInitialState(history),
initialState: getInitialState(history, { storageKey }),
reducers: {
push: (state: AppRouterState, action: LocationChangeAction) => {
const newLocation = parseLocation(action.payload.location);
Expand All @@ -23,7 +25,7 @@ const createRouterSlice = (history) => {
state.action = ActionTypes.Push;
state.locationHistory.splice(state.currentIndex, state.locationHistory.length, newLocation);

persistOnPageHide(current(state));
persistOnPageHide(current(state), { storageKey });
},
replace: (state: AppRouterState, action: LocationChangeAction) => {
const newLocation = parseLocation(action.payload.location);
Expand All @@ -43,7 +45,7 @@ const createRouterSlice = (history) => {

delete state.locationHistory[state.currentIndex].state.forceRender;

persistOnPageHide(current(state));
persistOnPageHide(current(state), { storageKey });
},
back: (state: AppRouterState, action: PayloadAction<LocationChangePayload>) => {
const { nextLocationIndex, isSkipping = false } = action.payload;
Expand All @@ -67,7 +69,7 @@ const createRouterSlice = (history) => {

delete state.locationHistory[nextLocationIndex].state.forceRender;

persistOnPageHide(current(state));
persistOnPageHide(current(state), { storageKey });
},
forward: (state: AppRouterState, action: PayloadAction<LocationChangePayload>) => {
const { nextLocationIndex, isSkipping = false } = action.payload;
Expand All @@ -91,12 +93,12 @@ const createRouterSlice = (history) => {

delete state.locationHistory[nextLocationIndex].state.forceRender;

persistOnPageHide(current(state));
persistOnPageHide(current(state), { storageKey });
},
setSkipping: (state: AppRouterState, action: PayloadAction<boolean>) => {
state.isSkipping = action.payload;

persistOnPageHide(current(state));
persistOnPageHide(current(state), { storageKey });
},
},
});
Expand Down
8 changes: 6 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { NavigateFunction } from 'react-router';
import type { CaseReducerActions, PayloadAction } from '@reduxjs/toolkit';
import type { BrowserHistory, Action, Location, Update, History } from 'history';
import type { Action, Location, Update, History } from 'history';

export enum ActionTypes {
Push = 'PUSH',
Expand Down Expand Up @@ -64,7 +64,7 @@ export type SliceActions = CaseReducerActions<{
}, 'router'>

export interface LocationListenerProps {
history: BrowserHistory;
history: History;
}

export type NavigateAwayCallback = ({ action, nextLocation }: NavigateAwayCallbackParams) => void;
Expand All @@ -79,3 +79,7 @@ export interface NavigateAwayProps {
callback: NavigateAwayCallback;
history: History;
}

export interface Options {
storageKey: string;
}

0 comments on commit ca7ecff

Please sign in to comment.