0

Im new to reactjs and trying to populate a form from a value retrieved from firebase.

Here is where the value is fetched.

componentWillMount: function () {

    var projectId = this.props.params.key;
    this.fb = new Firebase(rootUrl + 'items/');
    var projectRef = this.fb.child(projectId);

    var subjectproject = "NA";


    projectRef.child("subject").on("value", function(snapshot) {
        subjectproject = snapshot.val();
    });


},

And here is the form input that i want to populate

<div className="col-lg-6">
           <div class="input-group">
               <label class="control-label required" for="project_project_title">Subject</label>
                     <input defaultValue={subjectproject} value={this.state.subject} placeholder="Subject" onChange={this.handleInputChangeSubject} type="text" className="form-control"/>
            </div>
  </div>

All i ever get is projectSubject is undefined. How do i create a variable that can be used to provide a defaultvalue.

Edit -

 projectRef.child("subject").on("value", function(snapshot) {
        textsubject = (snapshot.val());
        this.setState({subject: textsubject});
    });

Throws FIREBASE WARNING: Exception was thrown by user callback. TypeError: this.setState is not a function

ChrisM
  • 706
  • 11
  • 30
  • Possible duplicate of [What is the scope of variables in JavaScript?](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Evan Davis Mar 03 '16 at 21:07

1 Answers1

2

subjectproject - is declared as local variable in componentWillMount. It is not visible in your render method.

See this: https://facebook.github.io/react/docs/forms.html#default-value

The defaultValue and defaultChecked props are only used during initial render.

Example(from comment):

componentWillMount: function () {
    var self = this;

   // some code

    projectRef.child("subject").on("value", function(snapshot) {
        self.setState({
            subjectproject: snapshot.val()
        });
    });


},
Dmitriy
  • 3,745
  • 16
  • 24
  • How would i go about making it usable in the form? – ChrisM Mar 03 '16 at 21:01
  • Ok so default value is wrong? How would i go about updating the box after the data is fetched? – ChrisM Mar 03 '16 at 21:14
  • When data is fetched you should use `this.setState` method to set data to `state[propertyName]`. And then you can use `this.state[propertyName]` anywhare in your `render` method – Dmitriy Mar 03 '16 at 21:18
  • Ive edited my post. If i try setState from inside the function it throws an error. Whats the correct way of doing it? If i use setState outside with other data it sets it fine. – ChrisM Mar 03 '16 at 21:32
  • I have edited my answer too :) `this` must point to correct object. – Dmitriy Mar 03 '16 at 21:37
  • Beautiful. Thank you very much. Much appreciated. – ChrisM Mar 03 '16 at 21:43