I can't import db to my app.
./src/Feed.js
Attempted import error: 'db' is not exported from './firebase'.
import * as firebase from 'firebase';
import 'firebase/firestore';
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
const firebaseApp=firebase.initializeApp(firebaseConfig);
const db=firebaseApp.firestore();
const auth=firebase.auth();
export default {db,auth};
I think this should work.
import * as firebase from 'firebase';
import 'firebase/firestore';
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
const firebaseApp = firebase.initialiseApp(firebaseConfig);
export const db = firebaseApp.firestore();
export const auth = firebase.auth();
// You can remove the export default.
The file i want to import db:
import React,{useState,useEffect} from 'react'
import './Feed.css'
import CreateIcon from '#mui/icons-material/Create';
import InputOption from './InputOption'
import ImageIcon from '#mui/icons-material/Image';
import SubscriptionsIcon from '#mui/icons-material/Subscriptions';
import EventNoteIcon from '#mui/icons-material/EventNote';
import CalendarViewDayIcon from '#mui/icons-material/CalendarViewDay';
import Post from './Post';
import { db } from"./firebase";
function Feed() {
const[posts,setPosts]=useState([]);
useEffect(()=>{
db.collection('posts').onSnapshot(snapshot=>{
setPosts(snapshot.docs.map(doc=>(
{
id:doc.id,
data:doc.data(),
}
)))
})
},[])
const sendPost=e=>{
e.preventDefault();
}
return (
<div className="feed">
<div className="feed_inputContainer">
<div className="feed_input">
<CreateIcon/>
<form>
<input type="text" placeholder="Start a post" />
<button onClick={sendPost} type="submit ">Send</button>
</form>
</div>
<div className="feed_inputOptions">
<InputOption Icon={ImageIcon} title='Photo' color="#70B5F9"/>
<InputOption Icon={SubscriptionsIcon} title="Video" color="#E7A33E"/>
<InputOption Icon={EventNoteIcon} title="Event" color="#C0CBCD"/>
<InputOption Icon={CalendarViewDayIcon} title="Write article" color="#7FC15E"/>
</div>
</div>
{posts.map(([post])=>{
<Post/>
})}
<Post name="Sonny Shanga" description='This is a test'
message='WOW this worked' />
</div>
)
}
export default Feed
Related
in firebase if I want to upload a file its not working perfectly, what is the mistake I did ,here I have use all the code in a one js file
import { React, useState } from "react";
import { initializeApp ,storage} from "firebase/app";
import "firebase/storage"
export default function Demo() {
const [search, setSearch] = useState("");
const firebaseConfig = {
apiKey: "VIzaSyDkgE2z3IIXr50AumPXmUfkoimM3f4z9d",
authDomain: "reactform-95c40.firebaseapp.com",
databaseURL: "https://reactform-65c50-default-rtd12.firebaseio.com",
projectId: "reactform-89c93",
storageBucket: "reactform-67c52.appspot.com",
messagingSenderId: "793300985055",
appId: "1:793300985055:web:aa37c4b76870f21f6d9a90"
};
initializeApp(firebaseConfig);
const upload = (e)=>{
if(search == null)
return;
storage.ref(search.name).put(search)
.on("state_changed" , alert("success"));
}
return (
<>
<input type="file" onChange={(e)=>{setSearch(e.target.files[0]);console.log('loading...')}}/>
<button onClick={(e)=>{upload(e)}}>Upload</button>
</>
);
}
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
its giving me the error cant figure it out i think its related to the firebase.js but same configuration working in other project fine but this one has that issue.
import React, { useState } from 'react';
import uuid from 'react-uuid';
import { useSelector, useDispatch } from 'react-redux';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import database from '../firebase/firebase';
const AddTasks = () => {
const dispatch = useDispatch();
const newLocal = null;
const [selectedDate, setSelectedDate] = useState(newLocal);
const [task, setTask] = useState('');
const date = new Date()
const userId = useSelector(state => state.auth.currentUser);
const addTask = () => {
const payload = { id: uuid(), text: task, completed: false, addedAt: selectedDate.toString() }
here its giving me that error i will also share my firebase.js after this
const dbtasksWrapper = database.ref().child(userId).child('tasks');
return dbtasksWrapper.child(payload.id).update(payload).then(() => {
setTask('');
setSelectedDate(null);
dispatch({ type: "ADD_TASKS", payload })
})
}
return (
<form onSubmit={e => {
e.preventDefault(e.target.value);
addTask();
}}>
<input className="input-group-prepend"
value={task}
placeholder="Enter your Task"
onChange={e => setTask(e.target.value)}
/>
<DatePicker className="input-group-prepend" placeholderText="Enter task date " selected={selectedDate} onChange={(date) => setSelectedDate(date)} showTimeSelect timeFormat="HH:mm" timeIntervals={15} timeCaption="time" dateFormat="MMMM d, yyyy H:mm aa" minDate={date} /><br />
<input className="btn btn-primary" type='submit' value='Submit' />
</form>
);
};
export default AddTasks;
here is my firebase.js file dont know how to get rid of this issue
import app from 'firebase/app';
import 'firebase/auth';
import "firebase/firestore";
import "firebase/database"
var firebaseConfig = {
apiKey: "AIzaSyAM7bXNJc-BlyLjUK23laYxDXSdqrg5m0A",
authDomain: "hse-project-aefd3.firebaseapp.com",
databaseURL: "https://hse-project-aefd3-default-rtdb.firebaseio.com",
projectId: "hse-project-aefd3",
storageBucket: "hse-project-aefd3.appspot.com",
messagingSenderId: "651568614628",
appId: "1:651568614628:web:2d0e91e352bbe6ef6970f1"
};
const firebase = app.initializeApp(firebaseConfig);
// Get a reference to the database service
export const database = firebase.database();
export default firebase;
There is no exported module "app" in "firebase/app"
You should import firebase from 'firebase/app'
import firebase from 'firebase/app';
import 'firebase/auth';
import "firebase/firestore";
import "firebase/database"
var firebaseConfig = {
apiKey: "AIzaSyAM7bXNJc-BlyLjUK23laYxDXSdqrg5m0A",
authDomain: "hse-project-aefd3.firebaseapp.com",
databaseURL: "https://hse-project-aefd3-default-rtdb.firebaseio.com",
projectId: "hse-project-aefd3",
storageBucket: "hse-project-aefd3.appspot.com",
messagingSenderId: "651568614628",
appId: "1:651568614628:web:2d0e91e352bbe6ef6970f1"
};
const app = firebase.initializeApp(firebaseConfig);
// Get a reference to the database service
export const database = app.database();
export default firebase;
I am building Vue SPA and have checked many posts before posting this.
I am not sure what I am doing wrong.
Below is my App.Vue:
<template>
<div id="app">
<Navigation />
<router-view class="container" :user="user" />
</div>
</template>
<script>
import Navigation from '#/components/Navigation.vue';
// import db from './db.js';
import Firebase from 'firebase';
export default {
name: 'App',
data: function() {
return {
user: null,
};
},
mounted() {
Firebase.auth().onAuthStateChanged(user => {
if (user) {
this.user = user.email;
}
});
},
components: {
Navigation,
},
};
</script>
<style lang="scss">
$primary: #37c6cf;
#import '../node_modules/bootstrap/scss/bootstrap';
</style>
Note: I have commmented the import from db.js which can be find after the first import. If I enable it Vue CLI is throwing different error.
in db.js:
import firebase from 'firebase';
const firebaseConfig = {
apiKey: 'yourkey',
authDomain: 'domainnew.firebaseapp.com',
databaseURL: 'yourdomain.com',
projectId: 'yourproject',
storageBucket: 'test',
messagingSenderId: '454545',
appId: '1:444d96:web:d78df',
measurementId: 'G-69599595',
};
// Initialize firebase
const firebaseApp = firebase.initializeApp(firebaseConfig);
firebase.analytics();
export default firebaseApp.firestore();
In the console I am keep getting below two errors and my Vue is not retrieving my email address from Firebase.
Can any one pleas help on this.
The following should do the trick:
db.js file
import firebase from 'firebase/app';
import "firebase/analytics";
import 'firebase/firestore';
import 'firebase/auth';
const firebaseConfig = {
apiKey: 'yourkey',
authDomain: 'domainnew.firebaseapp.com',
databaseURL: 'yourdomain.com',
projectId: 'yourproject',
storageBucket: 'test',
messagingSenderId: '454545',
appId: '1:444d96:web:d78df',
measurementId: 'G-69599595',
};
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
const auth = firebase.auth();
const analytics = firebase.analytics();
export { db, auth, analytics };
App.js file
<template>
<div id="app">
<Navigation />
<router-view class="container" :user="user" />
</div>
</template>
<script>
import Navigation from '#/components/Navigation.vue';
const fb = require('./db.js');
export default {
name: 'App',
data: function() {
return {
user: null,
};
},
mounted() {
fb.auth.onAuthStateChanged(user => {
if (user) {
this.user = user.email;
}
});
},
components: {
Navigation,
},
};
</script>
<style lang="scss">
$primary: #37c6cf;
#import '../node_modules/bootstrap/scss/bootstrap';
</style>
I have a vue App with vuefire installed. Following the docs here: https://vuefire.vuejs.org/vuefire/getting-started.html#plugin, I have the main.js file :
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { firestorePlugin } from 'vuefire'
Vue.config.productionTip = false;
Vue.use(firestorePlugin);
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
and the firebase.js file like this:
import firebase from "firebase";
const config = {
apiKey: "XXXXXX",
authDomain: "XXXXX",
databaseURL: "XXXXX",
projectId: "XXXXXXX",
storageBucket: "XXXXXX",
messagingSenderId: "XXXXXXX",
appId: "XXXXX"
};
firebase.initializeApp(config);
export const db = firebase.firestore();
And here is the home component
<template>
<div>
<button #click="signIn">Log in with google</button>
</div>
</template>
<script>
import firebase from "firebase";
import db from "#/firebase"
export default {
methods: {
signIn() {
const provider = new firebase.auth.GoogleAuthProvider();
firebase
.auth()
.signInWithPopup(provider)
.then(result => {
const malakas = {
userId: result.user.uid,
email: result.user.email,
displayName: result.user.displayName,
photoURL: result.user.photoURL
};
db.collection("malakes")
.doc(result.user.uid)
.set(spreadOparatorTest, { merge: true });
})
.catch(err => console.log(err));
}
}
};
</script>
<style lang="scss" scoped>
</style>
the weird thing is that in db.collection(...) i get:
TypeError: Cannot read property 'collection' of undefined
because the db that i am importing gets imported as undefined. But if I change the db.collection(...) to firebase.firestore().collection(...) it works fine but i do not understand why.
the problem is that you need to import a few dependencies separately... this is a good safe way:
import firebase from "firebase/app";
require('firebase/firestore')
require('firebase/auth')
const config = {
apiKey: "XXXXXX",
authDomain: "XXXXX",
databaseURL: "XXXXX",
projectId: "XXXXXXX",
storageBucket: "XXXXXX",
messagingSenderId: "XXXXXXX",
appId: "XXXXX"
};
firebase.initializeApp(config);
export const db = firebase.firestore();
export const auth = firebase.auth();
then your components can import em like this:
import firebase from 'firebase/app'
import { db, auth } from "./firebase" // <--- or wherever the config file is
export default {
methods: {
signIn() {
const provider = new firebase.auth.GoogleAuthProvider();
auth
.signInWithPopup(provider)
.then(result => {
const malakas = {
userId: result.user.uid,
email: result.user.email,
displayName: result.user.displayName,
photoURL: result.user.photoURL
};
db.collection("malakes")
.doc(result.user.uid)
.set(spreadOparatorTest, { merge: true });
})
.catch(err => console.log(err));
}
}
};
Hope this helps!