I am fairly new to react and I am trying out firebase. I am getting this error message
Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app)
and I have tried many things that didnt fix it.
This is how my config looks likes
export const config = {
apiKey: "AIzaSyCrfLCYS7VuvvUVaEkfzYVdJJLeqVuZHQE",
authDomain: "crudreac.firebaseapp.com",
databaseURL: "https://crudreac.firebaseio.com",
projectId: "crudreac",
storageBucket: "crudreac.appspot.com",
messagingSenderId: "116257347605"
};
And this is how I am TRYING to initialize the databse
import { config } from './Config/config';
import firebase from 'firebase/app';
import 'firebase/database'
import './App.css';
class App extends Component {
constructor(props){
super(props);
this.addNote = this.addNote.bind(this);
this.app = firebase.initializeApp(config);
console.log(firebase.app.name);
this.db = this.app.database().ref().child('notes');
this.state = {
notes:[],
}
}
I am probably doing the initialization wrong, so if anyone could help me out I would apreciate it
I have already tried doing
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
But it didnt help
Related
Firebase.js:
import firebase from "firebase";
const firebaseConfig = {
apiKey: <<API_KEY>>,
authDomain: "fir-42683.firebaseapp.com",
projectId: "fir-42683",
storageBucket: "fir-42683.appspot.com",
messagingSenderId: "950284829228",
appId: "1:950284829228:web:f9e6862d17650cfca38789",
measurementId: "G-VWT1P7ES8S"
};
export const db = firebase.initializeApp(firebaseConfig)
App.js
import {db } from './Firebase'
I wrote just a simple code for read data from firebase. but now, iam stuck on this error, what will i do.
ERROR in ./src/Firebase.js 3:0-32 Module not found: Error: Package path . is not exported from package D:\BROCAMP\Week 15\olx\node_modules\firebase (see exports field in D:\BROCAMP\Week 15\olx\node_modules\firebase\package.json)
The problem is const db = firebase.initializeApp(firebaseConfig)
You missed one step, this is actually const app = firebase.initializeApp(firebaseConfig)
Consider this hook which can get your db:
useGetFirestore.ts
import { getApp } from 'firebase/app';
import { getFirestore, Firestore } from 'firebase/firestore';
const useGetFirestore = (): Firestore => {
const app = getApp();
return getFirestore(app);
};
export default useGetFirestore;
The code you are calling db is actually app and that code just needs to run at the top of your app before anything:
const app = initializeApp(firebaseConfig);
Sometimes you only need this:
initializeApp(firebaseConfig);
I'm working on a project where I need to implement Firestore database in a React app, which I do like this: I have a firebase.js file in the src directory which contains information about Firebase and exports a db object,
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
// Firebase project configuration
const firebaseConfig = {
apiKey: ...
authDomain: ...
databaseURL: ...
projectId: ...
storageBucket: ...
messagingSenderId: ...
appId: ...
measurementId: ...
};
const app = initializeApp(firebaseConfig);
// Get a reference to the database service
const db = getFirestore(app);
export { db }
Then I try to import the db object from App.js,
import React, { Component } from 'react';
import { db } from './firebase'
class App extends Component {
render() {
return (
<div>
<h1>Hello</h1>
</div>
);
}
}
export default App;
And I get the following error in the console Uncaught SyntaxError: Cannot use import statement outside a module (at bundle.js:45109:2), as a result, the component does not render.
The line in which it seems to be a problem in bundle.js:45109:2 is this:
import { registerVersion } from '#firebase/app';
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'
im trying to initialize two firebase apps but getting an annoying error Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app). Im not sure how to fix this and how to make two seperate firebase. Any help is greatly appreciated!
database instance
import * as firebase from "firebase";
var config = {
apiKey: "AIzaSyC....",
authDomain: "car-app-506db.firebaseapp.com",
databaseURL: "https://car-app-506db.firebaseio.com",
projectId: "car-app-506db",
storageBucket: "car-app-506db.appspot.com",
messagingSenderId: "496521253390"
};
firebase.initializeApp(config);
const databaseRef = firebase.database().ref();
export const CarsRef = databaseRef.child("Cars");
export const authRef = firebase.auth();
export const provider = new firebase.auth.GoogleAuthProvider();
export const timeRef = firebase.database.ServerValue.TIMESTAMP;
export default databaseRef;
auth instance
import firebase from "firebase";
import 'firebase/auth';
import 'firebase/database';
var firebaseConfig = {
apiKey: "AIzaSyC6C-8A-vfsEzv31acwjhru8N64g0Hzhcc",
authDomain: "car-app-506db.firebaseapp.com",
databaseURL: "https://car-app-506db.firebaseio.com",
projectId: "car-app-506db",
storageBucket: "car-app-506db.appspot.com",
messagingSenderId: "496521253390"
};
var app = firebase.initializeApp(app);
export default app;
Each FirebaseApp instance has its own configuration and its own unique name. If you don't specify a name when you initialize the app, Firebase assumes your (re)initializing the default app. Since neither if your calls to firebase.initializeApp specifies a name, you're initializing the same app twice, which is an error.
The solution is to name your apps by passing a name (string) in to the second call to initializeApp. For example:
var firebaseConfig = {
apiKey: "AIzaSyC6C-8A-vfsEzv31acwjhru8N64g0Hzhcc",
authDomain: "car-app-506db.firebaseapp.com",
databaseURL: "https://car-app-506db.firebaseio.com",
projectId: "car-app-506db",
storageBucket: "car-app-506db.appspot.com",
messagingSenderId: "496521253390"
};
var app = firebase.initializeApp(firebaseConfig, "auth");
export default app;
Also see using multiple projects in your application in the Firebase docs.
I'm new in vue.js and I'm learning vue.js from documentation and tutorial on internet, now I'm trying make app with Firebase and vue.js but my when I run it, an error says:
-firebase not defined
However, I'm pretty sure that I imported it. Here my code:
main.js:
import Vue from 'vue'
import App from './App'
import router from './router'
import * as firebase from "firebase"
var config = {
apiKey: "###########",
authDomain: "###########",
databaseURL: "###########",
projectId: "###########",
storageBucket: "###########",
messagingSenderId: "###########"
};
firebase.initializeApp(config);
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
firebase,
components: { App },
template: '<App/>'
})
This my component register:
<template>
<div class="login">
<h3>Lets Register</h3>
<input type="email" v-model="email">
<input type="password" v-model="password">
<button v-on:click="register">Submit</button>
<p><router-link to="/Login"> Login? </router-link></p>
</div>
<script>
export default {
name: 'Register',
data () {
return{
email: '',
password: ''
}
},
methods:{
register : function(){
firebase.auth().createUserWithEmailAndPassword(this.email,this.password).then(
function (user) {
alert('Account been created')
},
function(err){
alert('opps'+ err.message)
}
);
}
}
}
Any help would be appreciated.
In main.js just register firebase as global with Vue.use(firebase) like this, and all components can access that.
import firebase from 'firebase'
Vue.use(firebase)
var config = {
apiKey: "####",
authDomain: "####",
databaseURL: "####",
projectId: "####",
storageBucket: "####",
messagingSenderId: "####"
};
firebase.initializeApp(config);
new Vue({
el: '#app',
render: h => h(App),
router : router,
firebase: firebase,
})
And in your components don't forget to import that like this:
import firebase from 'firebase'
It's really undefined at your component, I have with this problem too. How to solve it? Modules.
Create a Js file called firebase.service.js, on this file you'll define every function that uses firebase, you'll configure the firebase at this file too, then you'll export the functions to the other files, where you'll import and use them, just like this:
firebase.service.js
import * as firebase from 'firebase'
var config = { // put here your credentials
apiKey: apiKey,
authDomain: authDomain,
databaseURL: databaseURL,
projectId: projectId,
storageBucket: storageBucket,
messagingSenderId: messagingSenderId
}
firebase.initializeApp(config)
var auth = firebase.auth()
var db = firebase.database()
export function signOut (callback) {
auth.signOut().then(value => {
callback()
}, err => { callback(err) })
}
Components
<script>
import { signOut } from './firebase.services'
// use it here
</script>
You can't export firebase itself, because it'll throw an error saying that the firebase was already initialized.
You should import firebase in every component you want to use it in. Looks like you are importing firebase now in a different file so just add the import to the component.
Just adding some more info in case someone finds it useful. First off, only load components of firebase that you need. Gabriel Carneiro's response is really the base of the following...
Your firebase.js where you initialize and export your methods, modules, etc
/*this will import all the firebase which can be a bottleneck */
// import * as firebase from 'firebase'
/*better only importing what you need*/
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/functions';
const config = {
apiKey: "***************",
authDomain: "***************",
databaseURL: "***************",
projectId: "***************",
storageBucket: "***************",
messagingSenderId: "***************",
appId: "***************"
};
/*OptionalPrjName is optional that you can initialize your firebase with
it in case you are using more than one project or config file ,
it's optional as firebase can initialize without this name*/
firebase.initializeApp(config, "OptionalPrjName");
const auth = firebase.auth(firebase.app("OptionalPrjName"));
const firestore = firebase.firestore(firebase.app("OptionalPrjName"));
const functions = firebase.functions(firebase.app("OptionalPrjName"));
/*create modules ; say one for sign up , etc , another for functions, etc ... */
const app_firebase = {
signout: () => console.log(`firebase is` , firebase),
test: () => console.log(`testing`),
}
/*export them here so you can import them individually where you need in your components */
export {
app_firebase,
}
/*another way of only exporting your functions, etc. I like the above better becuase it helps bundling similar
functionalities together under a name space ; make sure you don't create confusion by assigning similar naming
so I always add something like app_ to my names in the above exports*/
export function fire_auth(callback) {
console.log(`firebase `, auth, firestore, functions);
}
your component, in which you can only import what you need to use (let call the component signup.vue) and say we have placed in the root of our directory so we access it in views like ../firebase :
<template>
<div class="signup">
<h2>signup</h2>
<button type="button" #click="signup">Sign Up</button>
<router-link to="/login">Login</router-link>
</div>
</template>
<script>
import { fire_auth, app_firebase } from '../firebase';
export default {
name: 'signup',
data() {
return {}
},
methods: {
signup: function() {
fire_auth();
app_firebase.test();
}
}
}
</script>
<style scoped>
/* scoped attr limits style to this component only */
</style>