简体   繁体   中英

chaining promise where 2nd promise is dependent on the result of the first

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;

在此处输入图片说明

Try this way

useEffect(() => {
  getAsyncData();
}, []);

const getAsyncData = async () => {
  try {
    const productId = await AsyncStorage.getItem("key");
    getDataFromFirebase(productId);
  } catch (error) {
    console.log(error);
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM