1

I am facing to asynchronism problem :

  1. I create a user in firebase, generating a unique ID for it.
  2. I get this unique ID.
  3. I call an async function to persist this ID with AsyncStorage method.

Problem : The asyncStorage method is called before I get back the generated ID from my user creation. How to deal with this ?

This is my code :

class Subscription extends Component {

  constructor() {
    super();
    this.state = {
      email: '', 
      password: ''
    }
  }

  persistUserId = (userID) => {
    try {
      AsyncStorage.setItem('userId', userID); // Here, user ID is undefined
    } catch (error) {
      console.log(error.message);
    }
  };

  updateInputValue = (value, prop) => {
    const state = this.state;
    state[prop] = value;
    this.setState(state);
  }

  registerUser = () => {
    var generatedUserId = '';

    firebase
    .auth()
    .createUserWithEmailAndPassword(this.state.email, this.state.password) // Authentication
    .then((res) => {
        var user = { // Set Javascript Object to insert
        email: this.state.email
        }

        database.collection("users").add({ // Create the new user generating an ID
            'email': user.email,
        }).then(function(docRef) {
            generatedUserId = docRef.id; // Get the generated ID (The one to persist witch asyncstorage)
        }).then(function() {
            this.persistUserId(generatedUserId) // Call the AsyncStorage to persist the ID
        })
            this.props.navigation.navigate('AppPage') // Go to next page.
    })
    .catch(error => {
        alert(error.message)
    })      
  }

1 Answers1

1

For persisting data. According to react-native doc. You need to use async await keyword:

_storeData = async () => {
  try {
    await AsyncStorage.setItem(
      '@MySuperStore:key',
      'I like to save it.'
    );
  } catch (error) {
    // Error saving data
  }
}

for your case:

persistUserId = async (userID) => {
    try {
      await AsyncStorage.setItem('userId', userID); // Here, user ID is undefined
    } catch (error) {
      console.log(error.message);
    }
  };

Note: Persisting data is async process. That's why you need to use async await

You need to update your firebase then catch as well. Either use bind or use arrow function. Here is updated version:

firebase
  .auth()
  .createUserWithEmailAndPassword(this.state.email, this.state.password) // Authentication
  .then((res) => {
    var user = {
      // Set Javascript Object to insert
      email: this.state.email,
    };

    database
      .collection("users")
      .add({
        // Create the new user generating an ID
        email: user.email,
      })
      .then( (docRef) =>  {
        generatedUserId = docRef.id; // Get the generated ID (The one to persist witch asyncstorage)
      })
      .then( () =>  {
        this.persistUserId(generatedUserId); // Call the AsyncStorage to persist the ID
      });
    this.props.navigation.navigate("AppPage"); // Go to next page.
  })
  .catch((error) => {
    alert(error.message);
  });
Shubham Verma
  • 3,814
  • 1
  • 4
  • 18