Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I created a web application that shows reports using amChart and followed the ReactJS amChart implementation, now i am trying to pass the firebase query result into ReactJS state, but cannot feature out why i cannot get the state data value to appear.

My idea is to sum all expense data and profit data then setState each of it and then pass it to amChart chart.data array

My code so far.

  componentDidMount () {

        am4core.useTheme(am4themes_animated);

        let chart = am4core.create("chartdiv", am4charts.XYChart);
        let expense = 0;
        let profit = 0;
       
        const citiesRef = db.collection('transactions');

        // Create a query against the collection
        const queryRef = citiesRef.where('category', '==', 'Expense').get();
        const queryProf = citiesRef.where('category', '==', 'Profit').get();
        
         queryRef.then(ref=> {

              ref.docs.forEach(doc => {

               expense += parseInt(doc.data().amount)
               
              
              })
              
              return this.setState( { totalExpense: expense } )
         })

         queryProf.then(ref=> {
            ref.docs.forEach(doc => {

             profit += parseInt(doc.data().amount)
             
            
            })
           
            return this.setState( { totalProfit: profit } )
       })
         
       chart.data = [ 
            {
                "year": "2003",
                "expense": this.state.totalExpense,
                "profit": this.state.totalProfit,     
            }
        ];
             
        
        // Rest of the chart code..
       
      }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
286 views
Welcome To Ask or Share your Answers For Others

1 Answer

Since setState is asynchronous, you will never get the results this way.

You need to characterize your componentDidMount method as async componentDidMount and then await for the promises to finish

await queryRef.then(ref=> {

and

await queryProf.then(ref=> {


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...