#StackBounty: #javascript #error-handling #fetch-api How do I catch and parse errors properly in my React form submission handler?

Bounty: 250

I’m using React 16.13.0. I have the following function to deal with submit events …

  handleFormSubmit(e) {
    e.preventDefault();
    const NC = this.state.newCoop;
    delete NC.address.country;

    fetch('/coops/',{
        method: "POST",
        body: JSON.stringify(this.state.newCoop),
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
    }).then(response => {
        if (response.ok) {
            return response.json();
        }
        console.log(response.json());
        console.log(response.body);
        throw new Error(response.statusText);
    }).catch(errors => {
        console.log(errors);
        this.setState({ errors });
    });
  }

However, I’m having an issue getting the errors properly from the response. When an error occurs, my endpoint returns a 400 request with the error text. This is what happens in curl …

curl --header "Content-type: application/json" --data "$req" --request POST "http://localhost:9090/coops/"
{"phone":["The phone number entered is not valid."]}

But the “response.statusText” contains “400 (Bad Request)”. What’s the right way to catch the error text and preserve it for future parsing? If my endpoint needs to format the data differently, what should it do (using Django/Python 3.7)?

Edit:

This is the Input component in which I’m trying to display errors …

          <Input inputType={'text'}
               title= {'Phone'}
               name= {'phone'}
               value={this.state.newCoop.phone}
               placeholder = {'Enter phone number'}
               handleChange = {this.handleInput}
               errors = {this.state.errors}

               /> 

And the code of the input component, src/Input.jsx

import React from 'react';
import {FormControl, FormLabel} from 'react-bootstrap';

const Input = (props) => {
    return (
  <div className="form-group">
      <FormLabel>{props.title}</FormLabel>
      <FormControl
            type={props.type}
            id={props.name}
            name={props.name}
            value={props.value}
            placeholder={props.placeholder}
            onChange={props.handleChange}
          />

      {props.errors && props.errors[props.name] && (
          <FormControl.Feedback>
                <div className="fieldError">
                     {props.errors[props.name]}
                </div>
          </FormControl.Feedback>
      )}
  </div>
    )
}

export default Input;

When I run “console.log(errors)” they appear as such …

{phone: Array(1), web_site: Array(1)}


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.