Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REACT - Set initial data in Formik Form after fetching from API

Tags:

reactjs

formik

I'm trying to do an edit page for a project I am working on, I can't seem to make the form get filled out with initial values coming from my API. I was hoping that after I fetched the data from my REST API, it would be set as the initialValues for my Form fields, however, it does not look like this is happening. Anything I could to to achieve my goal of pre-populating my form fields based on values I get from my API?

Here's my code:

const EditBookInfoForm= (properties) => {
    const [data, setData] = useState();

    useEffect(() => {
        fetch(apiUrl + properties.bookId)
        .then(response => response.json())
        .then(result => {
            setData(result);
        });
    }, []);

const validationSchema = Yup.object().shape({
        title: Yup.string()
            .max(50, 'You may only enter up to 50 characters')
            .required('Required'),
        description: Yup.string()
            .max(200, 'You may only enter up to 200 characters')
            .required('Required'),
        author: Yup.string()
            .required('Required')
    })

    return (
        <div>
            {
                (data !== undefined) ?
                    <Formik initialValues={data}
                        validationSchema={validationSchema}
                        onSubmit={(values) => {
                            setTimeout(() => {
                                alert(JSON.stringify(values, null, 2));
                            }, 3000)
                        }}
                    >
                        {props => (
                            <Form>
                                <Grid container spacing={2}>
                                    <Grid item xs={6}>
                                        <TextField name="bookId" label="Book ID" variant="outlined" 
                                             margin="dense" color="secondary" type="input"/>
                                        <TextField name="title" label="Title" variant="outlined" 
                                             margin="dense" color="secondary" type="input"/>
                                        <TextField name="description" label="Description" type="input"
                                             variant="outlined" margin="dense" color="secondary" />
                                        <TextField name="author" label="Author" variant="outlined" 
                                             margin="dense" color="secondary" type="input"/>
                                    </Grid>
                                </Grid>
                                <DialogActions >
                                    <DangerButton icon={<SaveRecordIcon />} label="Save"
                                        handleClick={() => alert("Save")} />
                                    <PrimaryButton icon={<PlusIcon />} label="Submit"
                                        handleClick={() => props.handleSubmit()} />
                                    <NeutralButton label="Next" handleClick={() => alert("next")} />
                                </DialogActions>
                            </Form>
                        )}
                    </Formik>
                    : <OverlaySpinner />
            }
        </div >
    )
}

export default EditBookInfoForm

Below is what the results from my API are:

[{
    bookId: 1
    title: "Anna Karenina"
    description: "Anna Karenina tells of the doomed love affair between the sensuous and rebellious Anna and the dashing officer, Count Vronsky."
    author: "Leo Tolstoy"
}]
like image 978
G Josh Avatar asked Jun 24 '26 05:06

G Josh


1 Answers

You can set the property 'enableReinitialize={true}' in Formik, as shown in the following topic Recommended way to set initialValues from async api call #1033

like image 121
Kleiton Avatar answered Jun 27 '26 12:06

Kleiton