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!