Skip to content

Instantly share code, notes, and snippets.

@cherta
Last active June 18, 2016 15:52
Show Gist options
  • Save cherta/69481bcf62182906c6122ea3b81dc459 to your computer and use it in GitHub Desktop.
Save cherta/69481bcf62182906c6122ea3b81dc459 to your computer and use it in GitHub Desktop.
Sample reducer
const initialState = {
token:: null,
tokenIsExpired: false,
errors: [],
profile:null,
loading: false
}
export default function auth(state = initialState, action) {
switch(action.type) {
case 'LOGIN_REQUEST':
return {
...state,
errors: errors(state.errors, action),
loading: loading(state.loading, action)
}
case 'LOGIN_SUCCESS':
return {
...state,
token: token(state.token, action),
errors: errors(state.errors, action),
tokenIsExpired: tokenIsExpired(state.tokenIsExpired, action),
loading: loading(state.loading, action)
}
case 'LOGIN_FAILURE':
return {
...state,
token: token(state.token, action),
errors: errors(state.errors, action),
tokenIsExpired: tokenIsExpired(state.tokenIsExpired, action),
loading: loading(state.loading, action)
}
case 'LOGOUT_SUCCESS':
return {
...state,
token: token(state.token, action),
tokenIsExpired: tokenIsExpired(state.tokenIsExpired, action),
profile: profile(state.profile, action)
}
case 'SESSION_EXPIRED':
return {
...state,
tokenIsExpired: tokenIsExpired(state.tokenIsExpired, action)
}
case 'PROFILE_REQUEST':
return {
...state,
loading: loading(state.loading, action)
}
case 'PROFILE_SUCCESS':
return {
...state,
profile: profile(state.profile, action),
loading: loading(state.profile, action)
}
default:
return state
}
}
function token(state, action) {
switch(action.type) {
case 'LOGIN_SUCCESS':
return action.payload.token
case 'LOGOUT_SUCCESS':
case 'LOGIN_FAILURE':
return null
default:
return state
}
}
function errors(state, action) {
switch(action.type) {
case 'LOGIN_REQUEST':
case 'LOGIN_SUCCESS':
return []
case 'LOGIN_FAILURE':
return action.payload.errors
default:
return state
}
}
function tokenIsExpired(state, action) {
switch(action.type) {
case 'LOGIN_SUCCESS':
case 'LOGIN_FAILURE':
case 'LOGOUT_SUCCESS':
return false
case 'SESSION_EXPIRED':
return true
default:
return state
}
}
function loading(state, action) {
switch(action.type) {
case 'LOGIN_REQUEST':
case 'PROFILE_REQUEST':
return true
case 'LOGIN_FAILURE':
case 'LOGIN_SUCCESS':
case 'PROFILE_SUCCESS':
return false
default:
return state
}
}
function profile(state, action) {
switch(action.type) {
case 'LOGOUT_SUCCESS':
return null
case 'PROFILE_SUCCESS':
return action.payload.profile
default:
return state
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment