How to load initial value in formik form ?
Loading initial value is a very important , Suppose you have a huge form and you want user to visit the form multiple time to update few more details , in that case you want to fetch the previous data form API and pre populate that data to the form .
To achieve that to have to follow 2 steps.
Step 1 :
Get the data form API and store it in the state using useState or you can use reducer or redux store , it is completely up to you
For example i have used useState and hardcoded the initial value
const [iniValue , setiniValue] = useState(
{
name:'code learning point'
}
)
Step 2 :
In the Formik component add this
initialValues={iniValue || initialValues}
if you have iniValue which will come from the API else load the initialValues,enableReinitialize
property which enables the reinitialisation feature to your formik form automatically. <Formik
initialValues={iniValue || initialValues}
validate={validation}
onSubmit={onSubmit}
enableReinitialize
>
Complete Code :
import { Form, Formik, Field, ErrorMessage, FieldArray } from 'formik';
import { useState } from 'react';
const Index = () => {
const [iniValue , setiniValue] = useState(
{
name:'code learning point'
}
)
const validation = (values) => {
let error = {};
if (!values.name) {
error.name = 'Name is required';
}
return error;
}
let initialValues = {
name: '',
};
const onSubmit = (values, props) => {
console.log('--values--', values);
props.isSubmitting(false)
}
return (
<Formik
initialValues={iniValue || initialValues}
validate={validation}
onSubmit={onSubmit}
enableReinitialize
>
{
(formik) => {
return(
<Form>
<Field name="name" />
<ErrorMessage name='name' />
<button type='submit' disabled={!formik.isValid || formik.isSubmitting} >Submit</button>
</Form>
)
}
}
</Formik>
)
}
export default Index;