Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a callback function in React Native?

Tags:

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

like image 581
Nurdin Avatar asked Dec 26 '18 14:12

Nurdin


1 Answers

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
  });
like image 96
Nupur Sharma Avatar answered Nov 15 '22 07:11

Nupur Sharma