Valonaut
Valonaut

Reputation: 29

asynchron firestore query with mapStateToProps

I would like to use some data I received from firestore to build a quiz. Unfortunately I can console.log the array, but if I use .length it is undefined.

Is this problem caused by some lifecycle or asnynchronous issue?

Thanks in advance!

import React, { Component } from 'react';
import { connect } from 'react-redux';

class LernenContainer extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            data: []
         }
    }

render() {    
     return ( 
            <div className="lernenContainer">
                LernenContainer
                {
                    console.log(this.props.firestoreData),
                    // prints array correctly

                    console.log(this.props.firestoreData.length)
                    // is undefined

                }
            </div>
         );
    }
}


const mapStateToProps = state => {
    return {
      firestoreData: state.firestoreData
    };
};

const mapDispatchToProps = dispatch => {
    return {
      // todo Achievements
    };
};

export default connect(mapStateToProps, mapDispatchToProps) (LernenContainer);

console.log(this.props.firestoreData):

console.log

Upvotes: 0

Views: 48

Answers (1)

Senthil
Senthil

Reputation: 777

Try below code

import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types'

class LernenContainer extends Component {
    constructor(props) {
        super(props);
    }
 static propTypes = {
    firestoreData: PropTypes.object.isRequired
  }
     render() { 

    const { firestoreData } = this.props
    console.log(firestoreData);
    console.log(firestoreData.length);


         return ( 
                <div className="lernenContainer">
                 </div>
             );
        }
}

    const mapStateToProps = (state) => ({
      firestoreData: state.firestoreData
    })
    const mapDispatchToProps = (dispatch) => ({
    })

  export default connect(mapStateToProps,mapDispatchToProps)(LernenContainer);

Upvotes: 2

Related Questions