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;
Related
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 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>
</>
);
}
The function createUserWithEmailAndPassword is not being called within SignUpUser function when onClick event happening. But when I do onClick={signUpUser(email,password)} it works
import React from 'react';
import styled from 'styled-components';
import { useState } from 'react';
import { signUpUser } from '../firebase';
function SignUpComponent() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
return (
<AuthForm>
<input type="text"
placeholder="Email"
name="email"
value={email}
onChange={(e) => setEmail(e.target.value)}/>
<input type="password"
name="password"
placeholder="password"
value={password}
onChange={(e) => setPassword(e.target.value)}/>
<SubmitFormButton
type="submit"
onClick={() => signUpUser(email,password)}
>
Sign Up
</SubmitFormButton>
</AuthForm>
)
};
Here is my firebase.js file
import { initializeApp } from "firebase/app";
import {
getAuth,
onAuthStateChanged,
signInWithPopup,
signOut,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
} from 'firebase/auth';
const firebaseConfig = {
apiKey: ****,
authDomain: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const auth = getAuth();
auth.useDeviceLanguage();
// Auth functions
export function signUpUser(email, password) {
if (password.length < 6) {
alert('Password is too short');
return;
};
˚˚createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
alert('Signed up Successfully', user);
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert(errorMessage);
});
};
onClick={signUpUser(email,password)}
Here the signUpUser is called during a render, no matter if clicked or not.
If it works that way and does not work with
onClick={() => signUpUser(email,password)}
then there are no other options but your SubmitFormButton does not trigger onClick. Maybe it is not passed to the DOM at all.
The problem is that the Auth form should implement "onSubmit" method. We should not call the function on the SubmitFormButton component
I am working on a basic CRUD TODO list using React and Firebase. Everything works fine with the app, but when I want to use environment variables, the app cant load the history of todos that I previously added. It still runs as usual, but the when I refresh the page there seems to be no history of the TODOs I added. Furthermore, when I remove the environmental variables, and just use the credentials, the app brings up the previous history and works as it's supposed to.
These are the files. I already installed dotenv just to let you know.
firebase.js
import firebase from "firebase";
require("dotenv").config();
const firebaseApp = firebase.initializeApp({
apiKey: process.env.NEXT_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_MESSAGE_SENDER_ID,
appId: process.env.NEXT_PUBLIC_APP_ID,
});
const db = firebaseApp.firestore();
export default db;
app.js
import React, { useState, useEffect } from "react";
import "./App.css";
import Todo from "./Todo";
import Button from "#material-ui/core/Button";
import FormControl from "#material-ui/core/FormControl";
import Input from "#material-ui/core/Input";
import InputLabel from "#material-ui/core/InputLabel";
import db from "./firebase";
import firebase from "firebase";
require("dotenv").config();
function App() {
const [todos, setTodos] = useState([]);
const [inputs, setInputs] = useState("");
useEffect(() => {
db.collection("todos")
.orderBy("timestamp", "desc")
.onSnapshot((snapshot) => {
setTodos(
snapshot.docs.map((doc) => ({ id: doc.id, todo: doc.data().todo }))
);
});
}, []);
const addToDo = (event) => {
event.preventDefault();
db.collection("todos").add({
todo: inputs,
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
});
setInputs("");
};
return (
<div className="App">
<h1>Hello</h1>
<form>
<FormControl>
<InputLabel>Write a to do</InputLabel>
<Input
type="text"
value={inputs}
onChange={(event) => setInputs(event.target.value)}
/>
</FormControl>
<Button
disabled={!inputs}
variant="contained"
color="primary"
type="submit"
onClick={addToDo}
>
Add to do
</Button>
</form>
<ul>
{todos.map((todo) => (
<Todo todo={todo} />
))}
</ul>
</div>
);
}
export default App;
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