'Keep the Form values after refreshing the page [duplicate]
I have created a basic form validation page using ReactJS with input fields of validation using regex.
I have a problem that when I fill the input fields with some data and before completing it if I click refresh the page the input fields are getting cleared.
I want to stop the input fields from clearing after refresh.
How can I do that.
Below is my code:
import React, { useState, useEffect } from 'react';
import PhoneIcon from '@mui/icons-material/Phone';
import LockIcon from '@mui/icons-material/Lock';
import { NavLink, useNavigate } from 'react-router-dom';
import "../index.css";
function Github () {
const initialvalues = {number:"", password:""}
const [formValues, setFormValues] = useState(initialvalues);
const [formErrors, setFormErrors] = useState({});
const [isSubmit, setIsSubmit] = useState(false);
const handleChange = (e) =>{
const{name,value} = e.target;
setFormValues({...formValues, [name]:value});
}
const handleSubmit = (e) =>{
e.preventDefault();
const errors = validate(formValues);
if (Object.keys(errors).length) {
setFormErrors(errors);
} else {
setIsSubmit(true);
}
}
let navigate = useNavigate();
const handleSubmits = (e) =>{
e.preventDefault();
const passerrors = validates(formValues);
if (Object.keys(passerrors).length) {
setFormErrors(passerrors);
} else {
navigate('/admin');
}
}
useEffect(()=>{
console.log(formErrors);
if(Object.keys(formErrors).length ===0 && !isSubmit){
console.log(formValues);
}
},[formErrors])
const validates = (values) =>{
const passerrors ={}
const regexp = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*_=+-]).{4,12}$/;
if(!values.password){
passerrors.password = "Password is required";
}else if(!regexp.test(values.password)){
passerrors.password = "passsword must contain atleast one uppercase,lowercase,number,special character";
}
else if(values.password.length < 4){
passerrors.password = "Password must me more than 4 characters";
}else if (values.password.length > 6){
passerrors.password = "Password cannot be more than 6 characters";
}
return passerrors;
}
const validate = (values) =>{
const errors = {}
const regexn = /^(\+91[-\s]?)?[0]?(91)?[789]\d{9}$/;
if(!values.number){
errors.number = "Mobile Number is required";
}else if(!regexn.test(values.number)){
errors.number = "Please enter a valid mobile number"
}else if(values.number.length > 10){
errors.number = "number must be only 10 digits"
}
return errors;
};
return (
<div className="container"
style={{textAlign:'center',paddingTop:"50px"}}>
<img src="images/img1.jpg" alt=''
width="100px" height="100px"
style={{borderRadius:"50%"}} /><br/>
<div style={{justifyContent:'space-between'}}>
<br/><br/><br/><br/>
{ !isSubmit
?
<form onSubmit={handleSubmit} >
<div>
<div>
<label style={{position:"relative", top:"8px",right:"5px",left:"115px"}}>
<PhoneIcon/></label>
<input className='input_field' type="number" name="number" placeholder='enter number'
autoComplete='off'
value={formValues.number}
onChange={handleChange}
style={{width:"180px",height:"35px"}}
/>
<label className='input_label'>Mobile Number</label>
<p style={{color:"red",fontSize:"13px"}} >{formErrors.number}</p>
</div>
<button className='btn-primary'
style={{width:"210px",height:"30px",fontSize:"15px",
marginLeft:"30px",marginTop:"20px",
backgroundColor:" rgb(0, 110, 255)"
}}>
Submit</button>
</div>
</form>
:
<form onSubmit={handleSubmits} >
<div>
<div>
<label style={{position:"relative", top:"8px",right:"5px",left:"80px"}} ><LockIcon/></label>
<input className='input_fieldp' type="password" name='password' placeholder='enter password'
value={formValues.password}
onChange={handleChange}
style={{width:"180px",height:"35px"}}
/>
<label className='input_labelp'>Password</label>
<p style={{color:"red",fontSize:"13px"}}>{formErrors.password}</p>
</div>
<button
style={{width:"210px",height:"30px",fontSize:"15px",
marginLeft:"30px",marginTop:"20px",
backgroundColor:" rgb(0, 110, 255)"
}}>
Login</button>
</div>
</form>
}
</div>
</div>
)
}
export default Github;
Suggest me how can I do that.
Solution 1:[1]
When you refresh you cannot use react state or redux store as they are cleared and initialized with each page refresh. The best approach I see here is to use your localstorage to store the values.
Then you can check whether the data is available in localstorage and use that on the initial render using a useEffect hook.
Solution 2:[2]
What you can do is use localstorage. You can use the native localstorage but i do recommend using lscache as it is more flexible (also handles if the browser doesn't have lscace) and since you're using a framework anyway.
what you can do is on your handleCange everytime you save something on state, you also save it on localstorage:
const handleChange = (e) =>{
const{name,value} = e.target;
setFormValues({...formValues, [name]:value});
// you can add a third parameter for expiration if you don't want it to be there forever
lscache.set(name, value);
}
then have a useEffect to handle the fetching of data on the cache on refresh
useEffect(() => {
const number = lscache.get("number");
setFormValues({...formValues, number});
}, [])
PS. Make sure the name of the cache is unique on the form/site.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | smooth-felix |
| Solution 2 | I am L |
