Haksatrya Bhaswara
Haksatrya Bhaswara

Reputation: 247

'firestore' is not defined no-undef

I have a new project using firebase. I've created 2 files,

firebase.js

import firebase from "firebase/app";
import "firebase/storage";
import "firebase/firestore";

const firebaseConfig = {
  apiKey: "x",
  authDomain: "x",
  projectId: "x",
  storageBucket: "x",
  messagingSenderId: "x",
  appId: "x",
  measurementId: "x",
};

firebase.initializeApp(firebaseConfig);

export default firebase;

and App.js

import React, { useEffect, useState, useRef } from "react";
import firebase from "./firebase";

export default function App() {
  const [urlVideo, setUV] = useState();

  useEffect(() => {
    getRoom();
    console.log("TEST");
  }, []);

  const getRoom = async () => {
    firebase
      .firestore()
      .collection("abc")
      .add({
        room: Math.floor(Math.random() * 10000),
        createdAt: firestore.FieldValue.serverTimestamp(),
      })
      .then(() => {
        console.log("Room added!");
      });
  };

  return (
    <div>
      
    </div>
  );
}

and when I run my project, I am getting this error. Please refer to the image below.

error

idk why this is happened, because I already have multiple projects with firebase before, and I've compared with another project (the code) and realized there's no difference with my last project using firebase.

I'm using

"firebase": "^8.7.0",

can you guys help me? thanks a lot!

Upvotes: 1

Views: 1828

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50930

Here's the problem:

createdAt: firestore.FieldValue.serverTimestamp()
           ^^^^^^^^^

The namespace is not defined anywhere so you would have to export that too.

Refactor the firebase.js like this:


if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}

const firestoreNamespace = firebase.firestore

export {firebase, firestoreNamespace};

App.js:

import { firebase, firestoreNamespace } from "./firebase"

// Now you can use the namespace like this
createdAt: firestoreNamespace.FieldValue.serverTimestamp()

Upvotes: 3

Related Questions