Home > Enterprise >  react firebase cannot import db from firebase-config.js
react firebase cannot import db from firebase-config.js

Time:04-20

I need your help. I am trying to import db from the firebase-config.js file where i have setup everything. but I get this error message..

ERROR in ./src/App.js 7:0-32 Module not found: Error: Package path . is not exported from package /Users/ispasdaniel/Documents/react-firebase-todo-app/node_modules/firebase (see exports field in /Users/ispasdaniel/Documents/react-firebase-todo-app/node_modules/firebase/package.json)

this is my firebase-config.js

    // Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

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

// Use this to initialize the firebase App
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

export { db };

and this is how i import it to my App.js file

import React, { useState, useEffect } from "react";
import firebase from "firebase";
import "./App.css";
import { db } from "./firebase-config.js";

function App() {
  const [todoInput, setTodoInput] = useState("");

  const addTodo = (e) => {
    e.preventDefault();

    db.collection("todos").add({
      inprogress: true,
      timestamp: firebase.firestore.FieldValue.serverTimeStamp(),
      todo: todoInput,
    });
  };

CodePudding user response:

You can import serverTimestamp() directly from Firestore Modular SDK as shown below:

// Remove this import
// import firebase from "firebase";

import { serverTimestamp } from "firebase/firestore";

db.collection("todos").add({
  inprogress: true,
  timestamp: serverTimestamp(),
  todo: todoInput,
});

CodePudding user response:

Make sure that you have installed the latest version of your Firebase, you can run this command:

npm i firebase@latest

Upon checking your codes, you've used two different versions in your firebase-config.js (you used the web version 9) and app.js (web version 8) that's why you encountered your error.

You can follow the Firebase documentation in adding a document for web version 9, and use what @Dharmaraj stated in importing serverTimestamp() directly:

// Remove this import
// import firebase from "firebase";
import { collection, addDoc, serverTimestamp } from "firebase/firestore";

const docRef = await addDoc(collection(db, "user"), {
  inprogress: true,
  timestamp: serverTimestamp(),
  todo: todoInput,
});
  • Related