2

I am using the fetch api in my handleSubmit function in a React component to post data like this:

handleSubmit(event) {
event.preventDefault();
var error = false;
var { username, password } = this.state
var mailFormat = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
if (!username.match(mailFormat)) {
 this.setState({ usernameError: true });
 error = true;
} else {
 this.setState({ usernameError: false });
}
if (password.length < 8) {
 this.setState({ passwordError: true });
 error = true;
} else {
 this.setState({ passwordError: false })
}
if (error) {
 this.setState({ formSuccess: false });
 return;
}
return window.fetch('http://localhost:8016/users/registration', {
 method: 'POST',
 headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
 body: JSON.stringify({ username_email: username, password: password })
})
 // .then(this.handleErrors)
 .then((response)=>{
 if (response.ok) {
 const { token } = response.clone();
 const loginOptions = {
 token,
 cookieOptions: { expires: 1 },
 callback: () => Router.push('/login')
 }
 setTimeout(() => {
 login(loginOptions)
 }, 5000)
 this.setState({
 username: '', password: '', userNameDup: false, formError: false, formSuccess: true
 })
 return response.json();
 } else if (!response.ok) {
 if (response.status === 409) {
 console.log("response.status ", response.status);
 this.setState({
 userNameDup: true, formError: true, formSuccess: false
 });
 return;
 }
 }
 return response;
 })
.catch(function (error) {
 console.log(error);
 });
}

My question regarding using fetch is typically one codes it like this to make a post request.

var url = 'https://example.com/profile';
var data = {username: 'example'};
fetch(url, {
 method: 'POST', // or 'PUT'
 body: JSON.stringify(data), // data can be `string` or {object}!
 headers:{
 'Content-Type': 'application/json'
 }
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));

As you can see in my version I have a conditional handling the error. (I’m pretty sure I’ve seen a version using a try catch block. I guess I’m used to the error/node style of handling errors.)

Anyway, I guess I’m wondering what would be the point of the catch function if the else clause in my conditional is handling the error? Will that still be utilized I mean?

So Can anyone show me what is the most ubiquitous style to handle the situation regarding error handling?

Thank you!

asked Aug 31, 2019 at 22:54

1 Answer 1

1

As per the MDN docs:

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

Knowing that, then you should at least check if response.ok == true before proceeding. The example you gave assumes it will always go the happy path which obviously is not the correct way to handle the response.

What you have in your code is ideal.

P.S. you can simplify else if (!response.ok) to just else

answered Sep 2, 2019 at 4:41
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.