David
David

Reputation: 537

Change value of field in reactjs component's state (with data obtained from firebase)

I simply want to fetch a string from a Firebase database and update the "eventName" field in my component, but I'm having trouble doing this. My code so far:

import React from 'react';
import {ref} from '../Firebase';

class EventDisplay extends React.Component {
    constructor () {
        super();
        this.state = {
            eventName: "No event Selected."
        };
    }
    render () {
        return (<div>
            <h1>Name of Event: {this.state.eventName}</h1>
            <h1>Date and Time: Dummy Name</h1>
            <h1>Event Description: Dummy Name</h1>
        </div>);
    }

    changeEventName(str) {
        this.setState({eventName: str});
    }

    componentWillMount() {
        const events = ref.child('events/event1/Title');
        var param;
        events.on('value', (function(snapshot) {
            param = snapshot.val();
            console.log(snapshot.val());
            changeEventName(param);
            })
        );
        console.log(param);
    }


}

export default EventDisplay;

However, changeEventName seems to be undefined where it is. Also "undefined" shows up in the console where I try to log param, but snapshot.val() has the desired string. Thanks

Upvotes: 1

Views: 72

Answers (2)

linasmnew
linasmnew

Reputation: 3977

changeEventName seems to be undefined where it is

Where you're calling changeEventName you need to prepend it with this.

this.changeEventName

Also since you're calling it inside of a callback you first need to bind the method in order to preserve the value of this. There're many ways you can do this, most common being:

Explicitly inside of a constructor:

this.changeEventName = this.changeEventName.bind(this)

Or using an arrow function:

events.on('value', ((snapshot) => { ... }));

Also "undefined" shows up in the console where I try to log param

That's because events.on is asynchronous, you need to move your console.log inside of the callback.

Upvotes: 2

Raghudevan Shankar
Raghudevan Shankar

Reputation: 1093

Try this.changeEventName when invoking the function; you need to do this because the function is available only within the context of the class.

Logging param returned undefined because events.on is an asynchronous function. What that means is that this function will go do whatever it was designed to do (fetch value) and only then execute the callback when its ready; param is only available in this callback method that you provided.

Upvotes: 0

Related Questions