I am trying to figure out how to get cloud firestore working with a react app.
I have found this tutorial, which uses react with realtime database, and have gotten it to load. Now I'm trying to figure out what changes I need to make to get it working with cloud firestore.
In my firebase.js, I have:
import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import firestore from "firebase/firestore";
class Firebase {
constructor() {
app.initializeApp(config).firestore();
this.auth = app.auth();
// this.db = app.firebase.database()
this.db = app.firebase.firestore();
}
doCreateUserWithEmailAndPassword = (email, password) =>
this.auth.createUserWithEmailAndPassword(email, password);
doSignInWithEmailAndPassword = (email, password) =>
this.auth.signInWithEmailAndPassword(email, password);
doSignOut = () =>
this.auth.signOut();
doPasswordReset = email =>
this.auth.sendPasswordResetEmail(email);
doPasswordUpdate = password =>
this.auth.currentUser.updatePassword(password);
// *** User API ***
user = uid => this.db.ref(`users/${uid}`);
users = () => this.db.ref('users');
}
export default Firebase;
Then, in my form, I'm trying this:
import { withFirebase } from '../../../components/firebase';
onSubmit = event => {
const { username, email, passwordOne } = this.state;
this.props.firebase
.doCreateUserWithEmailAndPassword(email, passwordOne)
.then(authUser => {
// Create a user
return this.props.firebase
.user(authUser.user.uid)
.set({
username,
email,
});
})
.then(authUser => {
this.setState({ ...INITIAL_STATE });
this.props.history.push(ROUTES.INITIAL_PROFILE);
})
.catch(error => {
this.setState({ error });
});
event.preventDefault();
}
onChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
The import withFirebase has:
import FirebaseContext, { withFirebase } from './Context';
import Firebase from '../../firebase.1';
export default Firebase;
export { FirebaseContext, withFirebase };
FirebaseContext has:
import React from 'react';
const FirebaseContext = React.createContext(null);
export const withFirebase = Component => props => (
<FirebaseContext.Consumer>
{firebase => <Component {...props} firebase={firebase} />}
</FirebaseContext.Consumer>
);
export default FirebaseContext;
When I try this, I get an error that says:
TypeError: Cannot read property 'firestore' of undefined
The error message points to this line of the firebase config file:
this.db = app.firebase.firestore();
How can I get firestore working in a react app?
app
is actually your firebase instance, so you have to doapp.firestore()
instead I guess. – Suman Kundu