I'm just wondering how to implement callback function in onPress
function. I want to make sure the first function completed then the second process triggered.
onPress={() => {
onSignIn(); //run this function first
if(_values.success == 1){ //then run this after onSignIn() function completed
navigation.navigate("SignedIn");
}
}}
onSignIn()
export const onSignIn = async () => {
if (_values.username && _values.password) {
fetch("http://localhost:3001/sessions/create", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: _values.username,
password: _values.password
})
})
.then((response) => response.json())
.then((responseData) => {
if(responseData.access_token){
AsyncStorage.setItem(USER_KEY, responseData.access_token);
_values.success = 1;
alert("Login successfully!");
return _values.success;
} else {
alert("Wrong username and password!");
_values.success = 0;
return _values.success;
}
})
.done();
} else{
alert("Please enter your username and password.");
}
}
Reference: https://github.com/datomnurdin/auth-reactnative
Return a Promise from the method and add .then() to the function call
export const onSignIn = async () => {
const promise = new Promise(async (resolve, reject) => {
try {
//do something and return result on success
resolve(result);
}catch(msg) { reject(msg);}
});
return promise;
}
Call the method like this:
onSignIn ().then(
(response,error) => {
//get callback here
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With