Objects are not valid as a React child (found: object with keys {}) - javascript

I am having trouble on posting the error from data after submit incorrect mail and password. With debugger i'm seeing error text, but the page has error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.
import { signInWithEmailAndPassword } from 'firebase/auth';
import React, {useState} from 'react';
import auth from '../../Firebase/firebase';
const SignIn = (errorCode) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [errorText, setErrorText] = useState(false);
const signIn = (e) => {
e.preventDefault();
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
console.log(userCredential);
})
.catch((error) => {
let errorCode = error.code;
let errorMessage = error.message;
debugger;
console.log(errorCode)
return (
setErrorText(true))
})
}
return (
<div>
<form onSubmit={signIn}>
<h1>Hey, Log In</h1>
<input type='email' placeholder='enter email' value={email} onChange={(e) => setEmail(e.target.value)}></input>
<input type='password' placeholder='enter pass' value={password} onChange={(e) => setPassword(e.target.value)}></input>
{ errorText ? <div>{errorCode}</div> : null
}
<button type='submit'>Push to login</button>
</form>
</div>
)
}
export default SignIn
I expected to image errorCode at the page signIn. Please, help me.

Hey you can declare the error code in global scope using useState like below and can follow below thread for looking into this kind of errors https://stackabuse.com/bytes/fix-objects-are-not-valid-as-a-react-child-error-in-react/
import React, { useState } from "react";
const SignIn = () => {
const [errorCode, setErrorCode] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [errorText, setErrorText] = useState(false);
const signIn = (e) => {
e.preventDefault();
setErrorCode('400')
console.log(errorCode);
setErrorText(true);
};
return (
<div>
<form onSubmit={signIn}>
<h1>Hey, Log In</h1>
<input
placeholder="enter email"
value={email}
onChange={(e) => setEmail(e.target.value)}
></input>
<input
type="password"
placeholder="enter pass"
value={password}
onChange={(e) => setPassword(e.target.value)}
></input>
{errorText ? <div>Error code {errorCode}</div> : null}
<button type="submit">Push to login</button>
</form>
</div>
);
};
export default SignIn;

Related

Uncaught TypeError: setName is not a function

this is my code i have defined function but it is still showing me error like this for setname setemail password
import React, {useState} from 'react'
import './Auth.css'
import icon from '../../assets/logo.svg'
import AboutAuth from './AboutAuth'
const Auth = () => {
const [isSignup, setIsSignup] = useState(false)
const {name, setName} = useState('')
const {email, setEmail} = useState('')
const {password, setPassword} = useState('')
const handleSwitch = () => {
setIsSignup(!isSignup)
}
const handleSubmit = (e) => {
e.preventDefault()
console.log({ name, email, password})
}
return (
<div>
<section className='auth-section'>
{
isSignup && <AboutAuth />
}
<div className='auth-container'>
{ !isSignup && <img src={icon} width='50px' alt='stack overflow' className='login-logo' /> }
<form onSubmit={handleSubmit}>
{
isSignup && (
<label htmlFor='name'>
<h4>Display Name</h4>
<input type="text" id='name' name='name' onChange={(e) => {setName(e.target.value)}} />
</label>
)
}
<label htmlFor="email">
<h4> Email </h4>
<input type="email" name='email' id='email' onChange={(e) => {setEmail(e.target.value)}} />
</label>
<input type="password" name='password' id='password' onChange={(e) => {setPassword(e.target.value)}}/>
export default Auth
Auth.jsx:36 Uncaught TypeError: setName is not a function And setEmail is not a function And setPassword is not a functionm Help Me To Solve That Issue
The problem lies in destructuring useState hook. React.useState hook returns an array of [state, setState]
Solution:
const [name, setName] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')

xhr.js:220 POST http://localhost:3000/EShop/register 400 (Bad Request)

Trying to POST request to send data to database but it always shows 400 bad request.
The AuthReducer file is as follow. Data is not getting posted when done in Frontend but its properly working when tested in postman api.
export const Register = (username, email , password) => async(disptach) => {
try{
disptach({type:REGISTER_USER_REQUEST})
const config = {
Headers:{
'Content-Type':'application/json'
}
}
const { data } = await axios.post('/EShop/register', {username ,email , password} , config)
disptach({
type:REGISTER_USER_SUCCESS,
payload:data.user
})
}catch(error){
disptach({
type:REGISTER_USER_FAIL,
payload : error.response.data.message
})
}
}
The register form is as follow..
import React, { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom"
import { useSelector, useDispatch } from "react-redux"
import Loader from "./loader";
import { Register } from "../actions/UserAction";
import "../css-files/Account.css"
export default function register() {
const [email, setemail] = useState('');
const [password, setpassword] = useState('');
const [username, setusername] = useState('');
const disptach = useDispatch();
const navigate = useNavigate();
const { isAuthenticated, error, loading } = useSelector(state => state.user)
useEffect(() => {
if (isAuthenticated) {
navigate('/account/login')
}
}, [disptach, isAuthenticated])
const SubmitRegisterHandler = (e) => {
e.preventDefault()
disptach(Register(username, email, password))
}
return (
<div id="Account_container">
{loading ?
<Loader />
:
<div id="wrapper">
<div id="Wrap_First">
<img src="https://res.cloudinary.com/dqxozrie1/image/upload/v1659935744/eshop/online-registration-sign-up_gfb2gs.webp" />
</div>
<div id="Wrap_Second">
<div id="login">
<h2>Create New Account</h2>
<form onSubmit={SubmitRegisterHandler}>
<input
required
type="text"
placeholder="Username"
value={username}
onChange={(e) => { setusername(e.target.value) }}
/>
<input
required
type="email"
placeholder="Email"
value={email}
onChange={(e) => { setemail(e.target.value) }}
/>
<input
required
type="password"
placeholder="Password"
value={password}
onChange={(e) => { setpassword(e.target.value) }}
/>
<button>Register</button>
</form>
<p id="existing_acc"><Link to="/account/login">Already have an account !</Link></p>
</div>
</div>
</div>
}
</div>
);
}
It gives 400 bad request always. Please help me how to resolve this issue.

How to display auth errors with p tag

how to display to user an auth error differently than with alert?
For example: User will type a bad password, and a p tag will tell him, that he typed uncorrect password.
Using Firebase v9 and React.
Some code:
import React from 'react'
import { Link, useNavigate } from "react-router-dom";
import { UserAuth } from '../context/AuthContext';
import { useState } from 'react';
const Signin = () => {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('');
const navigate = useNavigate();
const { signIn } = UserAuth();
const handleSubmit = async (e) => {
e.preventDefault();
setError('')
try{
await signIn(email, password)
navigate("/");
} catch (e) {
setError(e.message)
alert(e.message)
}
}
return (
<div className='Signin'>Signin
<form onSubmit={handleSubmit}>
<label>Email</label>
<input onChange={(e) => setEmail(e.target.value)} type="email"/>
<label>password</label>
<input onChange={(e) => setPassword(e.target.value)} type="password"/>
<button type="submit">Sign up</button>
<p className='errorp'></p>
</form>
</div>
)
}
export default Signin
Thank you!
Something like {error && <p className='errorp'>{error}</p>}

React history.push to localhost:3000 not redirecting

I am creating a login page using React. history.push("/") isn't directing and this error in console: Uncaught TypeError: Cannot read properties of undefined (reading 'push').
Did this from tutorial and followed the codes exactly, but still can't figure out for days.
import { useState } from "react";
import styles from "./register.css";
import Login from "../../containers/login/index";
function Register({ props, history }) {
const [name, setName] = useState();
const [email, setEmail] = useState();
const [password, setPassword] = useState();
function registerClicked() {
if (name !== " " && email !== " " && password !== " ") {
console.log(name, email, password);
alert("Thanks for registering");
history.push("/");
} else {
alert("Please register to continue");
}
}
return(
<div className="regContainer">
<p className="registerTitle">Register to sign in</p>
<input type="text"
placeholder="Create username"
onChange={(nameText) => setName(nameText.target.value)} />
<input type="text"
placeholder="Email address"
onChange={(emailText) => setEmail(emailText.target.value)} />
<input type="password"
placeholder="Password"
onChange={(passwordText) => setPassword(passwordText.target.value)} />
<button onClick={() => registerClicked()}>Register</button>
<p className="loginInstead">Already have an account? Sign in instead</p>
</div>
);
}
export default Register;
import { useNavigate } from "react-router-dom"
export default const Register = () => {
const navigate = useNavigate();
if(...){
navigate('/')
}
return <div></div>
}

Local storage token Problems

So this problem I am facing for quite some time. Basically Registering user work to some extent. This is what is happening, upon the user being created and me getting the Auth token displayed in the dev-tools/Application and me being pushed to the home as I should.
When I refresh the page I get this error × Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://reactjs.org/link/crossorigin-error for more information. I can fix this by clearing the localStorage. So if every time a new user is created, and if it wants to refresh the page, I will have to clear local storage every time. Which is totally not convenient.
There is another error, The logout handler is bugging, when I press the logout button it is displaying this error TypeError: Cannot read property 'push' of undefined and it pointing out the error is located in the UserContext. I would really appreciate some help really.
User Context
import React from "react";
import { useHistory } from "react-router-dom"
const UserContext = React.createContext();
function getUserFromLocalStorage() {
return localStorage.getItem("authToken")
? JSON.parse(localStorage.getItem("authToken"))
: { username: null, token: null };
}
function UserProvider({ children }) {
const [user, setUser] = React.useState(getUserFromLocalStorage());
const routerHistory = useHistory()
const logoutHandler = () =>{
localStorage.removeItem("authToken");
setUser(user);
routerHistory.push("/")
}
return (
<UserContext.Provider
value={{ user, setUser, logoutHandler }}
>
{children}
</UserContext.Provider>
);
}
export { UserContext, UserProvider };
Login
import React, { useState, } from "react";
import { useHistory } from "react-router-dom"
import axios from "axios";
import { Link } from "react-router-dom";
import "./Signin.css";
import { UserContext } from "../../context/user";
const Login = () => {
const { user, setUser } = React.useContext(UserContext);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const history = useHistory()
const loginHandler = async (e) => {
e.preventDefault();
const config = {
header: {
"Content-Type": "application/json",
},
};
try {
const { data } = await axios.post(
"http://localhost:5000/api/auth/login",
{ email, password },
config
);
user.authToken = data.token;
setUser(user)
history.push("/");
} catch (error) {
if (error.response) {
setError(error.response.data.error);
}
setTimeout(() => {
setError("");
}, 5000);
}
};
return (
<div className="signin">
<Link to='/'>
<img src='/audible/logo.png' />
</Link>
<form onSubmit={loginHandler} className="form__container">
<h3>Sign in with your Amazon account</h3>
{error && <span className="error__message">{error}</span>}
<span className='labels'>Email </span>
<input
className="input__field"
type="email"
required
id="email"
onChange={(e) => setEmail(e.target.value)}
value={email}
tabIndex={1}
/>
<span className='signin__forgot'>Password{" "}
<Link className='links' to="/forgotpassword" >
Forgot Password?
</Link>
</span>
<input
className="input__field"
type="password"
required
id="password"
autoComplete="true"
onChange={(e) => setPassword(e.target.value)}
value={password}
tabIndex={2}
/>
<button type="submit" className="signin__btn">
Sign In
</button>
<span className='new__sign'>New to Amazon? </span>
<Link to="/register">
<button className='signin__register'>
Create your amazon account
</button>
</Link>
</form>
</div>
);
};
export default Login;
Register
import { useState, } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import { useHistory } from "react-router-dom"
const Register = () => {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmpassword, setConfirmPassword] = useState("");
const [error, setError] = useState("");
const routerHistory = useHistory()
const registerHandler = async (e) => {
e.preventDefault();
const config = {
header: {
"Content-Type": "application/json",
},
};
if (password !== confirmpassword) {
setPassword("");
setConfirmPassword("");
setTimeout(() => {
setError("");
}, 5000);
return setError("Passwords do not match");
}
try {
const { data } = await axios.post(
"http://localhost:5000/api/auth/register",
{
username,
email,
password,
},
config
);
localStorage.setItem("authToken", data.token);
routerHistory.push('/login')
} catch (error) {
if (error.response) {
setError(error.response.data.error);
}
setTimeout(() => {
setError("");
}, 5000);
}
};
return (
<div className="signin">
<Link to='/'>
<img src='/audible/logo.png' />
</Link>
<form onSubmit={registerHandler} className="form__container">
<h3>Create account</h3>
{error && <span className="error__message">{error}</span>}
<span className='labels'>Username</span>
<input
type="text"
className="input__field"
required
id="name"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<span className='labels'>Email</span>
<input
type="email"
className="input__field"
required
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<span className='labels'>Password</span>
<input
type="password"
required
id="password"
className="input__field"
autoComplete="true"
placeholder="At least 6 characters"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<span className='labels'>Re-enter password</span>
<input
type="password"
required
id="confirmpassword"
className="input__field"
autoComplete="true"
value={confirmpassword}
onChange={(e) => setConfirmPassword(e.target.value)}
/>
<button type="submit" className="register__btn">
Create your Amazon account
</button>
<span >
Already have an account? <Link className='links' to="/login">Login</Link>
</span>
</form>
</div>
);
};
export default Register;
Login Link
import React from "react";
import { Link, useHistory } from "react-router-dom";
import { CartContext } from "../../context/cart";
import { UserContext } from "../../context/user";
export default function LoginLink() {
const { user, logoutHandler } = React.useContext(UserContext);
const { clearCart } = React.useContext(CartContext);
if (user.authToken) {
return (
<button
onClick={() => {
logoutHandler();
clearCart()
}}
className="login-btn"
>
logout
</button>
);
}
return <Link to="/login">Signin</Link>;
}

Categories