Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

collection and onSnapshot not defined – React

Ok so I’m learning react and trying to use firebase/firestore to play arround but for some reason it won’t recognize collection and onSnapshot

I’ve got the following:

firebase.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { doc, onSnapshot, query, where, getFirestore, collection, getDocs } from 'firebase/firestore';

const firebaseConfig = {
...
};

const app = initializeApp(firebaseConfig);
const db = getFirestore();

export default db;

App.js

import React, { useState, useEffect } from "react";
import db from './firebase.js';

function App() {

useEffect(() => { 
   onSnapshot(collection(db, 'posts'), (snapshot) => { 
       console.log(snapshot); 
   }) 
});

return ( <p>Return Text</p> );

}

export default App;

I googled and readed documentation and after so many tries it’s still not working, any help?

Tried using Firebase V8 and V9 code, expected to get the data using console.log and got nothing, the db imported from firebase.js seems to work since I can see the details using console.log

>Solution :

You need to import those functions in App.js and not in firebase.js:

// Add these imports
import { onSnapshot, collection } from 'firebase/firestore';

import React, { useState, useEffect } from "react";
import db from './firebase.js';

function App() {
  useEffect(() => {
    onSnapshot(collection(db, 'posts'), (snapshot) => {
      console.log(snapshot);
    })
  });

  return ( < p > Return Text < /p> );

}

export default App;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading