Form data filled does not show on console using react hooks - reactjs

I have a form built with formik and yup, but after filling the form, the data did not show on the console and when i clicked the next button, it does not take to the next page.
The validations are working.
.
.
.
const navigate = useNavigate()
const initialValues = {
phone: "",
email: ""
}
const validationSchema = Yup.object({
phone: Yup.string().required('Required'),
email: Yup.string().required('Required').email('Invalid email format'),
})
const onSubmit = values => {
console.log('Form data', values)
navigate("/NextPage")
}
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={onSubmit}>
<Form>
<div className="mb-3">
<label className='form-label'>Phone Number</label><br/>
<Field type='tel' name='phone' className='place-holder white-bg' id='phone'/>
<ErrorMessage name='phone'>
{ (errorMsg) => <div className='error'>{errorMsg}</div> }
</ErrorMessage>
</div>
<div className="mb-3">
<label className='form-label'>Email address(optional)</label><br/>
<Field type='email' name='email' className='place-holder white-bg' id='email'/>
<ErrorMessage name='email'>
{ (errorMsg) => <div className='error'>{errorMsg}</div> }
</ErrorMessage>
</div>
<Button variant="primary" type="submit" className="buy-token-next-btn">
Next
</Button>
</Form>
</Formik>

Related

useDispatch stops render of the page

I'm using React, redux with typescript to build a frontend page. In one of the page, I want to register a user. I utilized useDispatch() and the page stops rendering. If I comment out the useDispatch() line, the page will render normally.
I can't find anything online regarding this.
const Register: FC<any> = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
password2: '',
})
// If I comment out this line, the page will render normally
const dispatch = useDispatch<any>()
const { name, email, password, password2 } = formData
const onSubmit = (e: any) => {
e.preventDefault()
if (password !== password2) {
toast.error('Passwords do not match')
} else {
const userData = {
name,
email,
password,
}
dispatch(register(userData))
}
}
const onChange = (e: any) => {
setFormData((prevState) => ({
...prevState,
[e.target.name]: e.target.value,
}))
}
return (
<>
<section className='heading'>
<h1>
<SlUserFollowing /> Register
</h1>
<p>Please create an account</p >
</section>
<section className='form'>
<form onSubmit={onSubmit}>
<div className='form-group'>
<input
type='text'
className='form-control'
id='name'
name='name'
value={name}
onChange={onChange}
placeholder='Enter your name'
required
/>
</div>
<div className='form-group'>
<input
type='email'
className='form-control'
id='email'
name='email'
value={email}
onChange={onChange}
placeholder='Enter your email'
required
/>
</div>
<div className='form-group'>
<input
type='password'
className='form-control'
id='password'
name='password'
value={password}
onChange={onChange}
placeholder='Enter password'
required
/>
</div>
<div className='form-group'>
<input
type='password'
className='form-control'
id='password2'
name='password2'
value={password2}
onChange={onChange}
placeholder='Confirm password'
required
/>
</div>
<div className='form-group'>
<button className='btn btn-block'>Submit</button>
</div>
</form>
</section>
</>
);
};
export default Register;
I searched online and didn't find any source regarding this.

How to set the formik field value with the useState hook?

I have a simple form which has only two fields,name and wallet_address, I want the user's to type wallet_address or simply scan the address, once the scan is successful the address will be stored in the state variable, I want to update the wallet_address field with the new state value. Currently this is not working, only manually typing the address is working but not the scanning feature.
import { ErrorMessage, Field, Form, Formik } from "formik";
import ScanQrPopUp from "../components/wallet/popup/ScanQrPopup";
const [walletAddress, setWalletAddress] = useState<any>("");
const handleScanAddress = (wallet: string) => {
console.log("wallet address---", wallet);
setWalletAddress(wallet);
};
const validationSchema = Yup.object().shape({
name: Yup.string()
.min(3, "Name should be atleast 3 characters")
.required("Name is required"),
wallet_address: Yup.string()
.required("Wallet Address is required")
});
<Formik
initialValues={{
name: "",
wallet_address: "",
}}
onSubmit={async (values, { resetForm }) => {
setIsLoading(true);
console.log(values.name);
console.log(values.wallet_address);
setIsLoading(false);
resetForm();
}}
validationSchema={validationSchema}
validateOnChange
>
{({ values, resetForm }) => (
<Form>
<div className="w-[80%]">
<label
className="text-left"
htmlFor="input"
>
Name
</label>
<Field
name="name"
type="text"
spellCheck={false}
className="block"
placeholder="Enter the Name"
/>
<p className="text-red-600">
<ErrorMessage name="name" />
</p>
</div>
<div className="w-[80%] mt-4">
<label
className="text-left"
htmlFor="wallet_address"
>
wallet address
</label>
<Field
name="wallet_address"
type="text"
spellCheck={false}
className="block "
placeholder="Enter wallet address"
/>
<p className="text-red-600 ">
<ErrorMessage name="wallet_address" />
</p>
</div>
</Form>
)}
</Formik>
<ScanQrPopUp
handlePopUp={handleQrPopup}
walletAddress={handleScanAddress}
/>

