Nathan Hohnbaum
Nathan Hohnbaum

Reputation: 25

How do I get form data?

I'm writing a React app, and when trying to get the login form data to send to the backend, it is empty.

// Login component class
submitLoginForm = (event) => {
    event.preventDefault();
    const target = event.target;
    const data = new FormData(target);
    // data is empty, but I need it to contain the form data.
    // ...
}

render() {
    return (
        <div>
            <form onSubmit={this.submitLoginForm}>
                <input type="hidden" name="csrfmiddlewaretoken" value={Cookies.get("csrftoken")} />
                <label htmlFor="username">Username: </label>
                <input id="username" name="username" type="text" />

                <label htmlFor="password">Password: </label>
                <input id="password" name="password" type="password" />

                {this.state.errorText}
                <input type="submit" value="submit" />
            </form>
        </div>
    );
}

EDIT: While the FormData object does have form data, passing it to a fetch request fails to pass along any of the data and simply sends an empty JSON object instead. The same result happens with JSON.stringify. How do I get the data as a JSON object?

Upvotes: 0

Views: 187

Answers (2)

ray
ray

Reputation: 27245

Not sure this is the ideal way to do it, but you could build up a pojo from formData.entries() like this, and then do whatever you need to do from there.

const submitLoginForm = e => {
  e.preventDefault();
  const fd = new FormData(e.target);
  const formObj = [...fd.entries()].reduce((acc, [key, value]) => ({...acc, [key]: value}), {});
  console.log(formObj);
}
<form onsubmit="submitLoginForm(event)">
  <label htmlFor="username">Username: </label>
  <input id="username" name="username" type="text" />

  <label htmlFor="password">Password: </label>
  <input id="password" name="password" type="password" />
  <input type="submit" value="submit" />
</form>

Upvotes: 0

Drew Reese
Drew Reese

Reputation: 202605

TBH I've not had much luck getting FormData to work well with react. You can access the form fields of the form's onSubmit event object.

// Login component class
submitLoginForm = (event) => {
  event.preventDefault();
  const target = event.target;
  const data = {
    username: target.username.value,
    password: target.password.value,
  };
  // JSON.stringify(data) in request body
}

Upvotes: 1

Related Questions