Thursday, 5 May 2016

javascript - Promises with React

I have questions about promises. I'm just starting to deal with them and it's not that easy to understand!



I'm trying to setup an authentication system for my app.




RegisterPage



handleSubmit looks like that:



handleSubmit(event) {
event.preventDefault();
const { user } = this.state;
//some code here
userActions.register(user);

}


UserActions



function register(user) {
userService.register(user)
.then(
user => {
success(user);

},
error => {
failure(error.toString());
}
);
function success(user) { return { type: "REGISTER_SUCCESS", user } }
function failure(error) { return { type: "REGISTER_ERROR", error } }
}



UserService



function register(user) {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user)
};

return fetch(`/api/users/register`, requestOptions).then(handleResponse);

}

function handleResponse(response) {
return response.text().then(text => {
const data = text && JSON.parse(text);
if (!response.ok) {
const error = (data && data.message) || response.statusText;
return Promise.reject(error);
}


return data;
});
}


Question 1. That code is "working" but not like I want. That way, even if the request success, I still can have error from the server, like duplicate username or something like that. I guess what I want is to return Promise.reject() not just if !response.ok but also if I have errors in the JSON returned right?



function handleResponse(response) {
return response.text().then(text => {
const data = text && JSON.parse(text);

if (!response.ok) {
const error = (data && data.message) || response.statusText;
return Promise.reject(error);
}
else if(data.errors) {
return Promise.reject(data.message);
}

return data;
});

}


Question 2. If everything's fine, should I return data or return Promise.resolve(data)? And why?

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...