Form edit not working in react with onchange - javascript

I am trying to populate a form with data from different tables and allow the user to update the data for both.
I have populated the data in the form but I am not able to edit the data for certain fields which I have called inside a map function.
It is not allowing me to change or add data. Refer last input element of the form.
import React, { Fragment, useState, useEffect } from "react";
const ViewPt = ({ pts }) => {
// const [description, setDescription] = useState(todo.description);
const [name, setName] = useState(pts.name);
const [mobile, setMobile] = useState(pts.mobile);
const [email, setEmail] = useState(pts.email);
const [gender, setGender] = useState(pts.gender);
const [dob, setDob] = useState(pts.dob);
const [address, setAddress] = useState(pts.address);
const [treatment, setTreatment] = useState([]);
const [treatment_date, setTreatment_date] = useState("");
const [treatment_done, setTreatment_done] = useState("");
const [cost, setCost] = useState("");
const [paid, setPaid] = useState("");
const [next_appointment, setNext_appointment] = useState("");
const [selectedTreatment, setSelectedTreatment] = useState(false);
//edit patient function
const updatePatient = async(e) => {
e.preventDefault();
try {
const body ={ name,email,mobile,gender,dob,address };
const response = await fetch(`http://localhost:5000/patients/${pts.patient_id}`,{
method: "PUT",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(body)
});
window.location ="/";
} catch (err) {
console.error(err.message);
}
}
//get treatment information
const getTreatment = async() =>{
try {
const response = await fetch(`http://localhost:5000/patients/:id/treatment`)
const jsonData = await response.json();
setTreatment(jsonData);
} catch (err) {
console.error(err.message);
}
}
useEffect(() => {
getTreatment();
},[]);
//function for getting treatment details
const filterTreatmentDetails =async(e) =>{
console.log("__here__1", pts, treatment);
try{
const filtered = treatment.filter(t => pts.patient_id == t.patient_id);
if (
filtered
&& filtered.length > 0
) {
setSelectedTreatment(filtered);
}
console.log(filtered);
console.log("__here__2");
return filtered;
}
catch (err) {
console.error(err.message);
}
}
//edit treatment function
const updateTreatment = async(e) => {
e.preventDefault();
try {
const body ={ treatment_date,treatment_done,cost,paid,next_appointment };
const response = await fetch(`http://localhost:5000/patients/${pts.patient_id}/treatment`,{
method: "PUT",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(body)
});
window.location ="/";
} catch (err) {
console.error(err.message);
}
}
return <Fragment>
<button type="button" class="btn btn-warning" data-toggle="modal" onClick={filterTreatmentDetails} data-target={`#view${pts.patient_id}`}>
Edit
</button>
<div class="modal" id={`view${pts.patient_id}`}>
{/* onClick={() => setDescription(todo.description)} */}
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Data</h4>
<button type="button" class="close" data-dismiss="modal" >×</button>
</div>
<form className="text-left" onSubmit={updatePatient,updateTreatment}>
<div class="modal-body">
<div class="form-control">
<label for="name">Name </label>
<input type="text" className="form-control" id="name" placeholder="Enter Name" value={name} onChange={e=>setName(e.target.value)}/>
<small></small>
</div>
<div class="form-control" >
<label for="gender">Gender </label>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="inlineRadio1" value={gender} onChange ={e =>setGender(`m`)} />
<label class="form-check-label" for="inlineRadio1">Male</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="inlineRadio2" value={gender} onChange ={e =>setGender(`f`)} />
<label class="form-check-label" for="inlineRadio2">Female</label>
</div>
<small></small>
</div>
<div class="form-control">
<label for="email">Email</label>
<input type="text" className="form-control" id="email" placeholder="Enter Email" value={email} onChange={e=>setEmail(e.target.value)} />
<small></small>
</div>
<div class="form-control">
<label for="mobile">mobile</label>
<input type="number" className="form-control" id="mobile" placeholder="Enter 10 digit number" value={mobile} onChange={e=>setMobile(e.target.value)}/>
<small></small>
</div>
<div class="form-control">
<label for="dob">Date of Birth</label>
<input type="text" className="form-control" id="dob" placeholder="dob" value={dob}/>
<input type="date" className="form-control" id="dob" placeholder="dob" value={dob} onChange={e=>setDob(e.target.value)}/>
<small></small>
</div>
<div class="form-control">
<label for="address">Address</label>
<input type="text" className="form-control" id="address" placeholder="address" value={address} onChange={e=>setAddress(e.target.value)}/>
<small></small>
</div>
{
selectedTreatment && selectedTreatment.map(subTreatment => (
<div class="form-control" key={subTreatment.treatment_id}>
<label for="treatment">Treatment Done</label>
<input
type="text"
className="form-control"
id="treatment"
placeholder="Treatment Done"
value={subTreatment.treatment_done}
onChange={e=>setTreatment_done(e.target.value)}
/>
<small></small>
</div>
))
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal" onClick = {e => {updatePatient(e);updateTreatment(e)}}>Edit</button>
{/* <button type="button" class="btn btn-danger" data-dismiss="modal" onClick={() => {setName(patient.name),setEmail(patient.email),setMobile(patient.mobile),setGender(patient.gender),setDob(patient.dob),setAddress(patient.address)}}>Close</button> */}
</div>
</form>
</div>
</div>
</div>
</Fragment>
};
export default ViewPt;
In my understanding, below code is not working :
onChange={e=>setTreatment_done(e.target.value)}
I really appreciate your help!

In your hook, you are using treatment_done
const [treatment_done, setTreatment_done] = useState("");
but in your last input, the value is using
subTreatment.treatment_done, so
treatment_done
in your state hook has never been used.

Related

Issue with form submit using Reactjs

I am working on Reactjs(Nextjs),Trying to submit form but unable to submit form,How can i submit form data ? Here is my current code
export default function Home() {
const checklogin = async (e:any) => {
e.preventDefault();
alert("Its working");
}
<form className="forms-sample" onSubmit={checklogin}>
<div className="form-group first">
<label htmlFor="username">Username</label>
<input
type="text"
className="form-control"
placeholder="your-email#gmail.com"
id="username"
/>
</div>
<div className="form-group last mb-3">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
placeholder="Your Password"
id="password"
/>
</div>
<input
type="submit"
name="submit"
defaultValue="Log In"
className="btn btn-block btn-primary"
/>
</form>
1. controlled form
import React from 'react';
export default function Home() {
const INITIAL_DATA = {
username: '',
password: '',
};
const [formData, setFormData] = React.useState(INITIAL_DATA);
const checklogin = async (e) => {
e.preventDefault();
console.log(formData); // * PROCESS FORMDATA ON SUBMIT
alert('Its working');
setFormData(INITIAL_DATA); // * CLEAR DATA AFTER SUBMIT
};
function handleOnChangeInput(event) {
const name = event?.target?.name;
const value = event?.target?.value;
setFormData((prev) => ({
...prev,
[name]: value,
}));
}
return (
<form className='forms-sample' onSubmit={checklogin}>
<div className='form-group first'>
<label htmlFor='username'>Username</label>
<input
type='text'
className='form-control'
placeholder='your-email#gmail.com'
id='username'
onChange={handleOnChangeInput}
value={formData?.username}
/>
</div>
<div className='form-group last mb-3'>
<label htmlFor='password'>Password</label>
<input
type='password'
className='form-control'
placeholder='Your Password'
id='password'
onChange={handleOnChangeInput}
value={formData?.password}
/>
</div>
<input
type='submit'
name='submit'
defaultValue='Log In'
className='btn btn-block btn-primary'
/>
</form>
);
}
2. Uncontrolled form
import React from 'react';
export default function Home() {
const formRef = React.useRef(null);
const checklogin = async (event) => {
event.preventDefault();
alert('Its working');
// * Get form enteries
const formData = new FormData(formRef?.current);
const formEnteries = Object.fromEntries(formData?.entries());
console.log(formEnteries); // * PROCESS FORMENTERIES ON SUBMIT
// * Clear form fields here
const formCurrentTarget = event?.currentTarget;
formCurrentTarget?.reset();
};
return (
<form className='forms-sample' onSubmit={checklogin} ref={formRef}>
<div className='form-group first'>
<label htmlFor='username'>Username</label>
<input
type='text'
className='form-control'
placeholder='your-email#gmail.com'
id='username'
name='username'
/>
</div>
<div className='form-group last mb-3'>
<label htmlFor='password'>Password</label>
<input
type='password'
className='form-control'
placeholder='Your Password'
id='password'
name='password'
/>
</div>
<input
type='submit'
name='submit'
defaultValue='Log In'
className='btn btn-block btn-primary'
/>
</form>
);
}
Read more about controlled and uncontrolled components here - Link

How can I persist updated form data after submit?

So I have some formdata in my react app that I want to persist after I make a put request to the mongodb. Problem is that the change is not visible on page refresh. It is only after I log out and log in again that I can see the updated value in the form.
For example let's say that I want to change my first name from John to Eric. The change will update but not in the form. In the form the value will still be John until I log out and in again.
It feels almost like it has to do with the jwt token but I don't know. Any ideas what the problem can be?
export const Edit = () => {
const navigate = useNavigate();
const user = Cookies.get("access_token");
const [id, setId] = useState(null)
const [firstName, setFirstName] = useState("")
const [lastName, setLastName] = useState("")
const [city, setCity] = useState("")
const [email, setEmail] = useState("")
const checkUser = async () => {
try {
const res = await axios
.get(`${process.env.REACT_APP_API_URL}user/protected`, {
withCredentials: true,
headers: {
Authorization: `Bearer ${user}`,
},
})
console.log(res.data.user);
setId(res.data.user.id)
setFirstName(res.data.user.firstName)
setLastName(res.data.user.lastName)
setCity(res.data.user.city)
setEmail(res.data.user.email)
} catch (error) {
console.warn(error)
}
}
useEffect(() => {
if (!user) {
navigate('/')
} else {
checkUser();
}
}, []);
const updateUser = async () => {
try {
const userData = {
firstName: firstName,
lastName: lastName,
city: city,
email: email
}
const API_URL = `${process.env.REACT_APP_API_URL}user/`;
const userId = id;
const res = await axios.put(API_URL + "/" + userId + "/edit", userData)
setFirstName(res.data.firstName)
setLastName(res.data.lastName)
setCity(res.data.city)
setEmail(res.data.email)
// works and is updated in the database
} catch (error) {
console.warn(error)
}
}
return (
<>
<section className="m-5">
<h1 className="mb-5 text-center">Settings</h1>
<form className="row g-3">
<div className="col-md-6">
<label htmlFor="firstName" className="form-label">
First name
</label>
<p>{formErrors.firstName}</p>
<input
type="text"
className="form-control"
id="firstName"
name="firstName"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
/>
</div>
<div className="col-md-6">
<label htmlFor="lastName" className="form-label">
Last name
</label>
<p>{formErrors.lastName}</p>
<input
type="text"
className="form-control"
id="lastName"
name="lastName"
value={lastName}
onChange={(e) => setLastName(e.target.value)}
/>
</div>
<div className="col-md-6">
<label htmlFor="city" className="form-label">
City
</label>
<p>{formErrors.city}</p>
<input
type="text"
className="form-control"
id="city"
name="city"
value={city}
onChange={(e) => setCity(e.target.value)}
/>
</div>
<div className="col-md-6">
<label htmlFor="email" className="form-label">
Email
</label>
<p>{formErrors.email}</p>
<input
type="email"
className="form-control"
id="email"
name="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="col-12 pt-4 text-center">
<button
type="submit"
className="btn btn-primary btn-lg"
onClick={updateUser}
>
Update
</button>
</div>
<div className="col-12 pt-1 text-center">
<button
type="submit"
className="btn btn btn-lg"
>
<a href="edit/password" className="text-decoration-none">
Change Password
</a>
</button>
</div>
</form>
</section>
</>
);
};
Add user as a dependency to the useEffect's dependency array:
useEffect(() => {
if (!user) {
navigate('/')
} else {
checkUser();
}
}, [user]);

REACT: SELECT from MYSQL

i a new user and a new in React world. I need help to solve this situation about a Select with values from mysql DB.
I receive the values, but the select goes in infinite loop.
The error is surely in this file cause server.js works without problem!!
Really thanks for the help, and sorry if it could be a stupid question. I m studying react from one week and i have not found answers on internet
function FormAddMenu({ registerMenu }) {
const [nomeMenuReg, setNomeMenuReg] = useState("");
const [descrizioneMenuReg, setDescrizioneMenuReg] = useState("");
const [prezzoMenuReg, setPrezzoMenuReg] = useState("");
const [disponibilitaMenuReg, setDisponibilitaMenuReg] = useState("");
const [portataMenuReg, setPortataMenuReg] = useState("");
const [addMenu, setAddMenu] = useState({
portataMenuReg: "",
nomeMenuReg: "",
descrizioneMenuReg: "",
prezzoMenuReg: "",
disponibilitaMenuReg: "",
});
const [portate, setPortate] = useState({ value: "", label: "" });
const selectOptions = async () => {
Axios.post("http://localhost:3001/selectPortata").then((response) => {
// console.log("risposta:",response.data)
setPortate(
response.data.map((risp) => ({
...setPortate,
value: risp.value,
label: risp.label,
})),
);
});
};
selectOptions();
console.log("portate:", portate);
const submitHandler = (e) => {
e.preventDefault();
registerMenu(addMenu);
document.getElementById("addmenu").reset();
};
const handleCheckbox = (e) => {
console.log(e.target.checked);
if (e.target.checked === true) {
setAddMenu({ ...addMenu, disponibilitaMenuReg: 1 });
} else {
setAddMenu({ ...addMenu, disponibilitaMenuReg: e.target.value });
}
};
return (
<div className="container width85">
<h1>CREA IL MENU'</h1>
<form id="addmenu">
<div className="mb-3">
<label htmlFor="portataMenuReg" className="form-label">
PORTATA
</label>
<Select
options={portate}
onChange={(e) => setAddMenu({ ...addMenu, portataMenuReg: e.target.value })}
className="mb-3"
/>
</div>
<div className="mb-3">
<label htmlFor="nomeMenuReg" className="form-label">
NOME
</label>
<input
type="text"
onChange={(e) => setAddMenu({ ...addMenu, nomeMenuReg: e.target.value })}
className="form-control"
id="nomeMenuReg"
rows="3"
/>
</div>
<div className="mb-3">
<label htmlFor="descrizioneMenuReg" className="form-label">
DESCRIZIONE
</label>
<textarea
className="form-control"
onChange={(e) =>
setAddMenu({ ...addMenu, descrizioneMenuReg: e.target.value })
}
id="descrizioneMenuReg"
rows="3"
></textarea>
</div>
<div className="mb-3">
<label htmlFor="prezzoMenuReg" className="form-label">
PREZZO
</label>
<input
type="text"
className="form-control"
onChange={(e) => setAddMenu({ ...addMenu, prezzoMenuReg: e.target.value })}
id="prezzoMenuReg"
rows="3"
/>
</div>
<div className="mb-3">
<label htmlFor="disponibilitaMenuReg" className="form-label">
DISPONIBILITA'
</label>
<input
type="checkbox"
value="0"
className="htmlForm-control"
onChange={handleCheckbox}
id="disponibilitaMenuReg"
rows="3"
/>
</div>
<div className="mb-3">
<button type="submit" onClick={submitHandler} className="btn btn btn-danger">
AGGIUNGI AL MENU
</button>
</div>
</form>
</div>
);
}
export default FormAddMenu;
Wrap the selectOptions(); call in an useEffect (since loading data and mutating state based on it is a side effect).
The empty dependency array (documented above) means the effect is only executed once on mount.
React.useEffect(() => {
selectOptions();
}, []);

ReactJs | Show only the selected value in URL

I am new to reatJS. Can some genius please help me with my issue?
I am developing a e-pharmacy website where I let the users to first select a preferred districts and select a pharmacy from that area. I list out all the districts along with a drop down menu which shows all the pharmacies in that district. Then the user can make orders to the selected pharmacy.
I pass the selected pharmacy Id through the URL when user post an order.
If I had 3 districts, and I have selected a pharmacy from the third district, the URL appears like this:
http://localhost:3000/uploadlist?phmcy=&phmcy=&phmcy=1 (here the id of the selected pharmacy is "1")
The URL shows all the unselected values also. My preference is to display only the selected pharmacy's Id.
I want only the selected value to be displayed. Like this:
http://localhost:3000/uploadlist?phmcy=1
Here is my codes:
The district component: (Where the customer can select a district)
import React,{ Component } from 'react';
//import { Router } from 'react-router-dom/cjs/react-router-dom.min';
import { Link, withRouter } from "react-router-dom";
import './district.css';
import Upload from "./upload.component";
import Districtpharmacy from "./districtpharmacy.component";
class District extends React.Component{
state = {
pharmacy: []
};
render(){
return(
<div className="container">
<div className="container district">
<form action="/uploadlist" method="get">
<div className="row">
<div className="container header">
<h1>Select your District and Nearby Pharmacy</h1>
<p>Please select only one pharmacy</p>
</div>
</div>
<div className="row">
<div className="form-column">
<Districtpharmacy district="Mathara"/>
<Districtpharmacy district="Galle"/>
<Districtpharmacy district="Hambantota"/>
<Districtpharmacy district="Kalutara"/>
<Districtpharmacy district="Colombo"/>
<Districtpharmacy district="Gampaha"/>
<Districtpharmacy district="Rathnapura"/>
<Districtpharmacy district="Kurunegala"/>
</div>
<div className="form-column">
<Districtpharmacy district="Monaragala"/>
<Districtpharmacy district="Anuradhapura"/>
<Districtpharmacy district="Polonnaruwa"/>
<Districtpharmacy district="Kandy"/>
<Districtpharmacy district="Nuwara Eliya"/>
<Districtpharmacy district="Kegalla"/>
<Districtpharmacy district="Matale"/>
<Districtpharmacy district="Badulla"/>
<Districtpharmacy district="Ampara"/>
</div>
<div className="form-column">
<Districtpharmacy district="Puttalam"/>
<Districtpharmacy district="Trincomalee"/>
<Districtpharmacy district="Batticaloa"/>
<Districtpharmacy district="Mannar"/>
<Districtpharmacy district="Vavuniya"/>
<Districtpharmacy district="Mulaitivu"/>
<Districtpharmacy district="Kilinochchi"/>
<Districtpharmacy district="Jaffna"/>
</div>
</div>
<br/>
<button type="submit" >Add</button>
</form>
</div>
</div>
);
}
}
export default withRouter(District);
district.pharmacy component: (where the dropdown menu is returned.)
import React,{ Component } from 'react';
//import { Router } from 'react-router-dom/cjs/react-router-dom.min';
import { Link } from "react-router-dom";
import './district.css';
//import Upload from "./upload.component";
class Districtpharmacy extends React.Component{
state = {
pharmacy: [],
District: this.props.district
};
componentDidMount() {
console.log(this.state)
fetch("https://localhost:44357/api/Pharmacies?field=district&value="+this.props.district)
.then(response => response.json())
.then(pharmacy => this.setState({pharmacy: pharmacy}));
//console.log(this.state)
}
render(){
//console.log(this.state)
const pharm=this.state.pharmacy.map((pharmacies) =>{
return(<option value ={pharmacies.id}>{pharmacies.pharmacyname},{pharmacies.address}</option>)})
return(
<div>
<label class="label" for="district"><span>{this.props.district}</span></label>
<select name="phmcy" className="form-control select-dropdown"><option value="">Select Pharmacy</option>{pharm}</select>
</div>
)
}
}
export default Districtpharmacy
Can someone help me with this?
Edited:
The order posting form:
The parent file: (uploadlist.js)(the "phmcy" value is to be fetched from the url. this file is triggered after selecting the pharmacy)
export default function Uploadlist() {
let myphmcy = (new URLSearchParams(window.location.search)).get("phmcy")
console.log(myphmcy);
const ordersAPI= (url='https://localhost:44357/api/Orders') => {
return {
fetchAll: () => axios.get(url),
create: newRecord => axios.post(url, newRecord),
update: (id, updateRecord) => axios.put(url + id, updateRecord),
delete: id => axios.delete(url+id)
}
}
const addOrEdit = (formData, onSuccess) => {
ordersAPI().create(formData)
.then(res => {
onSuccess();
})
.catch(err => console.log(err.response.data))
}
return (
<div className="row">
<div className="jumbotron jumbotron-fluid py-4 "></div>
<div className="container text">
<h1 className="display-4"> Order Register</h1>
</div>
<div className="col-md-4 offset-3">
<Upload //this is the child component where the order form is built.
addOrEdit = {addOrEdit}
myphmcy = {myphmcy}
/>
</div>
<div className="col-md-1">
<div> </div>
</div>
</div>
)
}
the child file:
const initialFieldValues ={
orderID:0,
date_time:'',
status:'',
status2:'',
pharmacyName:'',
customerName:'',
patientName:'',
patientAge:'',
address:'',
email:'',
teleNo:'',
customer_id:1,
pharmacy_id:0,//data obtaind from the URL have to posted as the pharmacyID when posting.
image:'',
imageSource:'',
imageData: null
}
export default function Upload(props) {
const {addOrEdit} = props
const {myphmcy} = props
console.log(myphmcy);
const [values, setValues] = useState(initialFieldValues)
const[errors, setErrors] = useState({})
const handleInputChange= e => {
const {name, value} = e.target;
setValues({
...values,
[name]:value
})
}
/*const addOrEdit = (formData, onSuccess) => {
ordersAPI().create(formData)
.then(res => {
onSuccess();
})
.catch(err => console.log(err.response.data))
}*/
const showPreview = e => {
if(e.target.files && e.target.files[0]){
let imageData = e.target.files[0];
const reader = new FileReader();
reader.onload = x => {
setValues({
...values,
imageData,
imageSource : x.target.result
})
}
reader.readAsDataURL(imageData)
}
else{
setValues({
...values,
imageData:null,
imageSource:''
})
}
}
const validate = () => {
let temp = {}
temp.customerName = values.customerName == "" ? false : true;
setErrors(temp)
return Object.values(temp).every(x => x == true)
}
const resetForm = () => {
setValues(initialFieldValues)
document.getElementById('image-uploader').value = null;
}
const handleFormSubmit = e => {
e.preventDefault()
if (validate()){
const formData = new FormData()
formData.append('orderID',values.orderID)
formData.append('date_time',values.date_time)
formData.append('status',values.status)
formData.append('status2',values.status2)
formData.append('pharmacyName',values.pharmacyName)
formData.append('customerName',values.customerName)
formData.append('patientName',values.patientName)
formData.append('patientAge',values.patientAge)
formData.append('address',values.address)
formData.append('email',values.email)
formData.append('teleNo',values.teleNo)
formData.append('customer_id',values.customer_id)
formData.append('pharmacy_id',myphmcy)
formData.append('image',values.image)
formData.append('imageData',values.ImageData)
addOrEdit(formData, resetForm)
alert("Your file is being uploaded!")
}
}
const applyErrorClass = field => ((field in errors && errors[field] == false) ? ' invalid-field' : '')
return (
<>
<div className="container text-center ">
<p className="lead"></p>
</div>
<form autoComplete="off" noValidate onSubmit={handleFormSubmit}>
<div className="card">
<div className="card-header text-center">Place Your Order Here</div>
<img src={values.imageSource} className="card-img-top"/>
<div className="card-body">
<div className="form-group">
<input type="file" accept="image/*" className="form-control-file" onChange={showPreview} id="image-uploader"/>
</div>
<div className="form-group">
<input type="datetime-local" className="form-control" placeholder="Date Time" name="date_time" value={values.date_time}
onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Enter the prescription items and qty" name="status" value={values.status} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="What are the symptoms?" name="status2" value={values.status2} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Pharmacy Name" name="pharmacyName" value={values.pharmacyName} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className={"form-control" + applyErrorClass('customerName')} placeholder="Your Name" name="customerName" value={values.customerName} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Patient Name" name="patientName" value={values.patientName} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Patient Age" name="patientAge" value={values.patientAge} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Delivery address" name="address" value={values.address} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Your Email" name="email" value={values.email} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Contact Number" name="teleNo" value={values.teleNo} onChange={ handleInputChange}/>
</div>
<div className="form-group text-center">
<button type="submit" className="btn btn-light">submit</button>
</div>
</div>
</div>
</form>
</>
)
}
The codes are so long. but I have uploaded them all for a better understanding of my issue.

How to update state after a promise response in react.js

I have class component for user sign up along with a form. I am making an api call based on user input to check if a user exists. The handleInputChange initially sets the state to some user input and the handleSubmit makes a call to another function which fetches from an endpoint. I want to set this.state.user to that response. I tried what was on this link but couldn't get it to work. Any ideas would help
import React, { Component } from 'react';
const user_add_api = "http://localhost:5000/add_user";
const user_check_api = "http://localhost:5000/user_by_username/";
here is the class:
class SignUp extends Component {
constructor(props) {
super(props);
this.state = {
first_name: '',
last_name: '',
username: '',
email: '',
password: '',
user: ''
};
}
checkUser = (user) => {
const userPromise = fetch(user_check_api + user);
var meh = '123meh';
userPromise
.then(data => data.json())
.then(data => this.setState({user: {...this.state.user, meh}}))
// let curr = {...this.state};
// curr['user'] = 'somevalue';
// this.setState({ curr:curr['user'] });
console.log(this.state.user);
}
handleSubmit = (event) => {
event.preventDefault();
const data = this.state;
let s = this.checkUser(data.username);
console.log(data);
}
handleInputChange = (event) => {
event.preventDefault();
this.setState({
[event.target.name]: event.target.value,
})
}
render () {
return (
<form className="form-horizontal">
<div className="form-group">
<label className="col-md-4 control-label">First Name</label>
<div className="col-md-4">
<input name="first_name" type="text" placeholder="John" className="form-control input-md" required onChange={this.handleInputChange}></input>
</div>
<label className="col-md-4 control-label">Last Name</label>
<div className="col-md-4">
<input name="last_name" type="text" placeholder="Doe" className="form-control input-md" required onChange={this.handleInputChange}></input>
</div>
<label className="col-md-4 control-label">Username</label>
<div className="col-md-4">
<input name="username" type="text" placeholder="John Doe" className="form-control input-md" required onChange={this.handleInputChange}></input>
</div>
<label className="col-md-4 control-label">Email</label>
<div className="col-md-4">
<input name="email" type="text" placeholder="johndoe#example.com" className="form-control input-md" required onChange={this.handleInputChange}></input>
</div>
<label className="col-md-4 control-label">Password</label>
<div className="col-md-4">
<input name="password" type="password" placeholder="" className="form-control input-md" required onChange={this.handleInputChange}></input>
</div>
<label className="col-md-4 control-label"></label>
<div className="col-md-8">
<button name="save" onClick={this.handleSubmit} className="btn btn-success">Register</button>
</div>
</div>
</form>
);
}
}
export default SignUp;
This fetch(user_check_api + user) return a Promise and you not wait it. Maybe you should change like that
checkUser = (user) => {
var meh = '123meh';
fetch(user_check_api + user)
.then(data => data.json())
.then(data => {
this.setState({user: {...this.state.user, meh}})
console.log(this.state.user) // Show log in in success func
})
}
Or use async/await
checkUser = async (user) => {
const userPromise = await fetch(user_check_api + user);
var meh = '123meh';
userPromise
.then(data => data.json())
.then(data => this.setState({
user: {...this.state.user, meh}
}, console.log(this.state.user))) // Show log in callback
}

Categories

Resources