RGS
RGS

Reputation: 4253

Parse componentDidMount values in render with state

I'm new using react. I'd like to get content from firebase and parse it in render. So I try:

constructor(props) {
    super(props);
    this.state = {
        loading: true,
        data: null
    }
}


componentDidMount() {
    var feedRef = firebase.database().ref().child('posts').limitToLast(10);
    feedRef.once('value', async function(snapshot) {

        this.setState({ data: snapshot.val(), loading: false }); // error Unhandled Rejection (TypeError): Cannot read property 'setState' of null

    });
}

render() {

    return this.state.loading ? (
        <div>
            <Spinner />
        </div>
    ) : (

        <>
                <div>
                    // how to put firebase content here?
                </div>
        </>

    );
}

I'd like to get content from firebase (user name, img) and place it in render. How can I make it?

Upvotes: 0

Views: 41

Answers (2)

UjinT34
UjinT34

Reputation: 4987

You pass a regular function to feedRef.once and it gets it's own this. You should use an arrow function:

feedRef.once('value', async (snapshot) => {

or save this in other variable:

const me = this;
feedRef.once('value', async function(snapshot) {

    me.setState({ data: snapshot.val(), loading: false }); // error Unhandled Rejection (TypeError): Cannot read property 'setState' of null

});

Upvotes: 2

Ferin Patel
Ferin Patel

Reputation: 3978

You can use map function to iterate over data state and render the list of items inside data state.
Please to sure to use ${item.WHATEVER_YOUR_FIELD_IS} inside map function.

<div>
   {this.state.data.map(item => {

     return(
      <div>
         <h1>${item.username}</h1>
         <img src=`${item.imgURL}`/>
      </div>
   )
})}
</div>

Upvotes: 2

Related Questions