Created
November 30, 2017 07:48
-
-
Save st8998/ee9f9ef921dfb8441da1ac731ae130d1 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
import { eventChannel } from 'redux-saga' | |
import { take, spawn, put, takeLatest, takeEvery, call } from 'redux-saga/effects' | |
import { isEmpty } from 'ramda' | |
import * as actions from './auth_actions' | |
const provider = new firebase.auth.GoogleAuthProvider() | |
const authStateChannel = eventChannel((emit) => { | |
firebase.auth().onAuthStateChanged((user) => { | |
if (user) { | |
emit({ | |
id: user.uid, | |
email: user.email, | |
name: user.displayName, | |
photoUrl: user.photoURL, | |
}) | |
} else { | |
emit({}) | |
} | |
}) | |
return () => {} | |
}) | |
function* subscribeOnStateChannel() { | |
while (true) { | |
const user = yield take(authStateChannel) | |
yield put(actions.setCurrentUser(isEmpty(user) ? null : user)) | |
} | |
} | |
function* requestLogin() { | |
const auth = firebase.auth() | |
try { | |
yield call(auth.signInWithPopup.bind(auth), provider) | |
} catch (e) { | |
console.error(e) | |
} | |
} | |
function* requestLogout() { | |
const auth = firebase.auth() | |
try { | |
yield call(auth.signOut.bind(auth)) | |
} catch (e) { | |
console.error(e) | |
} | |
} | |
export default function* watch() { | |
yield spawn(subscribeOnStateChannel) | |
yield takeLatest(actions.requestLogin, requestLogin) | |
yield takeEvery(actions.requestLogout, requestLogout) | |
} |
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
const provider = new firebase.auth.GoogleAuthProvider() | |
export const setCurrentUser = user => ({ type: 'AUTH/SET_CURRENT_USER', payload: user }) | |
setCurrentUser.toString = () => 'AUTH/SET_CURRENT_USER' | |
export const subscribeOnCurrentUserState = () => (dispatch) => { | |
console.log('SUBSCRIBE') | |
firebase.auth().onAuthStateChanged((user) => { | |
if (user) dispatch(setCurrentUser({ | |
id: user.uid, | |
email: user.email, | |
name: user.displayName, | |
photoUrl: user.photoURL, | |
})) | |
else dispatch(setCurrentUser(null)) | |
}) | |
} | |
export const requestLogin = () => async (dispatch) => { | |
const auth = firebase.auth() | |
try { | |
await auth.signInWithPopup(provider) | |
} catch (e) { console.log(e) } | |
} | |
export const requestLogout = () => async (dispatch) => { | |
const auth = firebase.auth() | |
try { | |
await auth.signOut() | |
} catch (e) { console.error(e) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment