How to display User name in profile page - react / firebase - javascript

I have made a signup/login/logout page which works perfectly fine, however I wanted to add an additional field in the register page for user name, and I wanted the username to display in the profile page.
I was able to inset the username field into the register page, and I have a name section on the profile page which also shows up when the profile page loads, however, when I input a user name in the register page, it does not appear in the profile page.
Can anyone please help me figure this out? I really appreciate the help everyone. My first post here :) just recently started my developer journey
// register.js
import { useState } from "react";
import "./forms.css";
import { auth } from "./firebase";
import { useNavigate, Link } from "react-router-dom";
import {
createUserWithEmailAndPassword,
sendEmailVerification,
} from "firebase/auth";
import { useAuthValue } from "./AuthContext";
function Register() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [error, setError] = useState("");
const navigate = useNavigate();
const { setTimeActive } = useAuthValue();
const validatePassword = () => {
let isValid = true;
if (password !== "" && confirmPassword !== "") {
if (password !== confirmPassword) {
isValid = false;
setError("Passwords does not match");
}
}
return isValid;
};
const register = (e) => {
e.preventDefault();
setError("");
if (validatePassword()) {
// Create a new user with email and password using firebase
createUserWithEmailAndPassword(auth, email, password)
.then(() => {
sendEmailVerification(auth.currentUser)
.then(() => {
setTimeActive(true);
navigate("/verify-email");
})
.catch((err) => alert(err.message));
})
.catch((err) => setError(err.message));
}
setName("");
setEmail("");
setPassword("");
setConfirmPassword("");
};
return (
<div className="center">
<div className="auth">
<h1>Register Account</h1>
{error && <div className="auth__error">{error}</div>}
<form onSubmit={register} name="registration_form">
<input
type="name"
value={name}
placeholder="Enter your user name"
required
onChange={(e) => setName(e.target.value)}
/>
<input
type="email"
value={email}
placeholder="Enter your email"
required
onChange={(e) => setEmail(e.target.value)}
/>
<input
type="password"
value={password}
required
placeholder="Enter your password"
onChange={(e) => setPassword(e.target.value)}
/>
<input
type="password"
value={confirmPassword}
required
placeholder="Confirm password"
onChange={(e) => setConfirmPassword(e.target.value)}
/>
<button type="submit">Register</button>
</form>
<span>
Already have an account?
<Link to="/login">login</Link>
</span>
</div>
</div>
);
}
export default Register;
import "./profile.css";
import { useAuthValue } from "./AuthContext";
import { signOut } from "firebase/auth";
import { auth } from "./firebase";
function Profile() {
const { currentUser } = useAuthValue();
return (
<div className="center">
<div className="profile">
<h1>Profile</h1>
<p>
<strong>Name: </strong>
{currentUser?.name}
</p>
<p>
<strong>Email: </strong>
{currentUser?.email}
</p>
<p>
<strong>Email verified: </strong>
{`${currentUser?.emailVerified}`}
</p>
<span onClick={() => signOut(auth)}>Sign Out</span>
</div>
</div>
);
}
export default Profile;

Related

Compare the input field value with the database field value in reactjs in a login form

I want to compare the input field value with the database field value in reactjs in a login form and put an alert if the both values are correct or not like the alert('Username or Password does not match!') will pop if the password entered is wrong or the username.
login.js
import React, { useState } from 'react'
import { Button, Form } from 'semantic-ui-react'
import axios from 'axios'
import { useNavigate } from 'react-router'
export default function Login() {
let navigate = useNavigate()
const[username, setusername] = useState('');
const[Employee_password, setEmployee_password] = useState('');
const GetData = (e) =>{
e.preventDefault();
console.log(username, Employee_password)
if(username !== employee.username && Employee_password !== Employee_password)
{
alert('Username or Password does not match!')
return false
}
axios.post('http://localhost:5000/emp/login',{
username,
Employee_password
})
console.log('username', username)
.then((res)=>{
console.log('Login Successfull')
navigate('/read')
}).catch(err=>{
console.log(err)
})
}
return(
<div>
<Form onClick={GetData} className='create-form'>
<h2>Login into existing ID</h2>
<Form.Field>
<label>Enter Username</label>
<input type='text' placeholder='Username' onChange={(e) => setusername(e.target.value)}></input>
</Form.Field>
<Form.Field>
<label>Password</label>
<input type='password' placeholder='Password' onChange={(e) => setEmployee_password(e.target.value)}></input>
</Form.Field>
<Button type='submit'>Login</Button>
</Form>
</div>
)
}

