Firebase JS SDK warning while using firebase database in reactjs [duplicate] - javascript

This question already has answers here:
Warning: It looks like you're using the development build of the Firebase JS SDK
(6 answers)
Closed 2 years ago.
I am trying to use firebase database for my project but I am unable to properly import and use the module. I have followed what the official documentation recommends.
This is the code where I am using it.
import React from "react";
import firebase from "firebase";
import ProjectItemCards from "./components/project-item-cards";
const ProjectContext = React.createContext();
class ProjectProvider extends React.Component {
constructor() {
super();
this.state = {
social: {},
projects: [],
featuredProjects: [],
loading: true,
};
}
componentDidMount() {
var ref = firebase.database().ref("projects");
ref.on("value", (snapshot) => {
const projects = snapshot.val();
console.log(projects);
const featuredProjects = projects
.map((project) => (project.featured === true ? project : null))
.slice(0, 4);
this.setState({
projects,
featuredProjects,
loading: false,
});
});
}
getProjectElements(projects) {
const projectElementList = projects.map((project, index) => {
return (
<ProjectItemCards key={index} project={project}></ProjectItemCards>
);
});
return projectElementList;
}
render() {
return (
<ProjectContext.Provider
value={{ ...this.state, getProjectElements: this.getProjectElements }}
>
{this.props.children}
</ProjectContext.Provider>
);
}
}
export { ProjectProvider, ProjectContext };
I have initialized firebase as follows
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import "bootstrap";
import "./sass/main.scss";
import * as firebase from "firebase/app";
import "firebase/analytics";
var firebaseConfig = {
apiKey: process.env.REACT_APP_API_KEY,
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "1:841600272388:web:12314d1260dded0601cd51",
measurementId: "G-55E4QT6C4F",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
ReactDOM.render(<App />, document.getElementById("root"));
I have removed all sensitive information from above code
Also note that I am getting my data as required and everything is working fine. I just want to get rid of this warning

initialization code should be used in a utility file and look like the following:
import * as firebase from 'firebase/app'
import 'firebase/firestore'
import 'firebase/storage'
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID
}
firebase.initializeApp(firebaseConfig)
export const db = firebase.firestore()
export const storage = firebase.storage()
export default firebase
you want to export the individual firebase features you are utilizing. In your case I would assume firebase.firestore
then your import should look like so:
import {db} from '../utils/firebase'

Related

NextAuth and Firebase causing SyntaxError Cannot use import statement outside a module

I'm new to both Next.js and Firebase. I've been trying to use NextAuth.js to authenticate with Discord for my firebase app. However, I ran into an error.
I've tried adding "type": "module" into my package.json file and converting all my imports into requires instead but I still get the same error.
This is my firebase.js
import firebase from "firebase/compat/app";
import { getApps, getApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
import { getStorage } from 'firebase/storage';
export const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID
};
export const app = getApps.length > 0 ? getApp() : firebase.initializeApp(firebaseConfig);
export const firestore = getFirestore(app);
export const storage = getStorage(app);
This is my [...nextauth].js
import NextAuth from "next-auth";
import DiscordProvider from 'next-auth/providers/discord';
import { FirestoreAdapter } from "#next-auth/firebase-adapter";
import { firebaseConfig } from "../../../lib/firebase";
export default NextAuth({
providers: [
DiscordProvider({
clientId: process.env.DISCORD_ID,
clientSecret: process.env.DISCORD_SECRET
}),
],
adapter: FirestoreAdapter(firebaseConfig),
})
Any help would be much appreciated
I went through this as well. I found using a simple config easier and exporting the default app into your component. Then in the component, add the extra functionality.
Here is my config;
import { initializeApp } from 'firebase/app';
// Initialize Firebase
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
}
const app = initializeApp(firebaseConfig)
export default app;
then in controller...
import { getDatabase } from 'firebase/database';
import app from '../services/firebase';
const rtdb = getDatabase(app);

Firebase Module not found: Can't resolve '../firebase' in '/vercel/path0/components' during deployment

I was trying to deploy my application that uses firebase on Vercel. But it gives `Module not found: Can't resolve '../firebase' in '/vercel/path0/components', in development this works.
My firebase.js
import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECTID,
storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_APP_ID,
measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID,
};
const app = !firebase.apps.length
? firebase.initializeApp(firebaseConfig)
: firebase.app();
const db = app.firestore();
const auth = app.auth();
const provider = new firebase.auth.GoogleAuthProvider();
export { auth, db, provider };
I am import auth, db and provider where ever I want to use them.
Here is one of the file where this error occurs.
import { auth } from "../firebase";
const Sidebar = () => {
const [user] = useAuthState(auth);
I guess the error is at import { auth } from "../firebase"; part.
Is there any way to fix this? Help would be appreciated.

In Firebase I am getting an Uncaught TypeError: Cannot read property 'initializeApp' of undefined, but not sure why 'firebase' is not defined?

here's my firebase import etc. in the config file, why would this be unable to recognise firebase?
import firebase from 'firebase/app'
import 'firebase/firestore'
import 'firebase/auth'
const firebaseConfig = {
apiKey: "XXX",
authDomain: "XXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX",
appId: "XXX",
measurementId: "XXX"
}
//init firebase
firebase.initializeApp(firebaseConfig)
const projectAuth = firebase.auth()
const projectFirestore = firebase.firestore()
const timestamp = firebase.firestore.FieldValue.serverTimestamp
export { projectAuth, projectFirestore, timestamp }
If you have installed version 9.0.0 then you would have to use compat libraries to use the namespaced version:
import firebase from 'firebase/compat/app'
import 'firebase/compat/firestore'
import 'firebase/compat/auth'
Although I'd recommend using the new Modular syntax which is designed to facilitate tree-shaking (removal of unused code) to make your web app as small and fast as possible.
import { initializeApp } from "firebase/app"
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore"
const app = initializeApp(firebaseConfig)
const projectAuth = getAuth(app)
const projectFirestore = getFirestore(app)
export { projectAuth, projectFirestore }
You can find detailed information in the documentation

How can I add data into Firebase Web 9.0.0?

I was using Firebase over year ago and I am confused on how to do basic CRUD in newest Firebase.
My Todo item that I want to add to Firebase db is:
import React, { useState } from 'react';
import firebase from '../utils/firebase'
export default function Form() {
const [title, setTitle] = useState('')
const handleChange = (e) => {
setTitle(e.target.value)
}
const createTodo = () => {
const todoRef = firebase.database().ref('Todo')
const todo = {
title,
complete: false
};
todoRef.push(todo)
}
return (
<div>
<input type="text" onChange={handleChange} value={title}/>
<button onClick={createTodo}>Add Todo</button>
</div>
)
}
My firebase.js in utils is:
import firebase from 'firebase/compat/app';
const firebaseConfig = {
apiKey: "AIzaSyDyfhIiB32tReM7E66wFR8oD0mMC3LKZWM",
authDomain: "nutriapp-b77ee.firebaseapp.com",
projectId: "nutriapp-b77ee",
storageBucket: "nutriapp-b77ee.appspot.com",
messagingSenderId: "717648627918",
appId: "1:717648627918:web:b382565fc790dd1495a89f",
measurementId: "G-W3H2K8NGNJ"
};
firebase.initializeApp(firebaseConfig)
export default firebase;
Please help, thanks

Where do I initialize Firebase app in React application?

I'm trying to integrate Firebase into my React app and after looking at various tutorials, I can't seem to find a consensus on where to put the firebase initialization code firebase.initializeApp(config).
My app's structure is this:
- app.js
- components
|___Index.jsx
|___Layout.jsx
|___PageContent.jsx
Each file looks like the following
app.js
Does all the express setup with server-side rendering
Index.jsx
import React from 'react';
import Layout from './Layout.jsx';
import PageContent from './PageContent.jsx';
import './global.css';
class Index extends React.Component {
render() {
return (
<Layout title={this.props.title}>
<PageContent />
</Layout>
);
}
}
export default Index;
PageContent.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import LandingPage from './components/Landing_Page/Landing.jsx';
class PageContent extends React.Component {
render() {
return (
<LandingPage />
);
}
}
if (typeof window !== 'undefined') {
ReactDOM.render(
<PageContent />,
document.getElementById('root')
);
}
export default PageContent;
I need to make sure Firebase is available in every page of my website. Right now it is a single page app but eventually I'll be adding more.
Can anybody help me understand where I might put the database initialization code so that it is applied everywhere?
this is how I do it
create file Firebase.js next to app.js and put your initialization code
Firebase.js file
import * as firebase from 'firebase';
let config = {
apiKey: "XXXXXXX",
authDomain: "XXXXX",
databaseURL: "XXXXX",
projectId: "XXXXX",
storageBucket: "XXXX",
messagingSenderId: "XXXX"
};
firebase.initializeApp(config);
export default firebase;
and then import Firebase.js file every where you want to use it , for example
import React from 'react';
import firebase from './../Firebase.js' // <------ import firebase
class Test extends React.Component {
componentDidMount(){
firebase.database().ref().child("X").on('value' , {...});
}
render() {
return (
<h1>Hello</h1>
);
}
}
export default Test;
Create file with name firebase.js
import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
const firebaseConfig = {
apiKey: 'AIzaXXXXXXXXXXXXXXXXXXXXXXX',
authDomain: 'test-XXXX.firebaseapp.com',
databaseURL: 'https://test-db.firebaseio.com',
projectId: 'test-XXXX',
storageBucket: 'test-bucket.appspot.com',
messagingSenderId: 'XXXXXXX',
appId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
};
firebase.initializeApp(firebaseConfig);
export const firebaseAuth = firebase.auth();
export const firestore = firebase.firestore()
Then use it as follows:
import { firebaseAuth } from 'firebase'
import SigninForm from 'signin.js'
const ModalSignIn = props => {
const [email, setEmail] = useState()
const [password, setPassword] = useState()
const handleSubmit = e => {
e.preventDefault()
firebaseAuth
.signInWithEmailAndPassword(email, password)
.then(res => {
console.log(res.user)
})
.catch(err => {
const { code, message } = err
console.log(code, message)
})
}
return (<SigninForm/>)
It seems that what you want is that firebase can be globally available to your react components.
It's the same question before using redux, how does react components consume the global state tree? Global variables? Come on, we'll know global variables are evil. React props? It seems very react but passing props down from root to the leaf components can't be fun.
Context API comes to rescue. You simply need firebase bindings for react just as redux/react-router did.
Assume you don't want to reinvent wheels,
If you use redux, consider react redux firebase
If you hates boilerplates, consider react firebase
and of course you can also build your own react firebase bindings through react context as just mentioned.

Categories