Skip to content

Instantly share code, notes, and snippets.

@2color

2color/session.js

Created Feb 3, 2017
Embed
What would you like to do?
redux-observable sessionStorage epic example
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
You can’t perform that action at this time.