Last active
February 25, 2019 17:54
-
-
Save Nitemaeric/dcb66e6a32beacb3e06472aed99769aa to your computer and use it in GitHub Desktop.
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 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