How to create editable form inputs with existing prefill data in React

I have some data and form inputs, I need to prefill the existing data in the fields and when click on edit I like to edit the data and submit it to the state on button click
const data = {
name: "nazar",
email: "nazar#gmail.com",
phone: 123456789
};
const [ editData, setEditData ] = useState()
function handleEdit(){
}
function handleSubmit(){
}
<form onChange={handleEdit}>
<input type="text" name='name'/><button>Edit</button><br/>
<input type="text" name='email'/><button>Edit</button><br/>
<input type="text" name='phone'/><button>Edit</button><br/>
<button type='submit' onSubmit={handleSubmit}>Submit</button>
</form>
// declare your data as initial state
const [data, setData] = React.useState({
name: 'nazar',
email: 'nazar#gmail.com',
phone: 123456789,
});
// handle on change according to input name and setState
const handleChange = (e) => {
setData({ ...data, [e.target.name]: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault()
// take data to submit
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
name="name"
value={data.name} // inject state correspond to input and so on
onChange={handleChange}
/>
<button>Edit</button>
<br />
<input
type="text"
name="email"
value={data.email}
onChange={handleChange}
/>
<button>Edit</button>
<br />
<input
type="text"
name="phone"
value={data.phone}
onChange={handleChange}
/>
<button>Edit</button>
<br />
<button type="submit">
Submit
</button>
</form>
</div>
);

Formik ErrorMessage not appearing on browser

In this simple form, I take description and category(select) from user inputs.
I try to display error by rendering prior, and it worked completely fine.
When I reafactored, using ErrorMessage from formik, it stopped showing error message on the browser.
I read the coumentation, and there seems no issue regarding my code below.
Any suggestion or something I didn't notice?
const initialValues = {
description: '',
category: '',
};
const validationSchema = Yup.object({
description: Yup.string().required('Required'),
category: Yup.string().required('Required'),
});
const onSubmit = (values) => {
console.log('Form data', values);
};
const AddForm = () => {
return (
<Formik
initialValues={initialValues}
ValidationSchema={validationSchema}
onSubmit={onSubmit}
>
<Form className='container'>
<div className='form-control'>
<label htmlFor='description'></label>
<Field
type='text'
id='description'
name='description'
placeholder='Enter Description...'
/>
<ErrorMessage name='description' />
</div>
<div className='form-control'>
<label htmlFor='category'></label>
<Field name='category' as='select'>
<option value='' label='Select Category' />
<option value='home' label='Home' />
<option value='work' label='Work' />
<option value='entertainment' label='Entertainment' />
</Field>
<ErrorMessage name='category' />
</div>
<button type='submit'>Submit</button>
</Form>
</Formik>
);
};
Its happening because you mistyped validationSchema to ValidationSchema i.e
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={onSubmit}
>
Here is demo working fine: https://codesandbox.io/s/spring-field-ieip1?file=/src/App.js

onchange in a form using formik the value of the field is not updated

I'm new to react, and I'm trying to apply validations to a form.
For some reason when adding the property:
onChange={onChange}
I want to send the values to the parent component. That's why I'm using the onchange.
Nothing I write is shown in my text fields, why does this happen?
export const Son = props => {
const { onChange } = props;
return (
<Formik
initialValues={{
fullname: "",
email: ""
}}
validationSchema={Yup.object().shape({
fullname: Yup.string()
.min(2, "Your name is too short")
.required("Please enter your full name"),
email: Yup.string()
.email("The email is incorrect")
.required("Please enter your email")
})}
onSubmit={(values, { setSubmitting }) => {
const timeOut = setTimeout(() => {
console.log(values);
setSubmitting(false);
clearTimeout(timeOut);
}, 1000);
}}
>
{({
values,
errors,
touched,
handleSubmit,
isSubmitting,
validating,
valid
}) => {
return (
<Form name="contact" method="post" onSubmit={handleSubmit}>
<label htmlFor="fullname">
Fullname
<Field
type="text"
name="fullname"
autoComplete="name"
placeholder="your fullname"
onChange={onChange}
/>
</label>
{<ErrorMessage name="fullname">{msg => <p>{msg}</p>}</ErrorMessage>}
{/*errors.fullname && touched.fullname && <p>{errors.fullname}</p>*/}
<br />
<label htmlFor="email">
Email
<Field
type="email"
name="email"
autoComplete="email"
placeholder="your email"
onChange={onChange}
/>
</label>
<ErrorMessage name="email">{msg => <p>{msg}</p>}</ErrorMessage>
<br />
<button type="submit" disabled={!valid || isSubmitting}>
{isSubmitting ? `Submiting...` : `Submit`}
</button>
</Form>
);
}}
</Formik>
);
};
this is my live code:
https://stackblitz.com/edit/react-qotvwb?file=components/son_component.js
you're not using the formik handleChange at all.
I highlighted the changes that I made in https://stackblitz.com/
and you can test this working here

Resources