Reputation: 155
I am having a lot of trouble chaining two promises together in my react native app. The first promise successfully gets a value in Async storage and sets it to the state. The second promise gets the data I have from Firebase, but is dependent on the state that I set from the first promise. Any help would be greatly appreciated.
import React, { useState, useEffect } from "react";
import { Text, StyleSheet, View } from "react-native";
import firebase from "../../firebase/fbConfig";
import AsyncStorage from "@react-native-async-storage/async-storage";
let DB = firebase.firestore();
function Questions(props) {
const [productId, setProductId] = useState("");
const [question, setQuestion] = useState("");
const [reward, setReward] = useState("");
const getAsyncData = () => {
AsyncStorage.getItem("key").then((value) => setProductId(value))
// works fine //
};
const getDataFromFirebase = (productId) => {
DB.collection("ads")
.where("productId", "==", productId)
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
setQuestion(doc.data().question);
setReward(doc.data().reward);
});
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
// works fine //
};
useEffect(() => {
getAsyncData().then((productId) => getDataFromFirebase(productId));
// does not work //
});
return (
<>
<View style={styles.container}>
</View>
</>
);
}
export default Questions;
Upvotes: 0
Views: 61
Reputation: 6967
Try this way
useEffect(() => {
getAsyncData();
}, []);
const getAsyncData = async () => {
try {
const productId = await AsyncStorage.getItem("key");
getDataFromFirebase(productId);
} catch (error) {
console.log(error);
}
};
Upvotes: 1