Created
July 24, 2020 02:31
-
-
Save alanfoandrade/b5c0373b9963c5303d858892ad81b0fb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
export function signInRequest(email, password) { | |
return { | |
type: '@auth/SIGN_IN_REQUEST', | |
payload: { email, password }, | |
}; | |
} | |
export function signInSuccess(token, user) { | |
return { | |
type: '@auth/SIGN_IN_SUCCESS', | |
payload: { token, user }, | |
}; | |
} |
This file contains hidden or 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 produce from 'immer'; | |
const INITIAL_STATE = { | |
token: null, | |
signed: false, | |
loading: false, | |
}; | |
export default function auth(state = INITIAL_STATE, action) { | |
return produce(state, draft => { | |
switch (action.type) { | |
case '@auth/SIGN_IN_REQUEST': { | |
draft.loading = true; | |
break; | |
} | |
case '@auth/SIGN_IN_SUCCESS': { | |
draft.token = action.payload.token; | |
draft.signed = true; | |
draft.loading = false; | |
break; | |
} | |
case '@auth/SIGN_FAILURE': { | |
draft.loading = false; | |
break; | |
} | |
default: | |
} | |
}); | |
} |
This file contains hidden or 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 { Alert } from 'react-native'; | |
import { takeLatest, call, put, all } from 'redux-saga/effects'; | |
import { signInSuccess, signUpSuccess, signFailure } from './actions'; | |
import api from '~/services/api'; | |
export function* signIn({ payload }) { | |
try { | |
const { email, password } = payload; | |
const response = yield call(api.post, '/sessions', { | |
email, | |
password, | |
}); | |
const { token, user } = response.data; | |
api.defaults.headers.Authorization = `Bearer ${token}`; | |
yield put(signInSuccess(token, user)); | |
} catch (err) { | |
Alert.alert( | |
'Falha na autenticação', | |
err.response | |
? err.response.data.message | |
: 'Verifique os dados, tente novamente' | |
); | |
yield put(signFailure()); | |
} | |
} | |
export function setToken({ payload }) { | |
if (!payload) return; | |
const { token } = payload.auth; | |
if (token) { | |
api.defaults.headers.Authorization = `Bearer ${token}`; | |
} | |
} | |
export default all([ | |
takeLatest('persist/REHYDRATE', setToken), | |
takeLatest('@auth/SIGN_IN_REQUEST', signIn), | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment