Search code examples
reactjsaxiosreact-final-form

Pass input values with React-Final-Form to Axios POST


I have a login page. Fields: username and password.

On form submit I want to pass the 2 input values to a function which will handle a POST call via Axios API.

Because I am using React-Final-Form, I don't see anyone using refs for the inputs in order to collect the data. Final-Form provides values as props, but I can't pass them to my external handleClickSignIn function.

const handleClickSignIn = () => {
  axios.post(url, data, {
    headers: headers
  })
  .then(response => console.log(response))
  .catch(err => console.log(err))
}

const focusOnError = createDecorators();

const SignIn = () => 
  <Fragment>
    <h1>Sign In page</h1>

    <Form 
      onSubmit={handleClickSignIn}
      decorators={[focusOnError]}
    >
      {
        ({ 
          handleSubmit, 
          values, 
          submitting 
        }) => (
        <form onSubmit={handleSubmit}>
          <Field 
            name='email'
            placeholder='Email'
            validate={required}
          > 
            {({ input, meta, placeholder }) => (
              <div className={meta.active ? 'active' : ''}>
                <label>{placeholder}</label>
                <input {...input} 
                  type='email' 
                  placeholder={placeholder} 
                  className="signin-field-input"

                />
etc...


Solution

  • you should look at the documentation

    onSubmit is a function that will be called with the values of your form

    So handleClickSignIn will retrieve the form values in its first argument

    const handleClickSignIn = (values) => {
        // do what you want with the form values
        axios.post(url, values, {headers: headers})
        .then(response => console.log(response))
        .catch(err => console.log(err))
    }