Reactfire: useFirestore().collection is not a functon

288 Views Asked by At

I am having a bit of a fight with reactfire and its poor documentation.

I see many examples around using the apis coming from useFirestore() as if that was a normal firestore instance coming from the firebase SDK.

I see code like:

const firestore = useFirestore()

const myCollection = firestore.collection('collectionName')

But if I try to do that I get firestore.collection is not a function. Did something radically change recently or am I not getting something?

Thanks in advance for any help!

1

There are 1 best solutions below

2
On

I think you have a bad project structure. I give you my example:

// react-create-app structure

src --|
      |-- index.js
      |-- firebaseConfig.js
      |-- firebaseApp.js
      |-- App.js
      |-- ExampleComponent.js

Try it.

// src/index.js

import React from 'react';
import ReactDOM from 'react-dom';

import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root'),
);

Your firebase app info file

// src/firebaseConfig.js
const firebaseConfig: Object = {
  apiKey: 'xxx',
  authDomain: 'xxx.firebaseapp.com',
  projectId: 'xxx-project',
  storageBucket: 'xxx.appspot.com',
  messagingSenderId: 'xxx',
  appId: 'xxx',
  // measurementId: 'xxx', // I don't enable google analytics for this project
};

export default firebaseConfig;

Example a FirebaseApp file

// src/firebaseApp.js

import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/functions';
import 'firebase/auth';
import firebaseConfig from './firebaseConfig'; // Your firebase app config

const app = firebase.initializeApp(firebaseConfig);

export default app;

Next file is App.js

// src/App.js

import React from 'react';

import { FirebaseAppProvider } from 'reactfire';
import firebaseApp from './firebaseApp'; 

import ExampleComponent from './ExampleComponent';

const App = () => {
  return (
    <FirebaseAppProvider firebaseApp={firebaseApp}>
      <ExampleComponent />
    </FirebaseAppProvider>
  );
};

export default App;

Component example code:

// src/ExampleComponent.js

import React from 'react';

import { useFirestore } from 'reactfire';

    
const ExampleComponent = () => {
    const firestore = useFirestore();
        
    console.log(firestore.collection('your_collection_name')); // Working good
        
    return <>Hello reactfire App</>;
};

export default ExampleComponent;