jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
33.98k stars 2.79k forks source link

Transfer data from Formic not working to object #3622

Open 85ar opened 2 years ago

85ar commented 2 years ago

Good afternoon. I am using Formik in my React js project. I'm doing a multi-step form. The form has 2 inputs where the user selects a start and end date. And then I need to put this data into an object of a certain structure to send a post request. But I'm using the tag and my input data is only inside it. How do I raise this data above and add it to the object? The component looks like this:

const StepTwo = (props: any) => {
const getSql = async () => {
 const sqlRequest : any => {
    object_id: [],
    start_date: " ",
    end_date: " ",
 }
}

return (
<Formik
    initialValues={props.data}
    ...
>
<Form>
<div>
<label>Start date</label>
<Field
    name="start_date"
    type="date"
></Field>

</div>

...

</Form>
</Formik>
)

}

... That is, I need to take the start_date and end_date from the formik values add pass them to an object sqlRequest.

Help me, please

yuhang1995 commented 2 years ago

I don't know if your component that contains the POST request can be a subcomponent of the Form, but if it is, then you can use useFormikContext to get the Form value you need. like this:

const FormContent = (props) => {
    return (
        <Formik>
            <Form>
                <Field />
                <Child />
            </Form>
        </Formik>
    )
}

function Child() {
    const {values} = useFormikContext()

    return <div>child</div>
}
85ar commented 2 years ago

Thank you very much