0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ReactNative + Firebase + RealtimeDatabase で componentDidMount内でデータの読み取りをしsetStateをする方法

Posted at

###とりあえず正常に動くソースコード

    componentDidMount() {
        firebase.database().ref("images/").on("value",this.handlePostUpdate);
        //firebaseの部分は各々違います
    }

    handlePostUpdate = (snapshot) => {
        this.setState({
            data:Object.values(snapshot.toJSON()),
        });
    }

このように記述することで、エラーが起こることなく望んだ処理を行うことができました。

一応、ついでにつまずいていた時のコードを下に書いておきます。

###エラーがでてしまっていたコード

    componentDidMount() {
        firebase.database().ref("images/").on("value",function(snapshot) {
            this.setState({
                data:Object.values(snapshot.toJSON()),
            });
        })
    }

このようにするとなぜか、

this.setState is not a function
<unknown>
    C:\Users\kim-sangwoo\expoapp\sns-sample\scenes\TimelineScreen.js:57:13
<unknown>
    
exceptionGuard
    C:\Users\kim-sangwoo\expoapp\sns-sample\node_modules\@firebase\database\dist\index.cjs.js:700:12
EventList.raise
    
EventQueue.raiseQueuedEventsMatchingPredicate_
    C:\Users\kim-sangwoo\expoapp\sns-sample\node_modules\@firebase\database\dist\index.cjs.js:9685:17
EventQueue.raiseEventsForChangedPath
    
Repo.onDataUpdate_
    C:\Users\kim-sangwoo\expoapp\sns-sample\node_modules\@firebase\database\dist\index.cjs.js:12774:13
PersistentConnection.onDataPush_
    C:\Users\kim-sangwoo\expoapp\sns-sample\node_modules\@firebase\database\dist\index.cjs.js:12083:18
PersistentConnection.onDataMessage_
    C:\Users\kim-sangwoo\expoapp\sns-sample\node_modules\@firebase\database\dist\index.cjs.js:12063:4
Connection.onDataMessage_
    C:\Users\kim-sangwoo\expoapp\sns-sample\node_modules\@firebase\database\dist\index.cjs.js:11340:13

this.setState is not a functionというエラーが出てしまいました。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?