Skip to content

Instantly share code, notes, and snippets.

@Nitemaeric
Last active February 25, 2019 17:54
Show Gist options
  • Save Nitemaeric/dcb66e6a32beacb3e06472aed99769aa to your computer and use it in GitHub Desktop.
Save Nitemaeric/dcb66e6a32beacb3e06472aed99769aa to your computer and use it in GitHub Desktop.
import request from 'superagent'
import Cookies from 'js-cookie'
// CONSTANTS
// ====================
const SIGN_IN = 'SIGN_IN'
const SIGN_IN_SUCCEEDED = 'SIGN_IN_SUCCEEDED'
const SIGN_IN_FAILED = 'SIGN_IN_FAILED'
const BASE_HOST = 'https://api.example.com'
// ACTIONS
// ====================
export const beginSignIn = {
type: SIGN_IN
}
export const signInSucceeded = (response) => ({
type: SIGN_IN_SUCCEEDED,
payload: response
})
export const signInFailed = (error) => ({
type: SIGN_IN_FAILED,
payload: error
})
// THUNK ACTIONS
// ====================
export const signIn = (data) => (dispatch, getState) => {
dispatch(beginSignIn)
return request
.post(`${BASE_HOST}/session`)
.send(data)
.then(response => {
dispatch(signInSucceeded(response))
})
.catch(error => {
dispatch(signInFailed(error))
})
}
// INITIAL STATE & REDUCER
// ====================
const initialState = {
authenticating: false,
authenticated: false
}
const authenticationReducer = (state = initialState, { type, payload }) => {
// HANDLER
switch(type) {
case SIGN_IN:
return { ...state, authenticating: true }
case SIGN_IN_SUCCEEDED:
Cookies.set('accessToken', payload.body.accessToken, { expires: 30, secure: true })
return { ...state, authenticated: true, authenticating: false }
case SIGN_IN_FAILED:
return { ...state, authenticated: false, authenticating: false, error: payload }
default:
return state
}
}
export default authenticationReducer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment