Search code examples
reactjscsvreact-final-form

React-Final-Form csv upload submit


I'm using React-Final-Form to upload and submit a simple csv file. I've tested the API and headers configuration, everything works fine if I use PostMan. I've also hardcoded the csv values into my const data as per API documentation, and everything works fine.

Hardcoded example:

// Example HARDCODED = WORKS PERFECTLY!!
  const data = {
    "invitation": {
      "file": "Email\nuser_1@gmail.com\nuser_2@gmail.com\n"
    }
  }

If I want to collect the cvs file from the uploaded input and pass it as a prop, it doesn't work. When I console.log the props value it returns undefined.

See my code below:

const handleSubmitOnClick = ({
  file
}) => {

  console.log(file)
  const url = 'http://localhost:3000/api/v1/invitations/upload';
  const headers = {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }

  const data = {
    "invitation": {
      "file": file   <==== *** HERE THE ISSUE ****
    }
  }

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

const JoinTesting = () => 
    <Form 
      onSubmit={handleSubmitOnClick}
    >
      {
        ({ 
          handleSubmit, 
          values, 
          submitting,
        }) => (
        <form onSubmit={handleSubmit} encType="multipart/form-data">

          <Field 
            name="invitation[file]"
            placeholder='Upload csv file'
            validate={required}
          >
            {({ input, meta, placeholder }) => (
              <div className={meta.active ? 'active' : ''}>
                <label>{placeholder}</label>
                <input 
                  {...input} 
                  type='file' 
                  placeholder={placeholder} 
                  className="join-field-input"

                />
                {meta.error && meta.touched && <span className="invalid">{meta.error}</span>}
                {meta.valid && meta.dirty && <span className="valid">Great!</span>}
              </div> ...etc..

Error I get is this:

Error: Request failed with status code 500
    at createError (createError.js:17)
    at settle (settle.js:19)
    at XMLHttpRequest.handleLoad (xhr.js:60)

which is weird because as I said, if I hardcode the file value everything works fine.

In the Browser networks tab, the Payload returns {invitation:{}} Any ideas?


Solution

  • I've found the issue.

    This is what I was doing wrong:

    const handleSubmitOnClick = ({
      file
    }) => {
    

    Supposed to be:

    const handleSubmitOnClick = file => {
    

    Because I was trying to deconstruct the props, when in reality I shouldn't have to. Practically it couldn't see any values coming through. I hope it will help someone else! happy coding!