in Firebase I am not able to upload image - javascript

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>
</>
);
}

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);

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

firebase_firebase__WEBPACK_IMPORTED_MODULE_5__.default.ref is not a function

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;

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

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'

Rewrite firebase service using dynamic import

Please help me to rewrite the code to use the dynamic import feature.
Unfortunately i have no idea how to use dynamic import in module.
import firebase from 'firebase/app';
import 'firebase/firestore';
const config = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
};
const initApp = firebase.initializeApp(config).firestore();
initApp.settings({
timestampsInSnapshots: true,
});
const app = firebase.app().firestore();
export default !firebase.apps.length ? initApp : app;
What i tried
import('firebase/app')
.then((firebase) => {
firebase.initializeApp(config).firestore();
});
That's because the firebase variable you want is in fact inside a default property. You could do something like this:
import('firebase/app')
.then(firebase => {
firebase.default.initializeApp(config).firestore();
});
A complete suggestion with async functions bellow:
// firebase-service.js
const firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MSG_SENDER_ID,
appId: process.env.FIREBASE_APP_ID
};
let db;
async function getFirestore () {
if (!db) {
const { default: firebase } = await import('firebase/app');
await import('firebase/firestore');
const app = firebase.initializeApp(firebaseConfig);
db = app.firestore();
}
return db;
}
export { getFirestore };

Categories