Login Page With React On Firebase - reactjs

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.

Related

firebase signinwithemailandpassword tenanid error

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

axios is not working in react project but fetch working fine

axios code:
import Axios from "axios";
export const getBlogPosts = async (setter) => {
try {
const res = await Axios.get(`https://jsonplaceholder.typicode.com/posts/1`);
if (res.status === 200 && res?.data) {
setter(res?.data);
}
} catch (error) {
console.log(error.message);
}
};
this is my app code :
import React, { useEffect, useState } from "react";
import { getBlogPosts } from "./_helper";
export function TestCustomerCreate() {
const [gridData, setGridData] = useState();
useEffect(() => {
getBlogPosts(setGridData);
}, []);
console.log(gridData);
return (
<div>
<h1>This is test create form</h1>
</div>
);
}
error msg: Request failed with status code 404
but when i'm using fetch its working fine (i'm using "axios": "0.19.2" with Metronic theme react (7.0.8)
Reason for this is in Metronic use axios-mock-adapter for demo purpose, it intercepts axios requests and redirects to mocked handlers. Mock Back-end
To use real REST APIs need to do 2 things.
remove mock initialization. For that remove mock initialization in
the src/index.js or src/main.js file.
Remove API initialization from the src/index or src/main.js
// Remove this to disable mock API
MockService.init();
// API service init
ApiService.init();

Stripe redirectToCheckout didn't work in React with firebase stripe extension..! Any suggestions?

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

Trying to remove Token from local storage on "Logout" button

I'm creating a basic login form that stores token with whatever credentials are entered. In my useToken.js I've created an arrow function that should remove Token:
const removeToken = (userToken) => {
localStorage.removeItem("token");
setToken(null);
};
In my header I got Logout button that should removeToken and logout user when it's clicked. My Header.js button that should Logout an user looks like this:
<Button variant="danger" onClick={removeToken}>
LogOut
</Button>
It throws the removeToken is not defined error.
localStorage.clear();
Check this out (:
Based on throwed the definition error, it seems that you haven't import function removeToken to the module where you are trying to use. So export it first then import it and then use.
The code with fix could look like that
useToken.js
export const removeToken = (userToken) => { // export function from module
localStorage.removeItem("token");
setToken(null);
}
Header.js
import { removeToken } from './useToken.js' // import removeToken function from useToken.js module
...
<Button variant="danger" onClick={removeToken}>
LogOut
</Button>
Don't forget to tweak path to the module while importing based on your project structure.

How do I add an event listener to a React component?

I'm trying to build a React web app (v 16.13.0). I want a flash message component, to display status after a form is submitted. If there is already something standard, that would be preferable, but since I can't find anything, I'm trying to roll my own using this -- https://medium.com/#jaouad_45834/building-a-flash-message-component-with-react-js-6288da386d53 . Here's the component
import React, { useEffect, useState } from 'react';
import Bus from '../Utils/Bus';
import './index.css';
export const Flash = () => {
let [visibility, setVisibility] = useState(false);
let [message, setMessage] = useState('');
let [type, setType] = useState('');
useEffect(() => {
Bus.addListener('flash', ({message, type}) => {
setVisibility(true);
setMessage(message);
setType(type);
setTimeout(() => {
setVisibility(false);
}, 4000);
});
}, []);
useEffect(() => {
if(document.querySelector('.close') !== null) {
document.
querySelector('.close').
addEventListener('click', () => setVisibility(false));
}
})
return (
visibility && <div className={`alert alert-${type}`}>
<span className="close"><strong>X</strong></span>
<p>{message}</p>
</div>
)
}
Problem is, web site uses custom code, but doesn't show source for
Bus.addListener('flash', ({message, type}) => {
setVisibility(true);
setMessage(message);
setType(type);
setTimeout(() => {
setVisibility(false);
}, 4000);
});
so my question is, how do I add an event listener to a React component?
Edit: In response to the answer given, I created this file ...
localhost:client davea$ cat src/Utils/Bus.js
import EventEmitter from 'events';
export default new EventEmitter();
but re-compiling my module results in this error ...
./src/components/Flash/index.js
Module not found: Can't resolve '../Utils/Bus' in '/Users/davea/Documents/workspace/chicommons/maps/client/src/components/Flash'
These are the first lines of the file above. Note the second "import" where I'm importing "Bus" ...
import React, { useEffect, useState } from 'react';
import Bus from '../Utils/Bus';
import './index.css';
export const Flash = () => {
The website included the code: https://medium.com/#jaouad_45834/building-a-flash-message-component-with-react-js-6288da386d53
To set that up, we need to create a new folder in our root directory and name it Utils and create on it a Bus.js file with will contains the following code:
import EventEmitter from 'events';
export default new EventEmitter();
This is all Bus.js is, a simple event emitter.
You can also use react-toastify or useToasts for this.
In order to show the flash message, you need to do something like the following.
Bus.emit('flash', {type: 'danger', message: 'error occurred'});
I have used the code you have provided and mixed it with a dummy form. Upon submitting the form, the flash message appears successfully.
Live example & working code is here:
https://codesandbox.io/s/dazzling-lamarr-k3cn5
Some notes:
I have refactored and removed 2nd useEffect as it is inefficient and unnecessary. The onClick can very well be applied to the close-span-element
If you are using redux, you can use create global Flash/Alert message and connect it to the store. Any redux-connected-component can simply work its own logic and dispatch an alert action and render different types of messages.
Using ready made libraries are also cool.
I think what you want is widely known as a Toaster, and you can use a library like React Toastify [https://github.com/fkhadra/react-toastify] with a simple configuration and high customization

Resources