Firebase signinwithemailandpassword is giving tenantid error. I don't get it. Why this error. Any help, pls ?
edit:
i searched on google with no help, thats why i posted in here. any one with any hint even, so that i can move forward
edit 2 - code:
...
import { auth } from "../../firebaseConfig";
import { signInWithEmailAndPassword } from "firebase/auth";
...
signInWithEmailAndPassword(auth, userCreds.email, userCreds.password).then((response) => {
}).catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
}).finally(() => {
});
Import auth from firebaseInit rather than importing it from firebaseConfig.
Change the auth import to below code
import { auth } from "../../firebaseInit"
issue resolved...
instead of calling config file
import { auth } from "../../firebaseConfig";
i must have called init file
"import { auth } from "../../firebaseInit";"
i have initialzed auth in init file and not in config file... my bad
Related
I tried to create authentication on react, but now I am currently stuck as my try and catch block is not working. When I click the signup button, I am not getting any error nor any response from the site. No user is uploaded to the Firebase database.
The Code is Given Below.
import React,{useRef,useState} from 'react'
import {Form,Button,Card,Alert} from 'react-bootstrap'
import {useAuth} from '../Context/AuthContext'
function Signup() {
const emailRef=useRef()
const passwordRef=useRef()
const passwordConfirmRef=useRef( )
const {signup} =useAuth();
const [error,setError]=useState();
const [loading,setLoading]=useState(false);
async function handleSubmit(e){
e.preventDefault()
if(passwordRef.current.value!==passwordConfirmRef.current.value){
return setError("Passwords Do Not Match")
}
try{
setError("");
setLoading(true);
await signup(emailRef.current.value,passwordRef.current.value)
}
catch {setError("Failed To Create An Account")}
setLoading(false);
}
}
export default Signup
Try catch block looks like this:
try {
...
} catch(e) {
console.log(e.message)
}
Are you sure you paste correct code ? Signup() don't have closing brackets. I don't see in your code that you're importing signup() function. And your main function is named Signup() this is not a good practice. A good name for your function can be onSignUp() instead of Signup().
The Submit Button Type Was Not Mentioned In The Above Code. So It Was Not Submitting And Hence No Error Were Shown In The Console.
So Just Add type='submit' To The Submit Button And The Code Will Work Properly.
So basically the console is showing me that I have an unexpected token but I don't think there is any unexpected token. Please help me. I have taken way too much time trying to fix this problem. Here is the code -
import React from 'react';
import firebase from 'firebase';
export default function App() {
// I have deleted this information because I don't want anyone to access my data
const firebaseConfig = {};
firebase.initializeApp(firebaseConfig);
function signInWithGoogle() {
var google_provider = new firebase.auth.GoogleAuthProvider();
firebase
.auth()
.signInWithPopup(google_provider)
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
});
}
return (
<div>
<h1>Google Sign In Authentication</h1>
<button onClick={signInWithGoogle}>Sign In</button>
</div>
);
}
The only issue I see in the provided code is you have not imported the Firebase Auth SDK. You can import that as shown below:
import firebase from 'firebase';
import "firebase/auth"
Also make sure you are using V8.X.X or lower with above code. If you have new Modular SDK V9.0.0+ then change your imports to compat version to keep using existing code:
import firebase from 'firebase/compat/app';
import "firebase/compat/auth"
I'm using firebase stripe extension "run subscriptions with stripe". In this extension integration i'm not able to redirect the checkout page (redirectToCheckout function did not work)..Any ideas how can i do that???
Here is my stripe webhooks events:
customer.subscription.updated
customer.subscription.deleted
customer.subscription.created
checkout.session.completed
price.updated
price.deleted
price.created
product.updated
product.deleted
product.created
Here is my first screen code in which user is creating...!
import firebase from 'firebase';
// import getStripe from './stripe';
import { loadStripe } from '#stripe/stripe-js/pure';
import '#stripe/stripe-js';
import redirectToCheckout from '#stripe/stripe-js';
const firestore = firebase.firestore();
firebase.auth().onAuthStateChanged((user) => {
if (user) {
console.log(user.uid)
// User logged in already or has just logged in.
} else {
// User not logged in or has just logged out.
}
});
export async function createCheckoutSession(){
let uid = "static uid";
const checkoutSessionRef = await firestore.collection('stripe').doc(uid).collection('checkout_sessions').add(
{price : 'price id',
success_url : 'https://localhost:3000/success',
cancel_url: 'https://localhost:3000/fail',
});
checkoutSessionRef.onSnapshot(async (snap) => {
const {error , sessionId} = snap.data();
if (error) {
// Show an error to your customer and
// inspect your Cloud Function logs in the Firebase console.
alert(`An error occured: ${error.message}`);
}
if (sessionId) {
const stripe = await loadStripe('pk_test_1234');
stripe.redirectToCheckout({ sessionId });
}
});
}
I am using the same code and it's working fine. The only difference I see here which might be the reason for your problem is that you are importing loadStripe from #stripe/stripe-js/pure which might need to be from "#stripe/stripe-js" and I don't think you need any other stripe import, for example, your imports should be like
import firebase from 'firebase';
import { loadStripe } from '#stripe/stripe-js';
I have these imports and they are working fine
I am trying to figure out how to add authentication to a react app that uses Cloud Firestore rather than Realtime Database.
I followed this tutorial and got the whole thing working. Then - the change I'm trying to add is the move from Realtime Database to Cloud Firestore - this makes a difference to whether authentication works. I have made 20 new projects to try to get this work - totally without the process in the tutorial and just relying on firebase documentation. None of them work.
Currently, I have a config file with:
import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import firestore from "firebase/firestore";
class Firebase {
constructor() {
app.initializeApp(config).firestore();
this.auth = app.default.auth();
// this.db = app.firebase.database()
this.db = app.firestore();
}
Then, i have a form with this submit handler:
import Firebase from '../../../firebase.1';
handleCreate = () => {
const { form } = this.formRef.props;
form.validateFields((err, values) => {
if (err) {
return;
};
const payload = {
// ...values,
name: values.name,
email: values.email,
organisation: values.organisation,
beta: values.beta,
role: values.role,
// createdAt: Firebase.FieldValue.serverTimestamp()
}
console.log("formvalues", payload);
Firebase
.auth()
.createUserWithEmailAndPassword(values.email, values.password)
console.log('Received values of form: ', values);
Firebase
.collection("users")
.add(payload)
// .then(docRef => {
// resetForm(initialValues);
// })
.then(e => this.setState({ modalShow: true }))
form.resetFields();
this.setState({ visible: false });
this.props.history.push(DASHBOARD);
});
};
At the moment, when I console.log(Firebase) I get:
Uncaught ReferenceError: Firebase is not defined
I have seen this post and followed each one of the recommendations in all of the answers.
I have tried changing the config file uses:
this.auth = app.default.auth();
It makes no difference.
When I try to use this, i get an error that says:
TypeError: _firebase_1__WEBPACK_IMPORTED_MODULE_14__.default.auth is not a function
Does anyone know how to use auth with firebase - where there is a Cloud Firestore instead of a Realtime Database - it's so weird that this makes a difference to whether the authentication tool works.
I've turned off the timestamp entry because I can't get firestore to record that either - but that is a problem for another day. I'm really trying to figure out how to use the authentication tool for now.
NEXT ATTEMPT
I tried to change the firebase.js file so that the config now looks like this:
import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
const devConfig = {
};
const prodConfig = {
};
const config =
process.env.NODE_ENV === 'production' ? prodConfig : devConfig;
const Firebase = app.initializeApp(config);
const database = app.firestore();
const auth = app.auth();
const settings = { timestampsInSnapshots: true };
export { Firebase, database as default, settings, auth };
Now, I get an error that says:
TypeError: _components_firebase__WEBPACK_IMPORTED_MODULE_2__.default
is not a constructor
I have been googling - what is a constructor. What is a webpack imported module number reference etc for the last few hours. I would love to know how to translate these error messages into something understandable.
Googling this exact error message suggests that something is wrong with the way the import and export statements are made. The new export in firebase.js is unusual (but others on Stack Overflow have tried it with problems using Firebase). It's still a question mark for me because I don't understand what the error message means.
The error message points to this line of my src/index.js
ReactDOM.render(
<FirebaseContext.Provider value={new Firebase()}>
That line comes from:
import FirebaseContext, { withFirebase } from './Context';
import Firebase from '../../firebase.1';
export default Firebase;
export { FirebaseContext, withFirebase };
That file imports from:
import React from 'react';
const FirebaseContext = React.createContext(null);
export const withFirebase = Component => props => (
<FirebaseContext.Consumer>
{firebase => <Component {...props} firebase={firebase} />}
</FirebaseContext.Consumer>
);
export default FirebaseContext;
It would be a huge reveal if anyone has any advice for learning how to learn what error messages mean. For the moment I'm guessing.
I just finished the tutorial recently also, but I simplified my firebase file. I export only the reference to the initialised firebase
import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
const config = {
//...
};
const firebase = app.initializeApp(config);
export default firebase;
And in my project I have:
//...
import firebase from '../../firebase';
//...
useEffect(() => {
const listener = firebase
.firestore()
.collection(COLLECTIONS.USERS)
.onSnapshot(querySnapshot => {
setUsers(querySnapshot);
querySnapshot.forEach(doc => console.log(doc.id, doc.data()));
});
return listener;
}, []);
//...
Check out my Github project here -> https://github.com/henev/react-auth-with-firebase
https://github.com/MrFiniOrg/AxiosQuestion
I would like to have my project setup so that I do not have to specify the same request header in every http call.
I have searched this online but I have not been able to accomplish this in my project.
Would someone please assist me in resolving this issue I am having.
I am new to react and axios and I am not sure how to configure this.
My project seems to be doing this but it is sending the request 2 times.
One with the header and one without.
My axios call can be found in the app.js class component
You can specify config defaults that will be applied to every request.
Global axios defaults
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
For more specific info, please visit their docs.
UPDATE:
You can do it in two ways:
1. In your index.js file [meaning the top-level aka 'root' file] you can configure your request/ response methods. Something like this:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import axios from 'axios';
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
axios.defaults.headers.common['Authorization'] = 'AUTH TOKEN';
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.interceptors.request.use(request => {
console.log(request);
// Edit request config
return request;
}, error => {
console.log(error);
return Promise.reject(error);
});
axios.interceptors.response.use(response => {
console.log(response);
// Edit response config
return response;
}, error => {
console.log(error);
return Promise.reject(error);
});
ReactDOM.render( <App />, document.getElementById( 'root' ) );
registerServiceWorker();
2. Or you can create a new file, a new instance of your axios.js file to be precise, and import the configurations separately in your components where you might need them. You could name it, eg axiosConfig.js, and put your specific configs inside of it. Something like this:
axiosConfig.js
// First we need to import axios.js
import axios from 'axios';
// Next we make an 'instance' of it
const instance = axios.create({
// .. where we make our configurations
baseURL: 'https://api.example.com'
});
// Where you would set stuff like your 'Authorization' header, etc ...
instance.defaults.headers.common['Authorization'] = 'AUTH TOKEN FROM INSTANCE';
// Also add/ configure interceptors && all the other cool stuff
instance.interceptors.request...
export default instance;
After that you would import this file to components that need it and use it instead of the previous Axios [node_modules] import, like this:
Example.js
import React, { Component } from 'react';
// import axios from 'axios'; We don't need this anymore
import axiosConfig from '../../axiosConfig'; // But instead our new configured version :)
class Example extends Component {
state = {
data: [],
error: false
}
componentDidMount () {
// We could name (import) it as axios instead, but this makes more sense here ...
axiosConfig.get('/posts' )
.then(response => {
this.setState({data: response});
});
})
.catch(error => {
this.setState({error: true});
});
}
NOTE: You can combine these two methods as needed, but remember that the configurations made in your configAxios.js file will overwrite those made in your index.js file [if they are the same configurations, that is :) ]
Using interceptors, it runs on each request so if the token changes (refreshes) then the next request picks up the new token. Check for existing values in the request to allow overriding of the header. Consider we are using any token generator and updating token in local storage. Here we are using keyclock object that is stored in localStorage
import * as axios from "axios";
axios.defaults.baseURL = process.env.REACT_APP_BASE_URL;
axios.interceptors.request.use(
config => {
if (!config.headers.Authorization) {
const token = JSON.parse(localStorage.getItem("keyCloak")).token;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
}
return config;
},
error => Promise.reject(error)
);
I also had the same issue and solution was to locate them in index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import axios from 'axios';
import './index.css';
import 'bootstrap/dist/css/bootstrap.css';
import App from './components/app/App';
import * as serviceWorker from './serviceWorker';
axios.defaults.baseURL = process.env.REACT_APP_BE_URL;
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root'),
);
serviceWorker.unregister();
Also, I use .env files to keep for example base urls:
.env.production
REACT_APP_BE_URL=http://production-url-to-backend/
.env.development
REACT_APP_BE_URL=http://localhost:3000/
And when you run locally .env.development will be used, for production build (npm run build) .env.production will be used.
More about axios global confg: https://github.com/axios/axios#global-axios-defaults
More about .env: https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
You can put it in a file (as explained here) and then import it in the top level
import { CssBaseline } from "#mui/material";
import "./App.css";
import ProfilePage from "./view/Profile/ProfilePage";
import "./service/axios-config"; //<---import it here
function App() {
return (
<div className="App">
<CssBaseline />
<ProfilePage />
</div>
);
}
export default App;
instead of adding this code in the top level:
axios.defaults.baseURL = process.env.REACT_APP_BE_URL;
I have a simple minimalistic method of setting axios config for request header and it handles global error.
import axios, { AxiosError, AxiosHeaders } from "axios";
import useAuthStore from "../hooks/useAuthStore";
import { BASE_URL } from "./config";
import { getItem } from "./storage";
const axiosInstance = axios.create({
baseURL: `${BASE_URL}`,
headers: {
"Access-Control-Allow-Origin": "*",
},
});
axiosInstance.interceptors.request.use(
async (config) => {
const token = await getItem("jwtToken");
if (config.headers)
(config.headers as AxiosHeaders).set("Authorization", `Bearer
${token}`);
return config;
},
(error) => Promise.reject(error),
);
axiosInstance.interceptors.response.use(
(response) => response,
(error) => {
if (error instanceof AxiosError && error.response?.status === 401)
{
useAuthStore.setState({ signedInAs: undefined });
}
return Promise.reject(error);
},
);
export default axiosInstance;
Note: The base URL is imported from another file while the useAuthStore is a custom hook from zustand that store the user state for authorization.