Home > Blockchain >  collection and onSnapshot not defined - React
collection and onSnapshot not defined - React

Time:03-26

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


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

CodePudding user response:

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;
  • Related