I want to pass [details] object from the current component to another component using navigate in react

While using the navigate and passing email in it, I am getting email in another component for first time only. Second time it is becoming undefined.
Please help me here to How can I send data using navigate from one component to another component. Here, after clicking on login button, it should redirect to desired page and should pass the details object.
Also I want to pass all the data available in details object to another component.
*This is studentStatus.js and this will recieve data from Login.js *
import { useLocation } from "react-router";
const Studentstatus = () => {
const {state} = useLocation();
console.log(state.email);
// const {id, firstname, lastname, email,password} = state;
return (
<>
{/* <p id="email" className="email">Email Id: -{state.email} </p><br/> */}
<div className="studentDetails">
<p id="id" className="id">ID: -{state.id}</p><br/>
<p id="fname" className="fname">First Name: - {state.firstname}</p><br/>
<p id="lname" className="lname">Last Name: -{state.lastname}</p><br/>
<p id="email" className="email">Email Id: -{state.email} </p><br/>
<p id="password" className="password">password Id: -{state.password} </p><br/>
</div>
</>
)
}
export default Studentstatus;
import './Login.css'
import { FcGoogle } from "react-icons/fc"
import { FaGithub, FaFacebook } from "react-icons/fa"
import { Link, Navigate } from 'react-router-dom'
import React,{ useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useEffect } from 'react'
const Login = () =>{
const showConsole =()=>{
//onclick it will display on console
console.log("I am google, facebook, github");
}
const navigate = useNavigate();
const [email, setEmail] = React.useState("");
const [password, setPassword] = React.useState("");
const [details, setDetails] = React.useState({});
function login(){
let item = {password, email};
console.log(item);
fetch("http://localhost:8080/student/login",{
method:'POST',
body:JSON.stringify(item),
headers:{
"Content-Type":'application/json',
"Accept":'application/json'
}
}).then((e)=>{
if(e.status === 200){
console.log("Success",e)
window.alert("Student Logged in successfully");
fetch(`http://localhost:8080/student/oneStudentEmail?email=${email}`,{
method:'GET',
headers:{
"Content-Type":'application/json',
"Accept":'application/json'
}
}).then((student)=>student.json())
.then((result)=>{
// console.log(result);
setDetails(result);
})
navigate("/student-status", {state:{email:details.email}})
}else{
console.log("Not found",e,item)
window.alert("Not found",item);
}
})
console.log(details);
}
return (
<>
<div className='main_login'>
<div><button className="btn_google" onClick={showConsole}><FcGoogle /></button></div>
<div><button className="btn_github" onClick={showConsole}><FaGithub /></button></div>
<div><button className="btn_facebook" onClick={showConsole}><FaFacebook /></button></div>
<div className="col-sm-6 offset-sm-3">
<h3>Enter Details</h3>
{/* input boxes */}
<input type="text" className="form-control" placeholder="Email" value={email} onChange={(e)=>{setEmail(e.target.value)}} /><br/>
<input type="password" className="form-control" placeholder="Password" value={password} onChange={(e)=>setPassword(e.target.value)} /><br/>
<button className="btn btn-primary" onClick={login} > Login </button><br/>
Already have an Account?<Link to="/sign-up">Sign Up</Link><br/>
</div>
{/* display details at the bottom but I want to pass data to another component */}
<div>
Id : -{details.id}<br/>
Name : -{details.firstname} {details.lastname}<br/>
Email: -{details.email}<br/>
Password: -{details.password}<br/>
</div>
</div>
</>
)
}
export default Login;

where to call the Axios post request in reactjs

