i want to show details on same page - reactjs

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);
}
});
};

Related

Two times click is necessary to Login in ReactJS

I am trying to make a Login page and I am successful in some way. So here is my Login component:
import React, { useState, useEffect } from "react";
import Axios from "axios";
import useForm from "../components/LoginForm/useForm";
import validate from "components/LoginForm/validate";
import redtruck from "../assets/img/red-truck.png";
import auth from "../Authentication/auth";
import { withRouter } from "react-router";
const Login = ({ submitForm, history }) => {
const [isSubmitted, setIsSubmitted] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
const [login, setLogin] = useState(false);
async function submitForm() {
setIsSubmitted(true);
try {
await fetchLogin(values.email, values.password);
if(login){
auth.login(() => {
history.push("/admin");
});
}
} catch (e) {
auth.login(() => {
history.push("/");
})
}
}
const { handleChange, values, handleSubmit, errors } = useForm(
submitForm,
validate
);
useEffect(() => {
if (localStorage.getItem("user-info")) {
submitForm();
}
}, []);
const fetchLogin = async (email, password) => {
try {
setLoading(true);
const res = await Axios({
method: "POST",
url: `url`,
headers: {
},
data: {
user_email: email,
user_password: password,
},
});
if (res.status === 200) {
setLogin(true);
localStorage.setItem("user-info", JSON.stringify(res.data));
}
setLoading(false);
} catch (err) {
setError(err.message);
setLoading(false);
}
};
return (
<>
<div>
<div className="form-container">
<div className="form-content-left">
<img className="form-img" src={redtruck} alt="spaceship" />
</div>
<div className="form-content-right">
<h1>SIGN IN</h1>
<form className="form" onSubmit={handleSubmit}>
<div className="form-inputs">
<label htmlFor="email" className="form-label">
Email address
</label>
<input
id="signin-email"
type="email"
name="email"
placeholder="Enter email"
className="form-input"
value={values.email}
onChange={handleChange}
/>
{errors.email && <p>{errors.email}</p>}
</div>
<div className="form-inputs">
<label htmlFor="password" className="form-label">
Password
</label>
<input
id="signin-password"
type="password"
name="password"
placeholder="Password"
className="form-input"
value={values.password}
onChange={handleChange}
/>
{errors.password && <p>{errors.password}</p>}
{login ? "" : <p>The password or the email is wrong</p>}
</div>
<button
variant="primary"
type="submit"
className="form-input-btn"
>
LOGIN
</button>
</form>
</div>
</div>
</div>
</>
);
};
export default withRouter(Login);
So the login state is set to true when email and password are right for the user. Later I want to use it when redirecting page to "/admin". But my problem is I have to click twice to login in the first place. Besides I am not sure, if the catch part is right:
catch (e) {
auth.login(() => {
history.push("/");
})
}
So I would be really glad, if you can give me some hint about it.
Thanks...
it is not that you have to press twice, you can check component state, sometimes React batches setState and then update value. You can look at this setState doesn't update the state immediately

I can't find an example of how to make an HTTP POST request using useEffect hook along with axios

Lately, I've been trying to make an HTTP POST request using the useEFfect hook along with axios, but the code returns this error in the console: Error: Request failed with status code 422. The POST request is always successfully made when I make it from the form onSubmit handler. However, when I try to make it from the useEffect hook, it gives that error. Can anybody help me with what I'm doing wrong? Here's the code:
import React, { useState, useEffect } from "react";
import axios from "axios";
function RandomPost() {
const [input, setInput] = useState({
name: "",
email: "",
companyName: "",
password: "",
});
const handleChange = (event) => {
setInput({ ...input, [event.target.id]: event.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
};
useEffect(() => {
const { name, email, companyName, password } = input;
axios
.post(`https://01hire.collaq.com/user/createCompany`, input)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}, [input]);
const { name, email, companyName, password } = input;
return (
<div>
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" id="name" value={name} onChange={handleChange} />
</label>
<label>
Email:
<input type="text" id="email" value={email} onChange={handleChange} />
</label>
<label>
Company Name:
<input
type="text"
id="companyName"
value={companyName}
onChange={handleChange}
/>
</label>
<label>
Password:
<input
type="password"
id="password"
value={password}
onChange={handleChange}
/>
</label>
<button type="submit">Submit</button>
</form>
</div>
);
}
export default RandomPost;

Better way to check input values of a form in React/Next Js

I've written a simple form for my web application. I plan on writing a feature that checks to make sure all fields are non-empty and valid, and displaying an error message as a component if not. This is the skeleton:
import { useState } from 'react';
import emailjs from "emailjs-com";
import apiKeys from "../public/credentials/apikeys";
import ContactStyles from "../public/styles/ContactStyles";
function ContactForm() {
const [fieldDict, setFieldDict] = useState(
{
name: "",
email: "",
subject: "",
message: ""
});
function sendEmail(e) {
e.preventDefault();
// TODO: Show success or error message
var blankField = false;
if (fieldDict.name.length === 0) {
console.log("No name"); // To be implemented here and on subsequent lines
blankField = true;
}
if (fieldDict.email.length === 0) {
console.log("No email");
blankField = true;
}
if (fieldDict.subject.length === 0) {
console.log("No subject");
blankField = true;
}
if (fieldDict.message.length === 0) {
console.log("No message");
blankField = true;
}
if (blankField) { return }
emailjs.sendForm(apiKeys.serviceID, apiKeys.templateID, e.target, apiKeys.userID)
.then((result) => {
console.log(result, fieldDict);
}, (error) => {
console.log(error, fieldDict);
});
e.target.reset();
}
return (
<div className="contact-section">
<div className="contact-container">
<h5 className="form-header">Send me an email!</h5>
<form className="contact-form" onSubmit={sendEmail}>
<div className="form-group">
<label className="label">Name</label>
<input className="input" type="text" name="name" autoComplete="off"
onInput={e => {
setFieldDict(prevFieldDict => ({...prevFieldDict, name: e.target.value}));
}}/>
</div>
<div className="form-group">
<label className="label">Email</label>
<input className="input" type="email" name="email" autoComplete="off"
onInput={e => {
setFieldDict(prevFieldDict => ({...prevFieldDict, email: e.target.value}));
}}/>
</div>
<div className="form-group">
<label className="label">Subject</label>
<input className="input" type="subject" name="subject" autoComplete="off"
onInput={e => {
//? Viability of this method?
setFieldDict(prevFieldDict => ({...prevFieldDict, subject: e.target.value}));
}}/>
</div>
<div className="form-group">
<label className="label">Message</label>
<textarea className="input textarea" name="message" rows="6"
onInput={e => {
setFieldDict(prevFieldDict => ({...prevFieldDict, message: e.target.value}));
}}/>
</div>
<div className="submit">
<button type="submit" value="Send">Submit</button>
</div>
</form>
</div>
<style jsx global>{ContactStyles}</style>
</div>
);
}
export default ContactForm;
With every keystroke, the corresponding key (name, email, subject, message) gets updated.
Question
Is there a better way to do this? A more efficient way to do this seems to be only updating the fieldDict dictionary when the use hits submit, but based on how react renders components does this really matter?
Note: The code as is works just fine, I'm just asking if there is a better way to do this? If you want a better way of seeing this, change the content of onInput{...} to e => console.log(e.target.value).
Any insight is much appreciated!
You can iterate through your dict and filter all names that are falsable.
function sendEmail(e) {
e.preventDefault();
const blankFields = Object.keys(fieldDict).filter(fieldName => !fieldDict[fieldName])
blankFields.forEach(fieldName => console.log(`no ${fieldName}`);
if (blankFields.length) { return }
emailjs.sendForm(apiKeys.serviceID, apiKeys.templateID, e.target, apiKeys.userID)
.then((result) => {
console.log(result, fieldDict);
}, (error) => {
console.log(error, fieldDict);
});
e.target.reset();
}

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;

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

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
});
});
};

Resources