JavaScript

6 out, 2020

5 tópicos úteis para usar em React apps com Firebase e Firestore

Publicidade

Introdução

yarn add react-redux-firebase
yarn add redux-firestore
yarn add firebase

Configuração

import { createStore, combineReducers, compose } from ‘redux’
import { reduxFirestore, firestoreReducer, createFirestoreInstance } from ‘redux-firestore’
import { firebaseReducer } from ‘react-redux-firebase’
import firebase from ‘firebase/app’
import ‘firebase/auth’
import ‘firebase/database’
import ‘firebase/firestore’

const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_apiKey,
  authDomain: process.env.REACT_APP_FIREBASE_authDomain,
  databaseURL: process.env.REACT_APP_FIREBASE_databaseURL,
  projectId: process.env.REACT_APP_FIREBASE_projectId,
  storageBucket: process.env.REACT_APP_FIREBASE_storageBucket,
  messagingSenderId:   process.env.REACT_APP_FIREBASE_messagingSenderId,
  appId: process.env.REACT_APP_FIREBASE_appId,
  measurementId: process.env.REACT_APP_FIREBASE_measurementId,
}; // from Firebase Console

const rfConfig = {} // optional redux-firestore Config Options

// Initialize firebase instance
firebase.initializeApp(firebaseConfig)

// Initialize Cloud Firestore through Firebase
firebase.firestore();

// Add reduxFirestore store enhancer to store creator
const createStoreWithFirebase = compose(
   reduxFirestore(firebase, rfConfig), // firebase instance as first argument, rfConfig as optional second)(createStore)

// Add Firebase to reducers
const rootReducer = combineReducers({

firebase: firebaseReducer,
firestore: firestoreReducer

})

// Create store with reducers and initial state
const initialState = {}
const store = createStoreWithFirebase(rootReducer, initialState)

const rrfConfig = {
  enableLogging: false,
  userProfile: ‘users’, // root that user profiles are written to
  updateProfileOnLogin: false, // enable/disable updating of profile on login
  useFirestoreForProfile: true, // Save profile to Firestore instead of Real Time Database
  useFirestoreForStorageMeta: true // Metadata associated with storage file uploads goes to Firestore
}

const rrfProps = {
  firebase,
  config: rrfConfig,
  dispatch: store.dispatch,
  createFirestoreInstance
}

export { store, rrfProps };

Uma pequena observação no código sobre userProfile: 'users'. Essa configuração permite gravar os dados de perfil (como nome, telefone, etc..) em uma collection automaticamente.
Agora precisamos configurar o arquivo index.js, verifiquemos as mudanças abaixo:

import React from ‘react’;
import { ReactReduxFirebaseProvider } from ‘react-redux-firebase’
import ReactDOM from ‘react-dom’;
import Root from ‘./Root’;
import * as serviceWorker from ‘./serviceWorker’;
import { Provider } from ‘react-redux’;
import { store, rrfProps } from ‘./firebase-config’;

ReactDOM.render(
   <Provider store={store}>
      <ReactReduxFirebaseProvider {…rrfProps}>
         <Root />
      </ReactReduxFirebaseProvider>
   </Provider>
   , document.getElementById(‘root’));

serviceWorker.unregister();

Usando

1. Redirecionar o login

import { isEmpty, isLoaded } from 'react-redux-firebase';
import { useSelector } from 'react-redux';

function Login(props) {
  const auth = useSelector(state => state.firebase && state.firebase.auth)

useEffect(() => {
     if (isLoaded(auth) && !isEmpty(auth))               
     history.push(routeNames.DASHBOARD)
  }, [auth]);

}

2. Usando Autenticação:

import { useFirebase } from 'react-redux-firebase';

function Login(props) {

const firebase = useFirebase();

function loginWithGoogle() {
       firebase.login({ provider: 'google', type: 'popup' }).catch(e => {
       let msg = handleAuthError (e.code);
       message.error(msg);

});

}

}

3. Usando real-time

import { useSelector } from 'react-redux';
import { useFirestoreConnect, useFirestore, useFirebase } from 'react-redux-firebase';

function Tests(props) {

useFirestoreConnect(() => [{ collection: 'tests', orderBy: [['createdAt', 'desc']] },])
   let tests = useSelector(state => state.firestore.ordered.tests);

return (<>{JSON.stringify(tests)}</>);

}

4. Usando Firestore

import { useFirestore } from 'react-redux-firebase'

function Test(props) {
   const firestore = useFirestore();

function addComment(comment) {
     const comments  = [...props.test.comments];
     comments.push(comment)

firestore.collection('tests').doc(props.test.id).set({ ...props.test, comments }).then(data => {

message.success('Comentário enviado!');

}).catch(e => {
        handleAuthError(e.code);
     }).finally(() => {
        //setLoading(false);
     });
   }

}

5. Usando as informações de perfil

import { useSelector } from 'react-redux';

function MenuBar(props) {

const profile = useSelector(state => state.firebase.profile);
  return (<>{JSON.stringify(profile)}</>);

}

Veja o artigo original aqui