Today I am struggling with a fetch issue in my react native app. I would like my user to login straight after he registers. In order to do that I have one function to fetch the signUp
and another one to fetch the login. The problem is that when in the view I click on the register()
button, only the signUp
fetch is called. Though, if I click a second time on the button then both the signup and the login fetch are called but an error occurs on the signup because the user has already been added to the database. So, I would like to be able to chain two fetch, one after another. Here is my code :
The API helper class:
const Api = {
signUp(user) {
return new Promise((resolve, reject) =>
{
console.log(Constant.default.apiUrl);
fetch(Constant.default.apiUrl + '/signup', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(user)
})
.then(response => response.json())
.then(responseJson => {
if (responseJson.success) {
console.log(responseJson.userData);
resolve(responseJson.userData);
} else {
reject(responseJson);
}
})
.catch(err => console.log(err));
});
},
login(user) {
return new Promise((resolve, reject) => {
fetch(Constant.default.apiUrl + '/login', {
method : 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(user)
})
.then(response => response.json())
.then(responseJson => {
console.log("responsejson " + responseJson);
console.log("laaaa");
if (responseJson.success) {
resolve(responseJson.userData);
} else {
reject(responseJson);
}
})
.catch(err => console.log("catch login" + err))
})
}
};
export default Api;
The register function (when I click register button):
register () {
if (this.state.password.length > 3 && this.state.password === this.state.confirmPassword) {
var user = {
firstName: this.props.firstName,
lastName: this.props.lastName,
emailAddress: this.state.emailAddress,
password: this.state.password,
};
Api.signUp(user)
.then(result => {
console.log("sign up result : " + JSON.stringify(result));
return {
emailAddress : user.emailAddress,
password : user.password
};
})
.then(loginUser => {
Api.login(loginUser)
.then(result => {
console.log("login result " + JSON.stringify(result));
})
.catch(resultErr => console.log(resultErr));
})
.catch(resultErr => console.log(resultErr));
} else {
this.setState({error: true,
errorMessage: 'Veuillez remplir les champs correctement'});
}
};
Please help me figure out why I have to click twice on register()
button.
EDIT:
When I click once, nothing happens in the console but the user is added to the database. The second time, I see this: