I tried to do something very simple but I do not understand why it not working for me
so i have a component that include the details about the user are logged in
and i want to request the details user and put them in the component
so I do a axios.get to my back-end i get the detail set them in the state with success put them in the component but when I refresh the page i get state is undefined
I add here the code
import axios from "axios";
import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from 'react-router-dom'
import './account.css'
function Account(props) {
const [user, setUser] = useState()
const [currentPass, setCurrentPass] = useState()
const [newPass, setNewPass] = useState()
const [confirmPass, setConfirmPass] = useState()
let navigate = useNavigate();
useEffect(() => {
let userArr = []
try {
axios.create({ withCredentials: true }).get(`http://127.0.0.1:3000/users/getMe`)
.then(res => {
console.log(res.data.data.user) //object
userArr.push(res.data.data.user)
console.log(userArr)
setUser(userArr)
console.log(user)
})
} catch (error) {
console.log(error)
}
}, [])
const updatePassword = async (e) => {
e.preventDefault()
try {
const res = await axios.create({ withCredentials: true }).patch(`http://127.0.0.1:3000/users/updatePassword`, {
currentPassword: currentPass,
newPassword: newPass,
passwordConfirm: confirmPass
});
if (!res) {
return "not work"
}
console.log(res.data.data.user)
navigate("/", { replace: true });
} catch (error) {
console.log(error);
}
}
return (
<div className="account-container" >
<div className="title-container">
<p className="title">My Account</p>
</div>
<p className="sub-title">User information </p>
<form className="form-user-information">
<div className="div-form-user-information">
<label className="label-form-user-information">Username</label>
<textarea placeholder="Username..." />
</div>
<div className="div-form-user-information">
<label className="label-form-user-information">ssss</label>
<textarea placeholder={user.map(el => {
return el.email
})} />
</div>
<div className="div-form-user-information">
<label className="label-form-user-information">First name</label>
<textarea placeholder="First name..." />
</div>
<div className="div-form-user-information">
<label className="label-form-user-information">Last name</label>
<textarea placeholder="Last name..." />
</div>
</form>
<div className="buttom-line"></div>
{/* //////CONTACT INFORMATION////////// */}
<p className="sub-title-contact">CONTACT INFORMATION </p>
<form className="form-contact-information">
<div className="div-form-contact-information">
<label className="label-form-contact-information">Full Address</label>
<textarea placeholder="Full Address..." />
</div>
<div className="div-form-contact-information">
<label className="label-form-contact-information">City</label>
<textarea placeholder="City..." />
</div>
<div className="div-form-contact-information">
<label className="label-form-contact-information">Country</label>
<textarea placeholder="Country..." />
</div>
<div className="div-form-contact-information">
<label className="label-form-contact-information">Postal code</label>
<textarea placeholder="Postal code..." />
</div>
</form>
<div className="buttom-line-contact"></div>
{/* //////PASSWORD INFORMATION////////// */}
<p className="sub-title-password">UPDATE PASSWORD </p>
<form className="form-password-information">
<div className="div-form-password-information">
<label className="label-form-password-information">Current Password</label>
<textarea onChange={(e) => setCurrentPass(e.target.value)} placeholder="Current Password..." />
</div>
<div className="div-form-password-information">
<label className="label-form-password-information">New Password</label>
<textarea onChange={(e) => setNewPass(e.target.value)} placeholder="New Password..." />
</div>
<div className="div-form-password-information">
<label className="label-form-password-information">Confirm Password</label>
<textarea onChange={(e) => setConfirmPass(e.target.value)} placeholder="Confirm Password..." />
</div>
<button onClick={(e) => updatePassword(e)} className="btn-update-pass">Update password</button>
</form>
</div>
);
}
export default Account;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Based on your post and comment, the issue seems to be that you are trying to access the value of the user state property before it is populated by the async axios call.
This is a common occurrence in React, and is quite simple to solve via conditional rendering.
Example:
{user === undefined
? <></>
: <textarea placeholder={user.map(el => {
return el.email
})} />
}
Or, instead of an empty fragment, you can put a loader/spinner or any other UI you'd like, in-order to let the user know that something is loading.
If you have more places where you try to access the value of user, you can use the conditional rendering there as-well.
Alternativaly, like Matias mentioned, you can put the condition before the "main" return of the component.
This is useful if you have multiple places where you need to access the value of user and you don't want to copy this logic for all of them.
Example:
if (user === undefined) {
return <></>
}
return (
...
)
maybe the state is not filled when the app is rendered. Try waiting for the axios request by adding a little loading system:
import axios from "axios";
import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from 'react-router-dom'
import './account.css'
function Account(props) {
const [user, setUser] = useState()
const [currentPass, setCurrentPass] = useState()
const [newPass, setNewPass] = useState()
const [confirmPass, setConfirmPass] = useState()
const [loading, setLoading] = useState(true) // add this
let navigate = useNavigate();
useEffect(() => {
let userArr = []
try {
axios.create({ withCredentials: true }).get(`http://127.0.0.1:3000/users/getMe`)
.then(res => {
console.log(res.data.data.user) //object
userArr.push(res.data.data.user)
console.log(userArr)
setUser(userArr)
console.log(user)
setLoading(false) // and this
})
} catch (error) {
console.log(error)
}
}, [])
const updatePassword = async (e) => {
e.preventDefault()
try {
const res = await axios.create({ withCredentials: true }).patch(`http://127.0.0.1:3000/users/updatePassword`, {
currentPassword: currentPass,
newPassword: newPass,
passwordConfirm: confirmPass
});
if (!res) {
return "not work"
}
console.log(res.data.data.user)
navigate("/", { replace: true });
} catch (error) {
console.log(error);
}
}
if(loading) return <p>loading</p> //and this...
return (
<div className="account-container" >
<div className="title-container">
<p className="title">My Account</p>
</div>
<p className="sub-title">User information </p>
<form className="form-user-information">
<div className="div-form-user-information">
<label className="label-form-user-information">Username</label>
<textarea placeholder="Username..." />
</div>
<div className="div-form-user-information">
<label className="label-form-user-information">ssss</label>
<textarea placeholder={user.map(el => {
return el.email
})} />
</div>
<div className="div-form-user-information">
<label className="label-form-user-information">First name</label>
<textarea placeholder="First name..." />
</div>
<div className="div-form-user-information">
<label className="label-form-user-information">Last name</label>
<textarea placeholder="Last name..." />
</div>
</form>
<div className="buttom-line"></div>
{/* //////CONTACT INFORMATION////////// */}
<p className="sub-title-contact">CONTACT INFORMATION </p>
<form className="form-contact-information">
<div className="div-form-contact-information">
<label className="label-form-contact-information">Full Address</label>
<textarea placeholder="Full Address..." />
</div>
<div className="div-form-contact-information">
<label className="label-form-contact-information">City</label>
<textarea placeholder="City..." />
</div>
<div className="div-form-contact-information">
<label className="label-form-contact-information">Country</label>
<textarea placeholder="Country..." />
</div>
<div className="div-form-contact-information">
<label className="label-form-contact-information">Postal code</label>
<textarea placeholder="Postal code..." />
</div>
</form>
<div className="buttom-line-contact"></div>
{/* //////PASSWORD INFORMATION////////// */}
<p className="sub-title-password">UPDATE PASSWORD </p>
<form className="form-password-information">
<div className="div-form-password-information">
<label className="label-form-password-information">Current Password</label>
<textarea onChange={(e) => setCurrentPass(e.target.value)} placeholder="Current Password..." />
</div>
<div className="div-form-password-information">
<label className="label-form-password-information">New Password</label>
<textarea onChange={(e) => setNewPass(e.target.value)} placeholder="New Password..." />
</div>
<div className="div-form-password-information">
<label className="label-form-password-information">Confirm Password</label>
<textarea onChange={(e) => setConfirmPass(e.target.value)} placeholder="Confirm Password..." />
</div>
<button onClick={(e) => updatePassword(e)} className="btn-update-pass">Update password</button>
</form>
</div>
);
}
export default Account;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Related
Hello guys so i tried to make global state so the other page can use the state. The problem is i got an error that says:
Login.js:18 Uncaught TypeError: Cannot destructure property 'emailLog' of '(0 , react__WEBPACK_IMPORTED_MODULE_0__.useContext)(...)' as it is undefined.
Im doing this because i want the email from user after logged in and pass them to another page so that i can display the logged in user.
App.js:
export const EmailUser = React.createContext();
function App() {
Axios.defaults.withCredentials = true;
const [invoice, setInvoice] = useState("");
const [currency, setCurrency] = useState("IDR");
const [myFile, setMyFile] = useState("");
const [emailLog, setEmailLog] = useState("");
return (
<EmailUser.Provider value={{ emailLog, setEmailLog }}>
<div className="App">
<BasicExample />
<div className="formInput">
<form method="POST" encType="multipart/form-data" action="http://localhost:3001/upload">
<div className="textUser"></div>
<input
className="inputForm"
defaultValue={emailLog}
type="email"
disabled
name="email"
/>
<input className="inputForm" type="number" placeholder="Invoice No" name="InvoiceNo" />
<input className="inputForm" type="date" name="Invoice_Date" />
<input className="inputForm" type="text" placeholder="Description" name="Description" />
<select
className="selectBox"
name="Currency"
onChange={(e) => {
setCurrency(e.target.value);
}}
>
<option value="IDR">IDR</option>
<option value="USD">USD</option>
<option value="YEN">YEN</option>
</select>
<input className="inputForm" type="number" placeholder="Amount" name="Amount" />
<input
className="custom-file-upload"
multiple
type="file"
name="DocumentFile"
onChange={(e) => {
setMyFile(e.target.value);
}}
/>
<button className="btnSubmit">Submit</button>
</form>
</div>
</div>
</EmailUser.Provider>
);
}
export default App;
Login.js
const Login = () => {
let navigate = useNavigate();
const { emailLog, setEmailLog } = useContext(EmailUser);
const [passwordLog, setPasswordLog] = useState("");
const [loginStatus, setLoginStatus] = useState("");
Axios.defaults.withCredentials = true;
const login = (e) => {
e.preventDefault();
Axios.post("http://localhost:3001/login", {
email: emailLog,
password: passwordLog,
}).then((response) => {
console.log(response);
if (response.data.message) {
alert(response.data.message);
} else {
setLoginStatus(response.data[0].email);
alert("Redirecting");
navigate("/home");
}
});
};
console.log(emailLog);
useEffect(() => {
Axios.get("http://localhost:3001/login").then((response) => {
if (response.data.loggedIn == true) {
setLoginStatus(response.data.email[0].email);
}
});
});
return (
<div>
<img className="wave" src={Wave} />
<img className="wave2" src={WaveV2} />
<div className="wrapper">
<div className="img">{/* <img src={Background}/> */}</div>
<div className="register-content">
<div className="registerForm">
<img src={Avatar} />
<h2 className="title">Welcome</h2>
<div className="input-div one">
<div className="i">
<i className="fas fa-user">
<GrMail />
</i>
</div>
<div className="div">
<input
type="email"
className="input"
placeholder="Email"
required
onChange={(e) => {
setEmailLog(e.target.value);
}}
/>
</div>
</div>
<div className="input-div pass">
<div className="i">
<i className="fas fa-lock">
<AiFillLock />
</i>
</div>
<div className="div">
<input
type="password"
className="input"
placeholder="Password"
required
onChange={(e) => {
setPasswordLog(e.target.value);
}}
/>
</div>
</div>
Don't have an account ?
<button type="submit" className="btn" onClick={login}>
Login
</button>
</div>
</div>
</div>
</div>
);
};
export default Login;
EmailUser context works only with the components that are children of EmailUser.Provider, and it doesn't seem to be the case for Login component. An easy way is to create a separate component, in some EmailUserProvider.js, like so:
import {createContext, useState} from "react"
export const EmailUser = createContext();
export default function EmailUserProvider({children}) {
const [emailLog, setEmailLog] = useState("");
return (
<EmailUser.Provider value={{ emailLog, setEmailLog }}>
{children}
</EmailUser.Provider>
);
}
And make it wrap all the components that would consume it. If I assume all my components and routes are rendered in App and want the context to be global, I would do so:
<EmailUserProvider>
<App/>
</EmailUserProvider>
staffForm.js
import React from 'react'
import { Link } from 'react-router-dom';
const StaffForm = ({handleSubmit},props) => {
// console.log(props);
const title = props.title;
const link =props.link;
return (
<section>
<div class="Employewrapper">
<div class="title">
{title} registration
</div>
<form class="form" onSubmit={handleSubmit} encType='multipart/form-data'>
<div class="inputfield">
<label>First Name</label>
<input required type="text" class="input" name='first_name'/>
</div>
<div class="inputfield">
<label>Last Name</label>
<input required type="text" class="input" name='last_name'/>
</div>
<div class="inputfield">
<label>Email</label>
<input required type="email" class="input" name='email'/>
</div>
<div class="inputfield">
<label>Password</label>
<input required type="password" class="input" name='password'/>
</div>
<div class="inputfield">
<label>Confirm password</label>
<input required type="password" class="input" name='confirm_password'/>
</div>
<div class="inputfield">
<label>Phone</label>
<input required type="tel" class="input" name='phone'/>
</div>
<div class="inputfield">
<label for="file">Profile Picture</label>
<input required type="file" id="file" accept="image/*" class="input" name='profile_picture'/>
</div>
<div class="inputfield">
<label>Birthdate</label>
<input required type="date" class="input" name='birthdate'/>
</div>
<div class="inputfield">
<label for="file">Id Card</label>
<input required type="file" id="file" accept="image/*" class="input" name='identification_card'/>
</div>
<div class="inputfield">
<input required type="submit" class="btn" />
</div>
<Link to={link} className='btn'>Back {title}</Link>
</form>
</div>
</section>
)
}
export default StaffForm;
DeliveryForm.js
import React from 'react'
import { Link } from 'react-router-dom';
import axios from 'axios';
import StaffForm from '../../Components/StaffForm';
import "../../Assets/styles/button.css"
const DeliveryForm = () => {
const url = 'http://127.0.0.1:8000/staff/delivery/';
const handleSubmit = (event)=>{
event.preventDefault();
const data = {
"user": {
"first_name": event.target.first_name.value,
"last_name": event.target.last_name.value,
"email": event.target.email.value,
"password": event.target.password.value,
"confirm_password": event.target.confirm_password.value,
"phone": event.target.phone.value
},
"profile_picture": event.target.profile_picture.files[0],
"birthdate": event.target.birthdate.value,
"identification_card": event.target.identification_card.files[0]
}
axios.request({
method: 'post',
headers: {
"Content-Type": "multipart/form-data",
},
url,
data
}).then(res => {
console.log(res)
})
}
return (
<>
<StaffForm handleSubmit={handleSubmit} title="Delivery" link="/Delivery"/>
</>
)
}
export default DeliveryForm
i have a particular form which i will be using for 3 api's the only difference are the title an the link i know the conventional way of writing props but it seems it not working in this case. on my page its not rendering anything but when i remove the props it works. i tried swithing the position of the props and the {handleSubmit}, when doing that i can see the prop but i can't post.
Just do it as you did with previous things in props.
const StaffForm = (props) => {
const handleSubmit = props.handleSubmit;
const title = props.title;
const link = props.link;
Or you will need to deconstruct everything in one place.
const StaffForm = ({ handleSubmit, title, link }) => {
Why: because props object is the first parameter, always. In my example you deconstruct it, and in your code - you deconstruct only handleSubmit from it and somewhy you were expecting to get a second parameter which you named props. No, only one and only first parameter is your props object.
Additionaly, you can use
const StaffForm = (props) => {
const { handleSubmit, title, link } = props;
or
// Spread operator
const StaffForm = ({handleSubmit, ...props}) => {
const { title, link } = props;
I have a login component where the user can log in with email and password. In the database, the user have following properties.
1.userID
2.Email
3.Password
I want to get the userid back from the API according to the user login. Cansome genius help me with this?
my login component:
export default class Login extends Component {
state = {};
submitHandler = e => {
e.preventDefault()
const logingdata ={
email : this .Email,
password: this .Password
}
axios
.post('/api/UserLogin', logingdata)
.then(response => {
console.log(response); //to print response in console in developper tool
//const currentuser = JSON.parse(atob(response.data.token.split(".")[1]));
localStorage.setItem('login', response.data.token);
console.log(this.email);
})
.catch(error => {
console.log(error => console.log(error.response.data))
})
}
render() {
return (
<div className="outer">
<div className="inner">
<form onSubmit={ this.submitHandler}>
<h3>Log in</h3>
<div className="form-group">
<label>Email</label>
<input type="text" className="form-control" placeholder="Enter email" onChange ={ e => this.Email = e.target.value} />
</div>
<div className="form-group">
<label>Password</label>
<input type="text" className="form-control" placeholder="Enter password" onChange ={ e => this.Password = e.target.value} />
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
<input type="checkbox" className="custom-control-input" id="customCheck1" />
<label className="custom-control-label" htmlFor="customCheck1">Remember me</label>
</div>
</div>
<br></br>
<button type="submit" className="btn btn-dark btn-lg btn-block">Sign in</button>
<p className="forgot-password text-right">
Forgot <Link to= "/Forgotpassword" >password?</Link>
</p>
</form>
</div>
</div>
);
}
}
EDIT:
console response hen login: (it shows only username and password)
I am sending a form data from a form in reactjs. Some pre inputs from the user have to be sent altogether with the form. I get that data from the URL of the parent file and the form is in the child component.
Parent url:
http://localhost:3000/uploadlist?phmcy=2
I have to get the phmcy value from the URL. (Here the data have to be passed is '2').
parent component:
import Upload froimportm './Upload'
import axios from "axios";
import { Link, withRouter } from "react-router-dom";
import { useLocation } from 'react-router';
export default function Uploadlist() {
let phmcy = (new URLSearchParams(window.location.search)).get("phmcy")
var myphmcy = JSON.stringify(phmcy);
//const phmcyvalue = new URLSearchParams(this.props.location.search);
//const phmcy = phmcyvalue.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
addOrEdit = {addOrEdit}
myphmcy = {myphmcy}
/>
</div>
<div className="col-md-1">
<div> </div>
</div>
</div>
)
}
Child component: (This is where the form is. I have only included a part)
import React, {useState, useEffect} from 'react';
import myphmcy from './Uploadlist';
//const myphmcy = JSON.stringify(phmcy);
console.log(myphmcy);
const defaultImageSrc = '/images/7.jpg';
const initialFieldValues ={
orderId:0,
dateTime:'',
status:'',
status2:'',
pharmacyName:'',
customerName:'',
patientName:'',
patientAge:'',
address:'',
email:'',
teleNo:'',
customerId:1,
pharmacyId:myphmcy,//data obtaind from the URL have to posted as the pharmacyID when posting.
imageName:'',
imageSrc:'',
imageFile: null
}
export default function Upload(props) {
const {addOrEdit} = props
const {myphmcy} = props
const [values, setValues] = useState(initialFieldValues)
const[errors, setErrors] = useState({})
const handleInputChange= e => {
const {name, value} = e.target;
setValues({
...values,
[name]:value
})
}
const showPreview = e => {
if(e.target.files && e.target.files[0]){
let imageFile = e.target.files[0];
const reader = new FileReader();
reader.onload = x => {
setValues({
...values,
imageFile,
imageSrc : x.target.result
})
}
reader.readAsDataURL(imageFile)
}
else{
setValues({
...values,
imageFile:null,
imageSrc:''
})
}
}
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('dateTime',values.dateTime)
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('customerId',values.customerId)
formData.append('pharmacyId',values.pharmacyId)
formData.append('imageName',values.imageName)
formData.append('imageFile',values.imageFile)
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.imageSrc} 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="dateTime" value={values.dateTime}
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>
</>
)
}
This doesn't work well and I can't post the data. Can some genius help me with this?
Issue
For some reason you import the Uploadlist (the default export/import) and name it myphmcy, save this in the initial state, and then never consume the passed myphmcy prop. This pattern tends to lead to stale state as you need to also handle when the prop values update so you can synchronize the state value.
Solution
Storing passed props is anti-pattern in React, just consume the myphmcy prop directly in the handleFormSubmit submit handler. This ensure you are always using the latest myphmcy props value when submitting the form data.
const handleFormSubmit = e => {
e.preventDefault();
if (validate()) {
const formData = new FormData();
formData.append('orderId', values.orderId);
formData.append('dateTime', values.dateTime);
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('customerId', values.customerId);
formData.append('pharmacyId', myphmcy) // <-- use the prop directly
formData.append('imageName', values.imageName);
formData.append('imageFile', values.imageFile);
addOrEdit(formData, resetForm) ;
alert("Your file is being uploaded!");
};
You are getting the myphmcy value from props but setting it outside of the function. So it will set only undefined to the pharmacyId. You need to assign the myphmcy value inside the fnuction.
I am facing this when I am trying to set form error object. Basically, I want to show the errors below each input field. In response, I am getting an array of objects how do I set to my error object?
Error - Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
import axios from "axios";
import React, { useState, useEffect, useCallback } from "react";
import { Link } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { register } from "../actions/userActions";
const Register = () => {
const [countriesList, setCountriesList] = useState("");
const [userRegistration, setUserRegistration] = useState({
firstName: "",
lastName: "",
email: "",
password: "",
fullAddress: "",
city: "",
zipCode: "",
country: "",
phone: "",
terms: true,
});
const [userRegistrationError, setUserRegistrationError] = useState({
firstNameError: "",
lastNameError: "",
emailError: "",
passwordError: "",
fullAddressError: "",
cityError: "",
zipCodeError: "",
countryError: "",
phoneError: "",
termsError: "",
});
const dispatch = useDispatch();
const userRegister = useSelector((state) => state.userRegister);
const { loading, errors, success } = userRegister;
useEffect(() => {
const countries = async () => {
try {
const { data } = await axios.get(
`https://restcountries.eu/rest/v2/all`
);
setCountriesList(data);
} catch (err) {
console.error(err);
}
};
countries();
}, []);
useEffect(() => {
const handleErrors = (errors) => {
errors.map((error) => {
if (error.param === "firstname") {
setUserRegistrationError({
...userRegistrationError,
firstNameError: error.msg,
});
}
if (error.param === "email") {
setUserRegistrationError({
...userRegistrationError,
emailError: error.msg,
});
}
return null;
});
};
if (errors) {
handleErrors(errors);
}
}, [errors, setUserRegistrationError]);
const handleChange = (e) => {
const name = e.target.name;
const value = e.target.value;
setUserRegistration({ ...userRegistration, [name]: value });
};
const handleChkChange = (e) => {
const checked = e.target.checked;
console.log(checked);
setUserRegistration({ ...userRegistration, terms: checked });
};
const handleSubmit = (e) => {
e.preventDefault();
try {
dispatch(register());
} catch (error) {
console.error(error);
}
};
return (
<div className="form_container">
<form action="" onSubmit={handleSubmit}>
<div className="row no-gutters">
<div className="col-6 pr-1">
<div className="form-group">
<div className="form-group">
<input
type="text"
name="firstName"
className="form-control"
placeholder="First Name*"
value={userRegistration.firstName}
onChange={handleChange}
/>
<p className="form-vald-error">
{userRegistrationError.firstNameError &&
userRegistrationError.firstNameError}
</p>
</div>
</div>
</div>
<div className="col-6 pr-1">
<div className="form-group">
<input
type="text"
className="form-control"
name="lastName"
placeholder="Last Name*"
value={userRegistration.lastName}
onChange={handleChange}
/>
<p className="form-vald-error">
{userRegistrationError.lastNameError &&
userRegistrationError.lastNameError}
</p>
</div>
</div>
</div>
<hr />
<div className="private box">
<div className="row no-gutters">
<div className="col-6 pr-1">
<div className="form-group">
<input
type="email"
className="form-control"
name="email"
id="email_2"
placeholder="Email*"
value={userRegistration.email}
onChange={handleChange}
/>
<p className="form-vald-error">
{userRegistrationError.emailError &&
userRegistrationError.emailError}
</p>
</div>
</div>
<div className="col-6 pl-1">
<div className="form-group">
<input
type="password"
className="form-control"
name="password"
id="password_in_2"
placeholder="Password*"
value={userRegistration.password}
onChange={handleChange}
/>
<p className="form-vald-error">
{userRegistrationError.passwordError &&
userRegistrationError.passwordError}
</p>
</div>
</div>
<div className="col-12">
<div className="form-group">
<input
type="text"
name="fullAddress"
className="form-control"
placeholder="Full Address*"
value={userRegistration.fullAddress}
onChange={handleChange}
/>
<p className="form-vald-error">
{userRegistrationError.fullAddressError &&
userRegistrationError.fullAddressError}
</p>
</div>
</div>
</div>
{/* /row */}
<div className="row no-gutters">
<div className="col-6 pr-1">
<div className="form-group">
<input
type="text"
className="form-control"
placeholder="City*"
name="city"
value={userRegistration.city}
onChange={handleChange}
/>
<p className="form-vald-error">
{userRegistrationError.cityError &&
userRegistrationError.cityError}
</p>
</div>
</div>
<div className="col-6 pl-1">
<div className="form-group">
<input
type="text"
className="form-control"
placeholder="Postal Code*"
name="zipCode"
value={userRegistration.zipCode}
onChange={handleChange}
/>
<p className="form-vald-error">
{userRegistrationError.zipCodeError &&
userRegistrationError.zipCodeError}
</p>
</div>
</div>
</div>
{/* /row */}
<div className="row no-gutters">
<div className="col-6 pr-1">
<div className="form-group">
<div className="custom-select-form">
<select
className="wide add_bottom_10 form-control"
name="country"
id="country"
value={userRegistration.country}
onChange={handleChange}
>
<option>Country*</option>
{countriesList &&
countriesList.map((country) => (
<option
key={country.alpha2Code}
value={country.alpha2Code}
>
{country.name}
</option>
))}
</select>
<p className="form-vald-error">
{userRegistrationError.countryError &&
userRegistrationError.countryError}
</p>
</div>
</div>
</div>
<div className="col-6 pl-1">
<div className="form-group">
<input
type="text"
className="form-control"
placeholder="Telephone *"
name="phone"
value={userRegistration.phone}
onChange={handleChange}
/>
<p className="form-vald-error">
{userRegistrationError.phoneError &&
userRegistrationError.phoneError}
</p>
</div>
</div>
</div>
{/* /row */}
</div>
<hr />
<div className="form-group">
<label className="container_check">
Accept <Link to="#0">Terms and conditions</Link>
<input
type="checkbox"
name="terms"
checked={userRegistration.terms}
onChange={handleChkChange}
/>
<span className="checkmark" />
<p className="form-vald-error">
{userRegistrationError.termsError &&
userRegistrationError.termsError}
</p>
</label>
</div>
<div className="text-center">
<input
type="submit"
defaultValue="Register"
className="btn_1 full-width"
/>
</div>
</form>
</div>
);
};
export default Register;
your effect depends on userRegistrationError which is an object, reference based. Each time useEffect runs,setUserRegistrationError
creates a new object reference, which leads to an infinite loop since references won't be the same as the previous one.
One approach to avoid this issue and keep the right references, is to pass a callback function to setUserRegistrationError instead than a value. This way userRegistrationError is no longer a dependency, it will be an argument to your function instead:
useEffect(() => {
const handleErrors = (errors) => {
errors.forEach((error) => {
if (error.param === "firstName") {
// here you pass a callback function instead, and userRegistrationError is no longer a dependency
// and returns the next state as expected
setUserRegistrationError(userRegistrationError => ({
...userRegistrationError,
firstNameError: error.msg,
}));
}
if (error.param === "email") {
setUserRegistrationError(userRegistrationError => ({
...userRegistrationError,
emailError: error.msg,
}));
}
});
};
if (errors) {
handleErrors(errors);
}
}, [errors, setUserRegistrationError]);
You have a problem with the second useEffect, the first time you update your state userRegistrationError, the component re-rendered and re-executed the useeffect because the dependency userRegistrationError has changed and the process gets repeated again because the state gets updated every render.
useEffect(() => {
const handleErrors = (errors) => {
errors.map((error) => {
if (error.param === "firstname") {
setUserRegistrationError({
...userRegistrationError,
firstNameError: error.msg,
});
}
if (error.param === "email") {
setUserRegistrationError({
...userRegistrationError,
emailError: error.msg,
});
}
return null;
});
};
if (errors) {
handleErrors(errors);
}
}, [errors, setUserRegistrationError ]); //replace userRegistrationError by setUserRegistrationError