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

1

1 Answer 1

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()
        });
    });


},
Sign up to request clarification or add additional context in comments.

6 Comments

How would i go about making it usable in the form?
Ok so default value is wrong? How would i go about updating the box after the data is fetched?
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
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.
I have edited my answer too :) this must point to correct object.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.