tylermcginnis / re-base

:fire: A Relay inspired library for building React.js + Firebase applications. :fire:
2.13k stars 143 forks source link

Issues with ComponentDidMount() #272

Open jguo1002 opened 5 years ago

jguo1002 commented 5 years ago

Some context: I have a sample-projects.js file, I imported as import sampleProjects from '../assets/sample-projects';

I tried to load the data and sync with firebase when opening the webpage, so I wrote

Option A

componentWillMount(){
        this.setState({
            projects: sampleProjects
        });
};
componentDidMount(){
        this.ref = base.syncState(`/projects`,{
            context: this,
            state: 'projects'
        });
    }

But nothing happened. Firebase is empty. And the webpage did not load anything. I checked state is empty too.

Then I tried: Option B

componentWillMount(){
        this.setState({
            projects: sampleProjects
        });
        console.log('will mount:', this.state)
        base.syncState(`/projects`,{
            context: this,
            state: 'projects'
        });
    };

The webpage rendered twice, first time state is normal, second it becomes empty. Firebase is empty too.

So I tried: Option C

componentWillMount(){
        this.setState({
            projects: sampleProjects
        });
        console.log('will mount:', this.state)
        base.syncState(`/projects`,{
            context: this,
            state: 'projects'
        });
        this.setState({
            projects: sampleProjects
        });
    };

This time it works! Data has been synced to firebase.

Since there is some data in firebase, I used Option A again, and it works nicely.

I kind of solved the problem. But I was wondering why it happens, why Option A did not work the first time? Thanks! (PS: Still have some issues, when it renders twice, holder.js does not work. But it is unrelated to this issue. )