Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { all, put, take, takeEvery } from 'redux-saga/effects';
- import { eventChannel } from 'redux-saga';
- import { auth, firestore } from 'firebase';
- import { addUserInfo, updateUserAuthedData, User } from 'state/actions/user';
- import { errorOccurred } from 'state/actions/common';
- import { UserActionTypes } from 'state/types/user';
- let userAuthedDataChannel: any;
- function* syncUserAuthedData({ type, payload }: { type: string; payload: User }) {
- // this statement prevent subscription when there is no uid and cancel subscription after user logged out
- if (payload.uid === '') {
- // if (userAuthedDataChannel) userAuthedDataChannel.close();
- return;
- }
- const ref = firestore()
- .collection('users')
- .doc(payload.uid)
- .collection('userData')
- .doc('authedData');
- userAuthedDataChannel = eventChannel(emit => ref.onSnapshot(emit));
- try {
- while (true) {
- const data = yield take(userAuthedDataChannel);
- yield put(updateUserAuthedData(data));
- }
- } catch (e) {
- yield put(errorOccurred(e.code));
- }
- }
- function* syncUserAuthedDataWatcher() {
- yield takeEvery(UserActionTypes.USER_INFO, syncUserAuthedData);
- }
- function* userStateWorker() {
- const channel = eventChannel(emit =>
- auth().onAuthStateChanged(user => {
- if (!user) return emit({});
- return emit(user);
- }),
- );
- try {
- while (true) {
- const user = yield take(channel);
- yield put(addUserInfo({ displayName: user.displayName || null, uid: user.uid || '' }));
- }
- } catch (e) {
- debugger
- yield put(errorOccurred(e.code));
- }
- }
- export default function* userSaga() {
- yield all([syncUserAuthedDataWatcher(), userStateWorker()]);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement