React props.auth.user is undifined when registering a user - reactjs

In my project when I try to print the name of the user that just registered it shows undifined.
When I register a user he is redirected to the dashboard page where is name should apear but it doesn´t. But when I reload the page the name shows correctly.
The login is done similiar to register but works fine.
My component to register bidder.
import React, { Component } from "react";
import { Link, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { registerBidder } from "../../actions/auth";
import { createMessage } from "../../actions/messages";
export class RegisterBidder extends Component {
state = {
email: "",
password: "",
password2: "",
first_name: "",
last_name: "",
aluno: "false"
};
static propTypes = {
registerBidder: PropTypes.func.isRequired,
isAuthenticated: PropTypes.bool
};
onSubmit = e => {
e.preventDefault();
const {
email,
password,
password2,
first_name,
last_name,
aluno
} = this.state;
if (password != password2) {
this.props.createMessage({
passwordNotMatch: "Passwords não são iguais"
});
} else {
const newUser = {
email,
first_name,
last_name,
password,
aluno
};
this.props.registerBidder(newUser);
}
};
handleChange = () => {
if (this.state.aluno == "false") {
this.setState({ aluno: "true" });
} else {
this.setState({ aluno: "false" });
}
};
onChange = e => this.setState({ [e.target.name]: e.target.value });
render() {
if (this.props.isAuthenticated && this.registerBidder) {
return <Redirect to="/dashboardBidder" />;
}
const { email, password, password2, first_name, last_name } = this.state;
return (
<div className="col-md-6 m-auto">
<div className="card card-body mt-5">
<h2 className="text-center">Register</h2>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Email</label>
<input
type="email"
className="form-control"
name="email"
onChange={this.onChange}
value={email}
/>
</div>
<div className="form-group">
<label>First Name</label>
<input
type="name"
className="form-control"
name="first_name"
onChange={this.onChange}
value={first_name}
/>
</div>
<div className="form-group">
<label>Last Name</label>
<input
type="name"
className="form-control"
name="last_name"
onChange={this.onChange}
value={last_name}
/>
</div>
<div className="form-group">
<label>Password</label>
<input
type="password"
className="form-control"
name="password"
onChange={this.onChange}
value={password}
/>
</div>
<div className="form-group">
<label>Confirm Password</label>
<input
type="password"
className="form-control"
name="password2"
onChange={this.onChange}
value={password2}
/>
</div>
<div className="react__checkbox">
<label>Aluno</label>
<input
type="checkbox"
className="react__checkbox--input"
aluno={this.state.aluno}
onChange={this.handleChange}
/>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">
Register
</button>
</div>
<p>
Already have an account? <Link to="/login">Login</Link>
</p>
</form>
</div>
</div>
);
}
}
const mapStateToProps = state => ({
isAuthenticated: state.auth.isAuthenticated
});
export default connect(mapStateToProps, { registerBidder, createMessage })(RegisterBidder);
My action to register.
export const registerBidder = ({
email,
first_name,
last_name,
password,
aluno
}) => dispatch => {
// Headers
const config = {
headers: {
"Content-Type": "application/json"
}
};
// Request Body
const body = JSON.stringify({
user: { email, first_name, last_name, password },
aluno: aluno
});
console.log(body);
dispatch({ type: USER_LOADING });
axios
.post("/api/auth/registar/bidder", body, config)
.then(res => {
dispatch({
type: REGISTER_SUCCESS,
payload: res.data
});
})
.catch(err => {
dispatch(returnErrors(err.response.data, err.response.status));
dispatch({
type: REGISTER_FAIL
});
});
};

Related

How can i use try/catch to solve Axios error in my code using React Js

How can I solve the Axios Error in my code using the try/catch method . Am building a chat application with react js and stream API, when I try to signup using my signup form I get the Axios error which I don't know how I can debug it. You can help me out by editing my attached code so that i can continue with my project. Thanks in advance.
// below is my code//
import React, { useState } from 'react';
import Cookies from 'universal-cookie';
import axios from 'axios';
import signinImage from '../assets/signup.jpg';
const cookies = new Cookies();
const initialState = {
fullName: '',
username: '',
password: '',
confirmPassword: '',
phoneNumber: '',
avatarURL: '',
}
const Auth = () => {
const [form, setForm] = useState(initialState);
const [isSignup, setIsSignup] = useState(true);
const handleChange = (e) => {
setForm({ ...form, [e.target.name]: e.target.value });
}
const handleSubmit = async (e) => {
e.preventDefault();
const { username, password, phoneNumber, avatarURL } = form;
const URL = 'https://localhost:5000/auth';
// const URL = 'https://medical-pager.herokuapp.com/auth';
const { data: { token, userId, hashedPassword, fullName } } = await axios.post(`${URL}/${isSignup ? 'signup' : 'login'}`, {
username, password, fullName: form.fullName, phoneNumber, avatarURL,
});
cookies.set('token', token);
cookies.set('username', username);
cookies.set('fullName', fullName);
cookies.set('userId', userId);
if(isSignup) {
cookies.set('phoneNumber', phoneNumber);
cookies.set('avatarURL', avatarURL);
cookies.set('hashedPassword', hashedPassword);
}
window.location.reload();
}
const switchMode = () => {
setIsSignup((prevIsSignup) => !prevIsSignup);
}
return (
<div className="auth__form-container">
<div className="auth__form-container_fields">
<div className="auth__form-container_fields-content">
<p>{isSignup ? 'Sign Up' : 'Sign In'}</p>
<form onSubmit={handleSubmit}>
{isSignup && (
<div className="auth__form-container_fields-content_input">
<label htmlFor="fullName">Full Name</label>
<input
name="fullName"
type="text"
placeholder="Full Name"
onChange={handleChange}
required
/>
</div>
)}
<div className="auth__form-container_fields-content_input">
<label htmlFor="username">Username</label>
<input
name="username"
type="text"
placeholder="Username"
onChange={handleChange}
required
/>
</div>
{isSignup && (
<div className="auth__form-container_fields-content_input">
<label htmlFor="phoneNumber">Phone Number</label>
<input
name="phoneNumber"
type="text"
placeholder="Phone Number"
onChange={handleChange}
required
/>
</div>
)}
{isSignup && (
<div className="auth__form-container_fields-content_input">
<label htmlFor="avatarURL">Avatar URL</label>
<input
name="avatarURL"
type="text"
placeholder="Avatar URL"
onChange={handleChange}
required
/>
</div>
)}
<div className="auth__form-container_fields-content_input">
<label htmlFor="password">Password</label>
<input
name="password"
type="password"
placeholder="Password"
onChange={handleChange}
required
/>
</div>
{isSignup && (
<div className="auth__form-container_fields-content_input">
<label htmlFor="confirmPassword">Confirm Password</label>
<input
name="confirmPassword"
type="password"
placeholder="Confirm Password"
onChange={handleChange}
required
/>
</div>
)}
<div className="auth__form-container_fields-content_button">
<button>{isSignup ? "Sign Up" : "Sign In"}</button>
</div>
</form>
<div className="auth__form-container_fields-account">
<p>
{isSignup
? "Already have an account?"
: "Don't have an account?"
}
<span onClick={switchMode}>
{isSignup ? 'Sign In' : 'Sign Up'}
</span>
</p>
</div>
</div>
</div>
<div className="auth__form-container_image">
<img src={signinImage} alt="sign in" />
</div>
</div>
)
}
export default Auth
const handleSubmit = async (e) => {
e.preventDefault();
try {
const { username, password, phoneNumber, avatarURL } = form;
const URL = 'https://localhost:5000/auth';
// const URL = 'https://medical-pager.herokuapp.com/auth';
const { data: { token, userId, hashedPassword, fullName } } = await axios.post(`${URL}/${isSignup ? 'signup' : 'login'}`, {
username, password, fullName: form.fullName, phoneNumber, avatarURL,
});
cookies.set('token', token);
cookies.set('username', username);
cookies.set('fullName', fullName);
cookies.set('userId', userId);
if(isSignup) {
cookies.set('phoneNumber', phoneNumber);
cookies.set('avatarURL', avatarURL);
cookies.set('hashedPassword', hashedPassword);
}
window.location.reload();
} catch(error) {
console.log(error.response);
}
}

Why my page is not redirecting to login page after successful registration in React?

Here, props.history.push("/login"); is not working
Other all things are Working
Can anyone Help?
import React, { useState } from 'react'
import { Link } from "react-router-dom";
import axios from "axios";
const Register = (props) => {
const [data, setData] = useState({
name: "",
email: "",
password: ""
})
const { name, email, password } = data;
const handleChange = (e) => {
setData({ ...data, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
await axios.post(
"/auth/register", { name, email, password }, {
headers: {
"Content-Type": "application/json",
},
}
);
props.history.push("/login");
} catch (err) {
console.log(err);
}
};
return (
<form>
<h3>Create an account</h3>
<div className="mb-3">
<label>Name</label>
<input
type="text"
className="form-control"
placeholder="First name"
name="name"
value={name}
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Email</label>
<input
type="email"
className="form-control"
placeholder="Enter email"
name="email"
value={email}
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Password</label>
<input
type="password"
className="form-control"
placeholder="Enter Password"
name="password"
value={password}
onChange={handleChange}
/>
</div>
<div className="d-grid">
<button type="submit" className="btn btn-primary" onClick={handleSubmit}>
Register
</button>
</div>
<p className="forgot-password text-right">
Already registered? <Link to="/login">Login</Link>
</p>
</form>
);
}
export default Register
You have to try using this
import { useHistory } from "react-router-dom";
In function components
let history = useHistory();
After successfully register
history.push("/login");
Now it works
import React, { useState } from 'react'
import { Link } from "react-router-dom";
import axios from "axios";
import { useNavigate } from 'react-router-dom';
const Register = (props) => {
const [data, setData] = useState({
name: "",
email: "",
password: ""
})
const { name, email, password } = data;
const handleChange = (e) => {
setData({ ...data, [e.target.name]: e.target.value });
};
let navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
try {
await axios.post(
"/auth/register", { name, email, password }, {
headers: {
"Content-Type": "application/json",
},
}
);
navigate("/login");
} catch (err) {
console.log(err);
}
};
return (
<form>
<h3>Create an account</h3>
<div className="mb-3">
<label>Name</label>
<input
type="text"
className="form-control"
placeholder="First name"
name="name"
value={name}
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Email</label>
<input
type="email"
className="form-control"
placeholder="Enter email"
name="email"
value={email}
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Password</label>
<input
type="password"
className="form-control"
placeholder="Enter Password"
name="password"
value={password}
onChange={handleChange}
/>
</div>
<div className="d-grid">
<button type="submit" className="btn btn-primary" onClick={handleSubmit}>
Register
</button>
</div>
<p className="forgot-password text-right">
Already registered? <Link to="/login">Login</Link>
</p>
</form>
);
}
export default Register

i want to show details on same page

i am developing an application i.e supply chain management application on reactJS, NodeJS and blockchain.
Frontend code:
import React, { Component } from 'react'
import { useState, useEffect } from "react";
import axios from "axios";
import { useNavigate } from 'react-router-dom';
const SignUp = () => {
const navigate = useNavigate();
const flag=0;
const [data, setData] = useState({
uname: "",
email: "",
location: "",
budget: "",
password: ""
});
const handleChange = (e) => {
const value = e.target.value;
setData({
...data,
[e.target.name]: value
});
};
const handleSubmit = (e) => {
e.preventDefault();
const userData = {
uname: data.uname,
email: data.email,
location: data.location,
budget: data.budget,
password: data.password
};
axios
.post("http://localhost:8080/api/signup/", userData)
.then((response) => {
console.log(response);
})
.catch((error) => {
if (error.response) {
console.log(error.response);
console.log("server responded");
} else if (error.request) {
console.log("network error");
} else {
console.log(error);
}
});
navigate(`/home`)
};
return (
<form>
<h3>Sign Up</h3>
<div className="mb-3">
<label>User Name</label>
<input
type="text"
name="uname"
value={data.uname}
className="form-control"
placeholder="User name"
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Email address</label>
<input
type="email"
name="email"
value={data.email}
className="form-control"
placeholder="Enter email"
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Location</label>
<input
type="text"
name="location"
value={data.location}
className="form-control"
placeholder="Location"
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Budget</label>
<input
type="Number"
name="budget"
value={data.budget}
className="form-control"
placeholder="Budget"
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Password</label>
<input
type="password"
name="password"
value={data.password}
className="form-control"
placeholder="Enter password"
onChange={handleChange}
/>
</div>
<div className="d-grid">
<button type="submit" onClick={handleSubmit}className="btn btn-primary">
Sign Up
</button>
</div>
<p className="forgot-password text-right">
Already registered sign in?
</p>
</form>
);
};
export default SignUp;
here if user successfully registered then i want to show deatils of the user on the same page. how should i do that?
i have attached the code and the screenshot of the page.
currently i am on my account page.
Inside of your handle submit
You can just navigate after the axios.then callback
Or if you want the behavior to be that user submits -> register success -> show success -> then redirect, you can setTimeout for say 1000ms and then navigate.
axios
.post("http://localhost:8080/api/signup/", userData)
.then((response) => {
console.log(response);
})
.then(() => {
setTimeout(() => navigate(`/home`), 1000);
}
.catch((error) => {
if (error.response) {
console.log(error.response);
console.log("server responded");
} else if (error.request) {
console.log("network error");
} else {
console.log(error);
}
});
If you mean, show the user data after a successful registration and assuming you're calling an api to register the user and you're getting the user details back on success, you can handle that in your handleSubmit method.
Here's an example
const showUserDetails = (userDetails) => {
// Code that shows user details
// Probably using state
};
const handleSubmit = (e) => {
e.preventDefault();
const userData = {
...
axios
.post("http://localhost:8080/api/signup/", userData)
.then((response) => {
// handle here
showUserDetails(response);
})
.catch((error) => {
if (error.response) {
...
} else {
console.log(error);
}
});
};

How to Edit a form in React by using functional components

I am working on a React project, In my project I have a form, In that form I fetch data by Id
From the backend, Now I am trying to do put method. But I have no idea how doing it so please me
How to send edited data to backend using the put method.
This is my code Editstudentdetails.js
import React, { useState, useEffect } from 'react';
import './Editstudentdetails.css';
import axios from 'axios';
import { withRouter } from 'react-router-dom'
function Editstudentdetails(props) {
const [getStudentDataById, setStudentDataById] = useState([])
const [editStudentDataById, latestEdit] = useState({ name:'', position: '', location: '', salary: '', email: '', password: '' })
const id = props.match.params.id
console.log(id)
useEffect(() => {
const getDataById = async () => {
try {
const result = await axios.get(`http://localhost:7500/api/registration/${id}`)
setStudentDataById(result.data)
console.log(result.data)
} catch (error) {
console.log(error)
}
}
getDataById()
}, [])
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, getStudentDataById, { [name]: value });
setStudentDataById(newData);
const latestData = Object.assign({}, editStudentDataById, { [name]: value })
latestEdit(latestData)
}
const handleSubmit = async e => {
e.preventDefault();
console.warn(editStudentDataById)
const editDataById = async () => {
try {
const response = await axios.put(`http://http://localhost:7500/api/registration/${id}`, editStudentDataById)
latestEdit(response.data)
console.warn(response.data)
} catch (error) {
console.warn(error)
}
}
editDataById()
}
return (
<div className='container'>
<div className='row'>
<div className='col-4'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Name</label>
<input type="text" name='name' value={getStudentDataById.name} onChange={handleChange} className="form-control" id="name"></input>
</div>
<div className="form-group">
<label htmlFor="position">Position</label>
<input type="text" name='position' value={getStudentDataById.position} onChange={handleChange} className="form-control" id="position"></input>
</div>
<div className="form-group">
<label htmlFor="location">Location</label>
<input type="text" name='location' value={getStudentDataById.location} onChange={handleChange} className="form-control" id="location"></input>
</div>
<div className="form-group">
<label htmlFor="salary">Salary</label>
<input type="number" name='salary' value={getStudentDataById.salary} onChange={handleChange} className="form-control" id="salary"></input>
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input type="email" name='email' onChange={handleChange} value={getStudentDataById.email} className="form-control" id="email"></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" name='password' onChange={handleChange} value={getStudentDataById.password} className="form-control" id="password"></input>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
)
}
export default withRouter(Editstudentdetails)
If you feel I am not clear with my doubt please put a comment Thank you
Please follow this example. It works perfectly.
import React, {useState, useEffect} from 'react';
import axios from 'axios';
function EditStudentDetails() {
const [post, setPost] = useState({});
const id = 1;
const handleChange = ({target}) => {
const {name, value} = target;
setPost({...post, [name]: value});
console.log(post);
};
const handleSubmit = async e => {
e.preventDefault();
const editDataById = async () => {
try {
const response = await axios.put(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: 'PUT',
body: JSON.stringify({
id: id,
title: post.title,
body: post.body,
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json));
console.warn(response.data);
} catch (error) {
console.warn(error);
}
};
editDataById();
};
return (
<div className='container'>
<div className='row'>
<div className='col-4'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Title</label>
<input type="text" name='title' value={post.title} onChange={handleChange}
className="form-control" id="title"/>
</div>
<div className="form-group">
<label htmlFor="position">Body</label>
<input type="text" name='body' value={post.body}
onChange={handleChange} className="form-control" id="body"/>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
)
}
export default EditStudentDetails;

PropType declared function, value is undefined

I'm trying to declare my function from a Action to the PropType but it always display a "...value is undefined". can someone tell where's my error?
I'v tried repack my react folder which is "client" using "npx" and also every related solution.
action/auth.js
import {
LOGIN_SUCCESS,
LOGIN_ERROR,
USER_LOADING,
USER_LOADED,
REGISTER_ERROR,
REGISTER_SUCCESS
} from "./types";
import axios from "axios";
export const getConfig = getState => {
let config = {
headers: { "Content-Type": "application/json" }
};
const token = getState().auth.token;
if (token) {
config.headers["x-auth-token"] = `Bearer ${token}`;
}
return config;
};
export const registerUser = userObj => (dispatch, getState) => {
axios
.post("/auth/register", JSON.stringify(userObj), getConfig(getState))
.then(result => {
console.log(result);
dispatch({
type: LOGIN_SUCCESS,
payload: result.data
});
})
.catch(error => {
console.log(error);
dispatch({
type: LOGIN_ERROR
});
});
};
component/main/RegisterForm
import React, { Component } from "react";
import { Link } from "react-router-dom";
import { Alert } from "reactstrap";
import { registerUser } from "../../actions/auth";
import { connect } from "react-redux";
import PropTypes from "prop-types";
export class RegisterForm extends Component {
constructor(props) {
super(props);
document.title = "OnlineChat - Register";
}
state = {
firstname: "",
lastname: "",
email: "",
password: "",
password1: "",
error: null,
visible: false
};
static propTypes = {
registerUser: PropTypes.func.isRequired
};
onChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
onDismiss = e => {
this.setState({ visible: false, error: null });
};
onSubmit = e => {
e.preventDefault();
const { firstname, lastname, email, password, password1 } = this.state;
const userObj = this.state;
console.log(firstname, lastname, email, password, password1);
if (!firstname || !lastname || !email || !password || !password1) {
return this.setState({ error: "Please fill all fields.", visible: true });
}
if (password !== password1) {
return this.setState({ error: "Password must match.", visible: true });
}
this.props.registerUser(userObj);
this.setState({
firstname: "",
lastname: "",
email: "",
password: "",
password1: ""
});
};
render() {
const {
firstname,
lastname,
email,
password,
password1,
error,
visible
} = this.state;
return (
<div className="d-flex align-items-center" style={{ height: "100vh" }}>
<div className="container">
<div className="row">
<div className="col-12 col-sm-12 col-md-6 col-lg-6 offset-md-3">
<Alert color="danger" isOpen={visible} toggle={this.onDismiss}>
<strong>Alert! </strong>
{error}
</Alert>
<div className="card">
<div className="card-body">
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label htmlFor="">First Name</label>
<input
type="text"
autoComplete="off"
className="form-control"
onChange={this.onChange}
value={firstname}
name="firstname"
/>
</div>
<div className="form-group">
<label htmlFor="">Last Name</label>
<input
type="text"
autoComplete="off"
className="form-control"
onChange={this.onChange}
value={lastname}
name="lastname"
/>
</div>
<div className="form-group">
<label htmlFor="">Email</label>
<input
type="email"
autoComplete="off"
className="form-control"
onChange={this.onChange}
value={email}
name="email"
/>
</div>
<div className="form-group">
<label htmlFor="">Password</label>
<input
type="password"
autoComplete="off"
className="form-control"
onChange={this.onChange}
value={password}
name="password"
/>
</div>
<div className="form-group">
<label htmlFor="">Re-type Password</label>
<input
type="password"
autoComplete="off"
className="form-control"
onChange={this.onChange}
value={password1}
name="password1"
/>
</div>
<button
className="btn btn-block btn-outline-success"
type="submit"
>
Register
</button>
</form>
<div className="d-block justify-content-left pt-2">
<Link to="/" className="cLink">
Have an account ?
</Link>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(
mapStateToProps,
{ registerUser }
)(RegisterForm);
reducer/authReducer
import {
LOGIN_ERROR,
LOGIN_SUCCESS,
REGISTER_ERROR,
REGISTER_SUCCESS,
USER_LOADING
} from "../actions/types";
const initialState = {
token: localStorage.getItem("token"),
isAuthenticated: null,
isLoading: false,
user: null
};
export default (state = initialState, action) => {
switch (action.type) {
case USER_LOADING:
return {
...state,
isLoading: true
};
case LOGIN_SUCCESS:
case REGISTER_SUCCESS:
localStorage.setItem("token", action.payload.token);
return {
...state,
...action.payload,
isAuthenticated: true,
isLoading: false
};
case LOGIN_ERROR:
case REGISTER_ERROR:
return {
...state,
token: null,
isAuthenticated: null,
isLoading: false,
user: null
};
default:
return state;
}
};
Here's the error message keeps prompting in my console.
Error Message
Delete export from class, make it class RegisterForm extends Component { not export class RegisterForm extends Component { since you are exporting the module at the bottom saying export default connect

Resources