I have the following Formik initial values setup:
const INITIAL_VALUES = {
taskName: 'Test',
taskNotes: 'Some notes',
areaGroups: [
{
name: Area Group 1,
areaInfo: [
{
areaName: "Area 1",
areaCode: null
}
]
}
]
};
What I am then doing is providing the user the option of loading a CSV file in order to avoid the user from entering further areaInfo
data via the frontend form.
The following code seems to add the loaded CSV values to the areaInfo
array, which I can see from a console.log(values)
but doesn't actually update/refresh the INITIAL_VALUES above or form.
The thing is though, when I click into the areaName
form field within the areaInfo
array, it then refreshes and displays my loaded CVS data but doesn't display it after I select the csv file to load/parse?
My component code for this is as follows and is using react-dropzone
and papaparse
npm packages:
const PerformUpload = ({ values }) => {
const formikProps = useFormikContext()
const classes = useStyles();
const onDrop = useCallback(acceptedFiles => {
acceptedFiles
.filter((file) => file.type === "text/csv")
.forEach(async (file) => {
const text = await file.text();
const result = parse(text, { header: true });
const myData = result.data
myData.map((data) => (
values.areaGroups[0].areaInfo.push(
{
"areaName": data.areaname,
"areaCode": data.areacode
}
)
))
});
}, []);
const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });
return (
<React.Fragment>
<section className="container">
<div {...getRootProps({className: 'dropZone'})}>
<input {...getInputProps()} />
<p>Drag files here or click to select a file</p>
</div>
</section>
</React.Fragment>
)
}
I am performing the push to the values.areaGroups[0].areaInfo
array but not sure if this correct as it doesn't refresh the frontend/initial values until I physically click on the field.
FYI, this PerformUpload
component is being called from within:
<Formik
enableReinitialize={true}
initialValues={INITIAL_VALUES}
....
Not sure what I am missing/doing wrong?
I managed to solve my issue by using Formik's setFieldValue
prior to pushing the data into my initial values.