SHARE
TWEET

Untitled

a guest Mar 26th, 2020 68 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { all, put, take, takeEvery } from 'redux-saga/effects';
  2. import { eventChannel } from 'redux-saga';
  3. import { auth, firestore } from 'firebase';
  4. import { addUserInfo, updateUserAuthedData, User } from 'state/actions/user';
  5. import { errorOccurred } from 'state/actions/common';
  6. import { UserActionTypes } from 'state/types/user';
  7.  
  8. let userAuthedDataChannel: any;
  9.  
  10. function* syncUserAuthedData({ type, payload }: { type: string; payload: User }) {
  11.   // this statement prevent subscription when there is no uid and cancel subscription after user logged out
  12.   if (payload.uid === '') {
  13.     // if (userAuthedDataChannel) userAuthedDataChannel.close();
  14.     return;
  15.   }
  16.   const ref = firestore()
  17.     .collection('users')
  18.     .doc(payload.uid)
  19.     .collection('userData')
  20.     .doc('authedData');
  21.   userAuthedDataChannel = eventChannel(emit => ref.onSnapshot(emit));
  22.  
  23.   try {
  24.     while (true) {
  25.       const data = yield take(userAuthedDataChannel);
  26.       yield put(updateUserAuthedData(data));
  27.     }
  28.   } catch (e) {
  29.     yield put(errorOccurred(e.code));
  30.   }
  31. }
  32.  
  33. function* syncUserAuthedDataWatcher() {
  34.   yield takeEvery(UserActionTypes.USER_INFO, syncUserAuthedData);
  35. }
  36.  
  37. function* userStateWorker() {
  38.   const channel = eventChannel(emit =>
  39.     auth().onAuthStateChanged(user => {
  40.       if (!user) return emit({});
  41.       return emit(user);
  42.     }),
  43.   );
  44.  
  45.   try {
  46.     while (true) {
  47.       const user = yield take(channel);
  48.       yield put(addUserInfo({ displayName: user.displayName || null, uid: user.uid || '' }));
  49.     }
  50.   } catch (e) {
  51.     debugger
  52.     yield put(errorOccurred(e.code));
  53.   }
  54. }
  55.  
  56. export default function* userSaga() {
  57.   yield all([syncUserAuthedDataWatcher(), userStateWorker()]);
  58. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top