Created
February 3, 2017 14:13
-
-
Save 2color/ae3255fdc5f82e169729ea8f7c76072e to your computer and use it in GitHub Desktop.
redux-observable sessionStorage epic example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Observable } from 'rxjs' | |
import 'rxjs/add/observable/of' | |
import 'rxjs/add/operator/map' | |
import 'rxjs/add/operator/merge' | |
import { createAction } from 'redux-actions' | |
export const SESSION_STORAGE_KEY = 'SESSION_STORAGE_KEY' | |
export const GET_SESSION_REQUESTED = 'payout/GET_SESSION_REQUESTED' | |
export const GET_SESSION_FOUND = 'payout/GET_SESSION_FOUND' | |
export const SET_SESSION = 'payout/SET_SESSION' | |
export const SET_SESSION_SUCCEEDED = 'payout/SET_SESSION_SUCCEEDED' | |
export const getSession = createAction(GET_SESSION_REQUESTED) | |
export const getSessionFound = createAction(GET_SESSION_FOUND) | |
export const setSession = createAction(SET_SESSION) | |
export const setSessionSucceeded = createAction(SET_SESSION_SUCCEEDED) | |
export const getSessionEpic = (action$, store) => { | |
return action$.ofType(GET_SESSION_REQUESTED) | |
.switchMap(action => { | |
/* eslint-env browser */ | |
const sessionString = sessionStorage.getItem(SESSION_STORAGE_KEY) | |
let session | |
try { | |
session = JSON.parse(sessionString) | |
} catch (e) { | |
console.error(e) | |
} | |
// Dispatch session found only if session isn't empty(null) | |
return Observable.of(getSessionFound(session)).filter(() => session !== null) | |
}) | |
} | |
export const setSessionEpic = (action$, store) => { | |
return action$.ofType(SET_SESSION) | |
.switchMap(action => { | |
const session = JSON.stringify(action.payload) | |
/* eslint-env browser */ | |
sessionStorage.setItem(SESSION_STORAGE_KEY, session) | |
// Dispatch session found only if session isn't empty(null) | |
return Observable.of(setSessionSucceeded(action.payload)) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment