Home > Net >  How to submit request with formik and axios
How to submit request with formik and axios

Time:07-17

I want to post some data with Axios and I'm using formik but as formik doesn't need an external state for tracking the input fields I don't know what to pass in the payload of Axios post request


const Form = () => {

  const submitHandler = (e) => {
    e.preventDefault();
    axios
      .post("http://127.0.0.1:8000/todo/todos/", {
       // i dont know what to put here, before i use formik it was like this 
      //state,})
  };
  return (
    <Formik
      initialValues={{
        title: "",
        description: "",
      }}
      validationSchema={validate}
    >
      {(formik) => (
        console.log(formik.values),
        (
          <StyledForm onSubmit={submitHandler}>
            <div>
              <div>
                <Input
                  name="title"
                  type="text"
                />
              </div>
              <div>
                <Textarea
                  type={"text"}
                  name="description"
                  as="textarea"
                />
              </div>
            </div>
          </StyledForm>
        )
      )}
    </Formik>
  );
};

export default Form;

CodePudding user response:

Since Formik handles your values, you should use it as well for submitting your form.

The onSubmit function you pass into Formik has all your needed values.

  const submitHandler = (values) => {
    axios.post("http://127.0.0.1:8000/todo/todos/", values);
    // further handling
  };

  return (
    <Formik
      initialValues={{
        title: "",
        description: "",
      }}
      validationSchema={validate}
      onSubmit={(values) => submitHandler(values)}
    >
  ...
  • Related