0
votes

So I'm currently following a tutorial, where the author is using redux to live update data with the help of real-time database. Inside the redux file, he uses the .on method, like so:

const watchPersonData = () => {
  return function(dispatch) {
    firebase.database().ref("person").on("value", function(snapshot) {

        var personData = snapshot.val();
        var actionSetPersonData = setPersonData(personData);
        dispatch(actionSetPersonData);

    }, function(error) { console.log(error); });
  }
};

However, I want to use cloud firestore, so I've tried to transform this code with the onSnapshot method. However, the user is undefined:

const watchPersonData = () => {
  return function(dispatch){



    db.collection('user').doc().onSnapshot(function(snap){



    var personData = snap.val();
    var actionSetPersonData = setPersonData(personData);
    dispatch(actionSetPersonData);

  })

  }
};

Currently I have a collection called 'user' and within this collection a document with an auto generated id (that's why doc() is empty) an within this document a string called username. Any ideas why this.props.personData.username is undefined in the console?

Whole app-redux file:

import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import * as firebase from 'firebase';


const db = firebase.firestore;


var config = {
    //config data for firebase
  };

firebase.initializeApp(config);


const initialState = {
  personData: { },
}

const reducer = (state = initialState, action) => {

  switch(action.type){
    case 'setPersonData':
      return { ...state, personData: action.value};

    default:
      return state;

  }
}
const store = createStore(reducer, applyMiddleware(thunkMiddleware));




const setPersonData = (personData) => {

  return{
    type: "setPersonData",
    value: personData
  };
};

const watchPersonData = () => {
  return function(dispatch){
    console.log('called')


    db.collection('user').doc().onSnapshot(function(snap){


    console.log(snap)
    var personData = snap;
    var actionSetPersonData = setPersonData(personData);
    dispatch(actionSetPersonData);




  })

  }
};








export { setPersonData, watchPersonData};
export { store };

Thanks everyone! in advance!

1

1 Answers

0
votes

Are you trying to access a specific user document in the user collection? You aren’t specifying a document Id which I’m pretty sure is leading to your undefined user.

You can call onSnapshot directly on a collection and receive collection updates (say another document is added) or call it on a specific document like you are doing and be updated when that document changes. An easy way to test is to hardcore an Id from your collection ias the doc argument and subscribe to doc changes and log to the console something like (‘doc changed’) and then make manual changes in the firestorm console.