Created
July 20, 2018 20:44
-
-
Save kaiobrito/292546eb883a0ce9fcd5cc40df7f8445 to your computer and use it in GitHub Desktop.
Authentication with Redux + Redux Saga
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
export const actionCreators = { | |
changeUser: user => ({ | |
type: actionTypes.USER_CHANGED, | |
payload: user | |
}), | |
logout: () => ({ | |
type: actionTypes.LOGOUT | |
}), | |
fetchUser: () => ({ | |
type: actionTypes.FETCH_USER_REQUEST | |
}), | |
errorFetchingUser: () => ({ | |
type: actionTypes.FETCH_USER_REQUEST_ERROR | |
}) | |
}; |
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 { takeEvery, call, put } from "redux-saga/effects"; | |
import { BugTracer } from "../../Services"; | |
import { UserRequester } from "../../Requesters"; | |
// $5 | |
function* setBugtracerUser({ payload }) { | |
yield call(BugTracer.setUser, payload); | |
} | |
// #4 | |
function* fetchUser() { | |
try { | |
const response = yield call(UserRequester.fetchMe); | |
yield put(actionCreators.changeUser(response.data)); | |
} catch (error) { | |
yield put(actionCreators.errorFetchingUser(error)); | |
} | |
} | |
// #3 | |
function* dispatchFetchUser() { | |
yield put(actionCreators.fetchUser()); | |
} | |
// #2 | |
function* onTokenChange({ payload }) { | |
axios.defaults.headers.common["Authorization"] = payload; | |
} | |
// #1 | |
export default function*() { | |
yield takeEvery(actionTypes.USER_CHANGED, setBugtracerUser); | |
yield takeEvery( | |
[actionTypes.ACCESS_TOKEN_CHANGED, actionTypes.LOGOUT], | |
onTokenChange | |
); | |
yield takeEvery(actionTypes.ACCESS_TOKEN_CHANGED, dispatchFetchUser); | |
yield takeEvery(actionTypes.FETCH_USER_REQUEST, fetchUser); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment