I am using Reactjs and firebase to create a Login Page in my application. I got an error that the 'firebase' is not defined in the part of onClick.
Here is my Log In Page code:
import React from 'react';
import { FacebookFilled, GoogleSquareFilled} from '#ant-design/icons';
import "firebase/app";
import { auth } from '../components/firebase';
const Login = () => {
return (
<div id="login-page">
<div id="login-card">
<h1>Welcome to SimpChat!</h1>
<h2 className="login-title">Login</h2>
<div className="login-button google"
onClick={() => auth.signInWithRedirect(new firebase.auth.GoogleAuthProvider())} //not defined
>
<GoogleSquareFilled style={{ fontSize: '20px' }} /> Sign In with Google
</div>
<br /><br />
<div className="login-button facebook"
onClick={() => auth.signInWithRedirect(new firebase.auth.FacebookAuthProvider())} //not defined
>
<FacebookFilled style={{ fontSize: '20px' }} /> Sign In with Facebook
</div>
</div>
</div>
);
}
export default Login;
and this is the firebase.js code:
import firebase from "firebase/compat/app";
import "firebase/compat/auth";
export const auth = firebase.initializeApp({
apiKey: "AIzaSyCqJv-aBQrcD-afBqQrI7uZJ-VCbWGBrD0",
authDomain: "simpchat-c8eb5.firebaseapp.com",
projectId: "simpchat-c8eb5",
storageBucket: "simpchat-c8eb5.appspot.com",
messagingSenderId: "692332223424",
appId: "1:692332223424:web:f6aac779101514b8544625",
measurementId: "G-PQXQBGPRSH"
}).auth();
You don't have firebase defined in your login page. Try updating the imports to:
// import "firebase/app";
import firebase from "firebase/compat/app";
I would highly recommend upgrading to Modular SDK as the compat version might be removed in future.
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.
I looked at the suggestions online for how to fix firebase, but they didn't work. I tried setting my firebase.json hosting feature where says "public" to "build", but that didn't work so what else should I do? I don't get errors when I compile it, but the website is blank when I run "npm start". Here is the relevant javascript code:
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
const firebaseApp = firebase.initializeApp({
apiKey: "AIzaSyBl_kNHH8oIn17VrR2mcKQqOn3eAZo-Osw",
authDomain: "instagram-clone-react-82ab7.firebaseapp.com",
projectId: "instagram-clone-react-82ab7",
storageBucket: "instagram-clone-react-82ab7.appspot.com",
messagingSenderId: "562669348604",
appId: "1:562669348604:web:ae6a7cee3832803e761979",
measurementId: "G-6PENZ2M8LS"
});
const db = firebaseApp.firestore();
const auth = firebase.auth();
const storage = firebase.storage();
export { db, auth, storage };
export default db;
App.js file code:
import React, { useState, useEffect } from 'react';
import './App.css';
import Post from './Post';
import { db } from './firebase';
function App() {
const [posts, setPosts] = useState([]);
//useEffect: Runs a piece of code based on a specific condition
useEffect(() => {
//this is where the code runs
db.collection('posts').onSnapshot(snapshot => {
//Everytime a new post is added, this line of code activates
setPosts(snapshot.docs.map(doc => doc.data()))
}) //"posts" inside of firebase also everytime a document gets modified inside of post it takes a screenshot
}, [] ); //conditions go here and there just variables
return (
<div className="App">
<div className="app__header">
<img
className="app__headerImage"
src="https://www.instagram.com/static/images/web/mobile_nav_type_logo.png/735145cfe0a4.png"
alt="instagram_text"
/>
</div>
<h1>Hello clever programmers let's build a react app!!!</h1>
{
posts.map(post => (
<Post username={post.username} caption={post.caption} imageUrl={post.imageUrl} />
))
}
</div>
);
}
export default App;
error in browser:
The issue is that you haven't imported Firebase Storage.
To fix it, simply add the import statement after you import firebase/compat/app, like below.
import firebase from "firebase/compat/app";
// After you import app...
import "firebase/compat/storage";
Now, when you call the function below with .ref(), it should work correctly.
const storage = firebase.storage().ref();
Try to use
const storage = firebase.storage().ref();
instead of
const storage = firebase.storage();
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
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 have created a React app and use firestore on it. I've tried to integrate firebase authentication to my app for authorizing logins, according to this document: https://firebase.google.com/docs/database/web/start
firebase.js :
import firebase from "firebase";
import "firebase/firestore";
import "firebase/auth";
const firebaseConfig = {
apiKey: ***,
authDomain: ***,
projectId: ***,
storageBucket: ***,
messagingSenderId: ***,
appId: ***,
measurementId: ***,
};
firebase.initializeApp(firebaseConfig);
export const db = firebase.firestore();
And I have a context file named AuthContext.js :
import React, { useState, useEffect, createContext } from "react";
import { authentication } from "./firestore";
export const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null);
useEffect(() => {
authentication.onAuthStateChanged((user) => {
setCurrentUser(user);
});
}, []);
return (
<AuthContext.Provider value={{ currentUser }}>
{children}
</AuthContext.Provider>
);
};
And this is App.js :
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Nav from "./pages/Routes/Nav";
import Footer from "./pages/Routes/Footer";
import Home from "./pages/Home";
import Search from "./pages/Search";
import Detail from "./pages/Detail";
import User from "./pages/User";
import LoginSignup from "./pages/LoginSignup";
import { AuthProvider } from "./utility/AuthContext";
function App() {
return (
<AuthProvider>
<Router>
<div>
<Nav />
<Switch>
<Route path="/" exact>
<Home />
</Route>
<Route path="/search">
<Search />
</Route>
<Route path="/detail/:id">
<Detail />
</Route>
<Route path="/user">
<User />
</Route>
<Route path="/LoginSignup">
<LoginSignup />
</Route>
</Switch>
<Footer />
</div>
</Router>
</AuthProvider>
);
}
export default App;
With this configuration, I got this error:
"It looks like you're using the development build of the Firebase JS SDK.
When deploying Firebase apps to production, it is advisable to only import
the individual SDK components you intend to use.
For the module builds, these are available in the following manner
(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):
CommonJS Modules:
const firebase = require('firebase/app');
require('firebase/<PACKAGE>');
ES Modules:
import firebase from 'firebase/app';
import 'firebase/<PACKAGE>';
Typescript:
import firebase from 'firebase/app';
import 'firebase/<PACKAGE>';"
And also:
Uncaught t {code: "auth/invalid-api-key", message: "Your API key is invalid, please check you have copied it correctly.", a: null}
I have tried to add these lines to firebase.js:
import firebase from "firebase/app"
And I have researched on Google and Stackoverflow but couldn't solve it. I am absolutely sure that the API key is correct. I checked it over and over. I think I'm missing something.
This is the screenshot of the error:
On these lines, what am I missing?
Swap import firebase from "firebase";. with import firebase from "firebase/app"; to get rid of the development build warning. Make sure you remove the original line or the error won't go away.
To fix the ID try going to https://console.firebase.google.com/u/0/project/[YOUR_PROJECT_ID]/settings/general/
Over there you should have a properly prefilled firebaseConfig that you can copy paste.