0
votes

This is my .tsx file for adding an enterprise.

When I run the program, I am able to type in the input but when I hit the submit button nothing happens.

I have a page in my application with a button to add a new enterprise. When the add enterprise button is clicked, a form is displayed with an input field for name and a submit button. When the user hits submit after filling out the form that enterprise name should appear in the enterprise table.

export default class AddEnterprise extends React.Component {
  state = {
    name: '',
  }

  handleChange = event => {
    this.setState({ name: event.target.value });
  }

  handleSubmit = event => {
    event.preventDefault();

    const enterprise = {
      name: this.state.name
    };

    axios.post(`${process.env.PUBLIC_URL}/api/enterprises`, { enterprise })
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }

  render() {
    return (
        <div>
    <form onSubmit={this.handleSubmit}>
      <label>
        Enterprise Name:
        <input type="text" name="name" onChange={this.handleChange} />
      </label>
      <button type="submit">Add</button>
    </form>
  </div>
    )
  }
}

In the developer console I get the following error:

Failed to load resource: the server responded with a status of 400 () createError.js:16 Uncaught (in promise) Error: Request failed with status code 400 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:61)

I am new to typescript/react and would appreciate any insight/solution.

1
uncaught promise is when axios.post(...).then(...), if promise resolves to error, you don't have handler there. Try this: axios.post(...).then(...).catch(err => console.log(err)).muradm

1 Answers

1
votes

you can catch the error in axios like this:

axios({
    ...
}).then((response) => {
    ....
}).catch((error) => {
    if( error.response ){
        console.log(error.response.data); // => the response payload 
    }
});