Chat Messages

In notebook:
FrontEndMasters Serverless
Created at:
2017-10-13
Updated:
2017-10-15
Tags:
backend JavaScript libraries React

We still need to listen to the user refs and messages.

App > Redux > Firebase > Redux > App

  //	****		actions/users.js		****
// **** 2.  ↴
import {database} from '../firebase'

// **** 3.  ↴
const usersRef = database.ref('users')

export const addUser = (user) => {
  return {
    type: 'ADD_USER',
    displayName: user.displayName,
    uid: user.uid,
    photoURL: user.photoURL
  };
};

// **** 1.  ↴
export const startListeningForUsers = () => {
  return (dispatch) => {
    usersRef.on('child_added', snapshot => {
      dispatch(addUser(snapshot.val()))
    })
  }
}
  //	****		actions/auth.js		****

import { auth, database,  googleAuthProvider } from '../firebase'

// **** 1.  ↴
const usersRef = database.ref('users')

export const signIn = () => {
  return dispatch => {
    dispatch({type: 'ATTEMPINT_LOGIN' })
    auth.signInWithPopup(googleAuthProvider)
  }
};

export const signOut = () => {
  auth.signOut().then(() => {
    auth.signOut()
  })
};

export const startListeningToAuthChanges = () => {
  return dispatch => {
    auth.onAuthStateChanged(user => {
      if (user) {
        dispatch(signedIn(user))
        // **** 2.  ↴
        usersRef.child(user.uid).set(pick(user, ['displayName', 'photoURL', 'email', 'uid'])
      } else {
        dispatch(signedOut())
      }
    })  
  }
}

We still use the listeners

  //	****		./index.js		****

import React from 'react';
import ..

import {startListeningToAuthChanges} from './actios/auth'
// **** 1.  ↴
import { startListeningForUsers } from './actions/users'

const middleware = [ thunk ];
const enhancers = [];
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const store = createStore(
  reducer,
  initialState,
  composeEnhancers(
    applyMiddleware(...middleware),
    ...enhancers
  )
);

store.dispatch(startListeningToAuthChanges())
// **** 2.  ↴
store.dispatch(startListeningForUsers())

ReactDOM.render(
  <Provider store={store}>
    <Application />
  </Provider>,
  document.getElementById('root')
);

Last step is messages...

Adding messages

We want to add Firebase to this code:

  //	****		actions/messages.js		****

// **** 1.  ↴
import { database } from '../firebase'

// **** 2.  ↴
const messagesRef = database.ref('messages')

export const addMessage = (key, { content, uid }) => {
  return {
    type: 'ADD_MESSAGE',
    content,
    key,
    timeStamp: Date.now(),
    uid
  };
};

export const removeMessage = (key) => {
  return {
    type: 'REMOVE_MESSAGE',
    key
  };
};

// **** 4 pull out content, uid.  ↴
export const createMessage = ({content, uid}) => {
  // **** 3. we need to return a function  ↴
  return dispatch => {
    const message = {
      content,
      uid,
      timeStamp: Date.now()
    }
    // **** 5 then push it onto the database.  ↴
    messagesRef.push(message)
  }
};

export const destroyMessage = (key) => {
  // **** 6. update this too  ↴
  return dispatch => {
    messagesRef.child(key)
    .remove()
    // to demo the Promise API :
    .then(() => {
      // remove the message from the UI ↴
      dispatch(removeMessage(key))
    })  
  }
};

// **** 7. finally, export the listener  ↴

export const startListeninigForMessages = () => {
  return dispatch => {
    // will listen for two things : ↴
    messagesRef.on('child_added', snapshot => {
      dispatch(addMessage(snapshot.key, snapshot.val()))
    })
    
    messagesRef.on('child_removed', snapshot => {
      dispatch(remvoceMessage(snapshot.key))
    })
  }
}

Question: Does Firebase have a date function ?

  • Not one that he is aware of

Finally, add the listener in index.js:

  //	****		./index.js		****

import React from 'react';
import ..

import {startListeningToAuthChanges} from './actios/auth'
import { startListeningForUsers } from './actions/users'
// **** 1. import the method  ↴
import { startListeninigForMessages } from './actions/messages'

const middleware = [ thunk ];
const enhancers = [];
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const store = createStore(
  reducer,
  initialState,
  composeEnhancers(
    applyMiddleware(...middleware),
    ...enhancers
  )
);

store.dispatch(startListeningToAuthChanges())
store.dispatch(startListeningForUsers())
// **** 2. use it  ↴
store.dispatch(startListeninigForMessages())

ReactDOM.render(
  <Provider store={store}>
    <Application />
  </Provider>,
  document.getElementById('root')
);