How can I add data into Firebase Web 9.0.0? - javascript

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

Related

when I try to get a data from the firebase I get error in the console

I have a 'products' collection in the firebase ,in my project I have a Products page that contain a list of all the products name each name is a link for edit product page ,in the edit product page I want to took the id from the URL Through use params, and get all the data about this product but I have error in the console that said :
Uncaught (in promise) Type Error: firebase__WEBPACK_IMPORTED_MODULE_1_.default. Collection is not a function
at fetch Data
this is my code in the firebase page:
import { initializeApp } from "firebase/app";
import {getFirestore} from "firebase/firestore"
const firebaseConfig = {
apiKey: "xxxxxx",
authDomain: "xxxxxx.firebaseapp.com",
projectId: "xxxxxx",
storageBucket: "xxxx.appspot.com",
messagingSenderId: "xxx",
appId: "xxxxxx",
measurementId: "xxxxxx"
};
const app = initializeApp(firebaseConfig);
const dB = getFirestore(app)
export default db
and that the code in the editproduct page :
import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import dB from '../firebase';
const EditProduct = () => {
const { id } = useParams();
const [product, setProduct] = useState({});
useEffect(() => {
const fetchData = async () => {
const snapshot = await dB.collection('Products').doc(id).get();
setProduct(snapshot.data)
}
fetchData();
}, [id])
}

Firebase - React: cannot read properties of undefined (reading 'auth')

The login.js is where the "Cannot read properties of undefined (reading 'auth')" coming from I would guess
Login.js:
import { useContext, useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import FirebaseContext from "../context/firebase";
import * as ROUTES from "../constants/routes";
export default function Login() {
const navigate = useNavigate();
const { firebase } = useContext(FirebaseContext);
const [emailAddress, setEmailAddress] = useState(" ");
const [password, setPassword] = useState(" ");
const [error, setError] = useState(" ");
const isInvalid = password === "" || emailAddress === "";
const handleLogin = async (event) => {
event.preventDefault();
try {
await firebase.auth().signInWithEmailAndPassword(emailAddress, password);
navigate.push(ROUTES.HOMEPAGE);
} catch (error) {
setEmailAddress(" ");
setPassword(" ");
setError(error.message);
}
};
useEffect(() => {
document.title = "Login - Bits&Bots";
}, []);
return (
<div className="login__container">
<div className="loginform">
<p>I will be the form</p>
{error && <p classname="error-text">{error}</p>}
<form onSubmit={handleLogin} method="POST">
<input
aria-label="Enter your email addres"
type="text"
placeholder="Email address"
classname="login__input"
onChange={({ target }) => setEmailAddress(target.value)}
/>
<input
aria-label="Enter your password"
type="password"
placeholder="Password"
classname="login__input"
onChange={({ target }) => setPassword(target.value)}
/>
<button disabled={isInvalid} type="submit" classname="login__submit">
Log in
</button>
</form>
</div>
<div className="create__account">
<p>
Don't have an account?{``}
<Link to="/signup" className="signup__link">
Sign up
</Link>
</p>
</div>
</div>
);
}
so there is a "import FirebaseContext from "../context/firebase";" in this file.
What contains inside that firebase.js file is:
import { createContext } from "react";
const FirebaseContext = createContext(null);
export default FirebaseContext;
So I cant seem to understand why the text "Cannot read properties of undefined (reading 'auth')" appearing when typing inside the form.
Here is a image of it:
If more detailed needed, here is the index.js file:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import FirebaseContext from "./context/firebase";
import { db, analytics, FieldValue, auth } from "./lib/firebase";
ReactDOM.render(
<FirebaseContext.Provider value={{ db, analytics, FieldValue, auth }}>
<App />
</FirebaseContext.Provider>,
document.getElementById("root")
);
and different firebase.js file from /lib
import firebase from "firebase/compat/app";
import "firebase/compat/firestore";
import "firebase/compat/analytics";
import "firebase/compat/auth";
// // here i want to import the seed file
// import { seedDatabase } from "../seed";
const firebaseConfig = {
apiKey: "0",
authDomain: "0",
projectId: "0",
storageBucket: "0",
messagingSenderId: "",
appId: "0",
measurementId: "0",
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const analytics = firebaseApp.analytics();
const auth = firebase.auth();
const FieldValue = db.FieldValue;
console.log(db);
// seedDatabase(db, "db");
export { db, analytics, FieldValue, auth };
I will apprechiate all the help i can get.
I'd suggest you read up on the differences between firebase v8 and v9, some of the instantiation of the firebase functions there is of v8 while some v9. I haven't used firebase for that long but in v9, a simple auth instantiation would look like this:
firebase.js
import { initializeApp } from 'firebase/app';
const firebaseConfig = {
apiKey: "0",
authDomain: "0",
projectId: "0",
storageBucket: "0",
messagingSenderId: "",
appId: "0",
measurementId: "0",
};
export default const firebaseApp = initializeApp(firebaseConfig);
And in another file e.g. login.js
import Firebase from "../Firebase";
import {getAuth, signInWithEmailAndPassword} from "firebase/auth"
var auth = getAuth(Firebase);
//more code over here
const mainFunc = () => {
//more code here
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
});
}
I know the compat library is there to offer backward compatibility to v8 but unless your project is super huge or something, I'd recommend you use the v9 way of doing things. It's cleaner.
heres a link to the firebase docs : https://firebase.google.com/docs/web/modular-upgrade
Regards.

in Firebase I am not able to upload image

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

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'

Categories