I am using Formik for react form with material UI.
I have two fields and I need to do the calculation on that two fields as value change, so I must get the value of those two fields,
const formik = useFormik({
initialValues: {
quantity: '',
price: '',
total: '',
},
validationSchema: Yup.object({
quantity: Yup.string().max(5).required('Quantity is required'),
price: Yup.string().max(5).required('Price is required'),
}),
onSubmit: values => {
},
})
And here is form
<form onSubmit={formik.handleSubmit}>
<TextField
type="number"
size="small"
error={Boolean(
formik.touched.quantity && formik.errors.quantity,
)}
helperText={
formik.touched.quantity && formik.errors.quantity
}
label="Quantity"
margin="normal"
name="quantity"
onBlur={formik.handleBlur}
onChange={formik.handleChange}
value={formik.values.quantity}
variant="outlined"
/>
<TextField
size="small"
error={Boolean(formik.touched.price && formik.errors.price)}
helperText={formik.touched.price && formik.errors.price}
label="Last Name"
margin="normal"
name="price"
onBlur={formik.handleBlur}
onChange={formik.handleChange}
value={formik.values.price}
variant="outlined"
/>
{Boolean(
formik.touched.tax_status && formik.errors.tax_status,
) && (
<FormHelperText error>
{formik.errors.tax_status}
</FormHelperText>
)}
<Box sx={{ py: 2 }}>
<Button
color="primary"
disabled={formik.isSubmitting}
fullWidth
size="large"
type="submit"
variant="contained">
Submit
</Button>
</Box>
</form>
How to retrieve values of quantity and price on every change?
>Solution :
I haven’t use formik so not sure, maybe you can put an useEffect on your formik.values and then do whatever you want with it.
Something like
useEffect(()=>{
//do your stuff
},[formik.vaues])