I have a form,thats data are saved in the state to be sent to the backend server.
i am handling the form with handleSubmit function and useEffect hook, where the handleSubmit prevents the form from being submitted unless it calls the validation function, in the useEffect I check if there are any errors using if condition and then console.log my data.
now I want to post the data hold in the state -the state is sent as a props to me- but I am confused whether to put the request in the HandleSubmit function or in the useEffect inside the body of the if condition.
import react, { Component, useState, useEffect } from 'react';
import {useNavigate } from 'react-router-dom';
import axios from 'axios';
import './sign.css';
const SignA = (props) => {
const navigate = useNavigate();
const [formErrors, setFormErrors] = useState({});
const [isSubmit, setIsSubmit] = useState(false);
const handleSubmit = (err) => {
err.preventDefault();
setFormErrors(validate(props.data));
setIsSubmit(true);
}
useEffect(() => {
console.log(Object.keys(formErrors).length);
if (Object.keys(formErrors).length === 0 && isSubmit) {
console.log('console the props data', props.data)
//here is where I think the post request should be put
if (isSubmit) {
return (navigate('/profileadmin'))
}
}
}, [formErrors])
const validate = (values) => {
const errors = {};
const regex = /^[^\s#]+#[^\s#]+\.[^\s#]{2,}$/i;
if (!values.firstname) {
errors.firstname = 'firstname is required!';
}
if (!values.lastname) {
errors.lastname = 'lastname is required!';
}
if (!values.mobile) {
errors.mobile = 'mobile is required!';
}
if (!values.email) {
errors.email = 'email is required!';
} else if (!regex.test(values.email)) {
errors.email = 'this is not a valid email format!'
}
return errors;
}
return (
<div className='signup'>
<form onSubmit={handleSubmit} >
<div className="container">
<h1>Sign Up</h1>
<div className="name">
<div>
<input
type="text"
placeholder="First name"
name="firstname"
id='firstName'
value={props.data.firstname}
onChange={props.change}
/>
</div>
<div>
<input
type="text"
placeholder="Last name"
name="lastname"
value={props.data.lastname}
onChange={props.change}
/>
</div>
</div>
<p className='errorMsg'>{formErrors.firstname}</p>
<p className='errorMsg'>{formErrors.lastname}</p>
<br />
<div>
<input
type="text"
placeholder="Business mobile number"
name="mobile"
value={props.data.mobile}
onChange={props.change}
/>
<p className='errorMsg'>{formErrors.mobile}</p>
<br />
<input
type="text"
placeholder="Email Adress"
name="email"
value={props.data.email}
onChange={props.change}
/>
<p className='errorMsg'>{formErrors.email}</p>
<br />
</div>
</div>
<br />
<div className="checkbox">
<label>
<input type="checkbox" className="check" />i’ve read and agree with <a href="url" >Terms of service</a>
</label>
</div>
<div className="clearfix">
<button type="submit" className="signupbtn">Sign Up</button>
</div>
</div>
</form >
</div >
)
}
export default SignA;
this is the request
axios.post('', props.data)
.then(res => console.log('post res', res))
.catch(error => {
console.error('There was an error in post request!', error);
});
You don't necessarily need useEffect here.
Here is how you can implement such thing:
Declare a state to hold form values:
const [formData, setFormData] = useState({})
Declare function to set the state:
const handleChange = (name, value) => {
setFormData({...formData, [name]: value})
}
Input onChange to capture:
// handleChange has two parameters
<input
type="text"
placeholder="First name"
name="firstname"
id='firstName'
value={props.data.firstname}
onChange={(event) => handleChange('firstName', event.target.value)}
/>
function for calling post axios post request
const handleSubmit = () => {
//check for validations code here
// if validations are right then post request here
// this will give you all the fields like firstName: "", lastName: ""
let requestBody = {
...formData
}
axios.post("url", requestBody).then((res)=> {
//your code here
})
}

Why is my boolean statement always evaluating to true?

I'm pretty new to javascript, and I am trying to figure out how to calculate sales tax based off of US states. In my code, I attempted to use an if else statement based off of the input value of state to accomplish this. However, no matter what I put in for the value of state the tax is determined based off of 8.75%, and I'm not sure what I am doing wrong. I would really appreciate any help or advice on how to fix this problem.
Thank you
PlaceOrderScreen.js
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link } from 'react-router-dom';
import { createOrder } from '../actions/orderActions';
import CheckoutSteps from '../components/CheckoutSteps';
import { ORDER_CREATE_RESET } from '../constants/orderConstants';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';
export default function PlaceOrderScreen(props) {
const cart = useSelector((state) => state.cart);
if (!cart.paymentMethod) {
props.history.push('/payment');
}
const orderCreate = useSelector((state) => state.orderCreate);
const { loading, success, error, order } = orderCreate;
const toPrice = (num) => Number(num.toFixed(2)); // 5.123 => "5.12" => 5.12
cart.itemsPrice = toPrice(
cart.cartItems.reduce((a, c) => a + c.qty * c.price, 0)
);
//Sales Tax//
{
if (cart.shippingAddress.state === 'New York'||'NY'){
cart.taxPrice = toPrice(0.0875 * cart.itemsPrice)}
else if (cart.shippingAddress.state === 'Kansas'||'KS') {
cart.taxPrice = toPrice(0.065 * cart.itemsPrice)}
else {
cart.taxPrice = toPrice(0 * cart.itemsPrice)}
};
cart.totalPrice = cart.itemsPrice + cart.shippingPrice + cart.taxPrice;
const dispatch = useDispatch();
const placeOrderHandler = () => {
dispatch(createOrder({ ...cart, orderItems: cart.cartItems }));
};
useEffect(() => {
if (success) {
props.history.push(`/order/${order._id}`);
dispatch({ type: ORDER_CREATE_RESET });
}
}, [dispatch, order, props.history, success]);
return (
<div>
<CheckoutSteps step1 step2 step3 step4></CheckoutSteps>
<div className="row top">
<div className="col-2">
<ul>
<li>
<div className="card card-body">
<h2>Shipping</h2>
<p>
<strong>Name:</strong> {cart.shippingAddress.fullName} <br />
<strong>Address: </strong> {cart.shippingAddress.address},
{cart.shippingAddress.city}, {cart.shippingAddress.state}, {cart.shippingAddress.postalCode}
,{cart.shippingAddress.country}
</p>
</div>
</li>
</ul>
</div>
</div>
</div>
ShippingAddressScreen.js
import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { saveShippingAddress } from '../actions/cartActions';
import CheckoutSteps from '../components/CheckoutSteps';
export default function ShippingAddressScreen(props) {
const userSignin = useSelector((state) => state.userSignin);
const { userInfo } = userSignin;
const cart = useSelector((state) => state.cart);
const { shippingAddress } = cart;
if (!userInfo) {
props.history.push('/signin');
}
const [fullName, setFullName] = useState(shippingAddress.fullName);
const [address, setAddress] = useState(shippingAddress.address);
const [city, setCity] = useState(shippingAddress.city);
const [state, setState] = useState(shippingAddress.state);
const [postalCode, setPostalCode] = useState(shippingAddress.postalCode);
const [country, setCountry] = useState(shippingAddress.country);
const dispatch = useDispatch();
const submitHandler = (e) => {
e.preventDefault();
dispatch(
saveShippingAddress({ fullName, address, city, state, postalCode, country })
);
props.history.push('/payment');
};
return (
<div>
<CheckoutSteps step1 step2></CheckoutSteps>
<form className="form" onSubmit={submitHandler}>
<div>
<h1>Shipping Address</h1>
</div>
<div>
<label htmlFor="fullName">Full Name</label>
<input
type="text"
id="fullName"
placeholder="Enter full name"
value={fullName}
onChange={(e) => setFullName(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="address">Address</label>
<input
type="text"
id="address"
placeholder="Enter address"
value={address}
onChange={(e) => setAddress(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="city">City</label>
<input
type="text"
id="city"
placeholder="Enter city"
value={city}
onChange={(e) => setCity(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="state">State</label>
<input
type="text"
id="state"
placeholder="Enter state"
value={state}
onChange={(e) => setState(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="postalCode">Postal Code</label>
<input
type="text"
id="postalCode"
placeholder="Enter postal code"
value={postalCode}
onChange={(e) => setPostalCode(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="country">Country</label>
<input
type="text"
id="country"
placeholder="Enter country"
value={country}
onChange={(e) => setCountry(e.target.value)}
required
></input>
</div>
<div>
<label />
<button className="primary" type="submit">
Continue
</button>
</div>
</form>
</div>
);
}
Your code should look like this:
cart.shippingAddress.state === 'New York'|| cart.shippingAddress.state === 'NY'
Your current code is testing if the string "NY" is true or not, and that evaluates to true in your boolean test, so you're always getting the 8.75% tax rate.

How to give props from one page to another with react Router

I have a problem: I have two pages, one named /login and the other one is called /app.
My problem is that I don't know how to pass props from /login to /app. In /app I want to show the person who logged in a welcome message with his name like: "Welcome Kazim". Hope you guys can help me. There is no problem to link from /login to /app but the props won't get passed.
import React, { useState } from "react";
import { Link, useHistory } from 'react-router-dom';
import axios from 'axios';
import "./SignIn.css";
import Logo from '../../images/logo.PNG';
function SignIn() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [validationWrong, setValidationWrong] = useState(true);
//eslint-disable-next-line
const [validationNoExist, setValidationNoExist] = useState(true);
const history = useHistory();
const test2 = {
pathname: '/app',
state: { email: 'irgendwas#web.de',
name: "horst" }
};
/* Wird an das Backend geschickt und wir erhalten eine Antwort */
const handleLogin = () => {
axios.post('https://localhost.../', {"email":email, "password":password})
.then(res => {
console.log(res);
console.log(res.data);
console.log(res.status);
if(res.status === 200) {
console.log("Willkommen")
setValidationWrong(true);
setValidationNoExist(true);
history.push(test2)
}
else if(res.status === 203) {
setValidationWrong(false);
}
else if(res.status === 204) {
setValidationNoExist(false);
}
})
.catch(error => {
console.log(error)
setValidationNoExist(false);
})
};
//const handleLogin2 = useCallback(() => {history.push('/sample')}, [history]);
return (
<div className="SignIn">
<div className="container" id="container">
<div className="form-container sign-in-container">
<form>
<div className="Logo"><img src={Logo} alt="Logo" /></div>
<h2>Entdecke neue Freunde</h2>
<input type="email" className={(validationWrong && validationNoExist) ? 'input-form' : 'input-form-validation-wrong'} onChange={event => setEmail(event.target.value)} placeholder="E-Mail" />
<input type="password" id="password" className={(validationWrong && validationNoExist) ? 'input-form' : 'input-form-validation-wrong'} onChange={event => setPassword(event.target.value)} placeholder="Passwort" />
{validationWrong === false &&
<p className='validation-wrong'>E-Mail oder Passwort ist falsch</p>
}
{validationNoExist === false &&
<p className='validation-wrong'>Diese E-Mail existiert nicht</p>
}
<div className='optional-buttons'>
<input id="input-remain" type="checkbox" className="input-remain" /><label for="input-remain">Angemeldet bleiben</label>
<a className="password-forgot" href="/">Passwort vergessen?</a>
</div>
<div className='buttons-container'>
<Link>
<button className="button-login" type="button" onClick={handleLogin}>Anmelden</button>
</Link>
<Link to="/registrieren" >
<button className="button-registration" type="button">Registrieren</button>
</Link>
</div>
</form>
</div>
<div className="overlay-container">
<div className="overlay">
<div className="overlay-panel overlay-right">
</div>
</div>
</div>
</div>
</div>
);
}
export default SignIn;
Here is the Chat.js
import React from "react";
import '../components/testchat/Testchat'
import Testchat from "../components/testchat/Testchat";
function Chat(props) {
return (
<div>
<h1>Willkommen {props.name}</h1>
<Testchat></Testchat>
</div>
);
}
Given route push with state:
history.push({
pathname: '/app',
state: {
email: 'irgendwas#web.de',
name: "horst",
},
})
You can access the route state on the location object on the receiving route. You can access the location object via the useLocation React hook.
function Chat(props) {
const { state } = useLocation();
const { name } = state;
return (
<div>
<h1>Willkommen {name}</h1>
<Testchat></Testchat>
</div>
);
}

Categories

Resources