0
0

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 3 years have passed since last update.

[React] firestoreのデータをaxios取得に書き換える

Last updated at Posted at 2021-01-10

開発環境

react : 17.0.1
node : 12.18.2
npm : 6.14.5
firebase : 8.2.1
axios : 0.21.1

既存コード

今回はusersコレクションをfirestoreで用意しておき、userのデータをfirestoreから取得し、userのnameを一覧で表示させる実装です。

top.js
import React, { useState, useEffect } from 'react'
import firebase from '../lib/firebase'

const Top = () => {
  const [users, setUsers] = useState([])

  // firestoreからuserのデータを取得する関数
  const getFirestoreUsers = async () => {
    const snapshot = await firebase.firestore().collection('users').get()
    const users = snapshot.docs.map(doc => doc.data())
    setUsers(users)
  }

  useEffect(() => {
    getFirestoreUsers()
  }, [])

  return (
    <div>
      {
        users.map((user, index) => (
          <p key={index}>{user.name}</p>
        ))
      }
    </div>
  )

export default Top

axiosの導入

yarn add axios

axiosでfirestoreのデータを取得する

userShow.js
import React, { useState, useEffect } from 'react'
import axios from 'axios'

const UserShow = () => {
  const [users, setUsers] = useState([])

  useEffect(() => {
    // プロジェクトIDは環境変数で呼び出す
    // process.envを付けるのを忘れずに
    const USERS_URL = `https://firestore.googleapis.com/v1/projects/${process.env.REACT_APP_PROJECT_ID}/databases/(default)/documents/users`
    const fetchUsersData = async () => {
      const result = await axios(USERS_URL)       

      setUsers(result.data.documents)
    }
    fetchUsersData()
  }, [])

  return (
    <div>
      {
        users.map((user, index) => (
          <p key={index}>{user.fields.name.stringValue}</p>
        ))
      }
    </div>
  )
}

export default UserShow

※useEffectを少しリファクタリングしました(2021/1/11)

userShow.js
useEffect(() => {
  axios.get(USERS_URL)
    .then(res => res.data.documents)
    .then(fields => setUsers(fields))
}, [])

まとめ

viewで呼び出す記述が長い気がするので、他に良い実装方法があれば教えていただきたいです。。

参考記事

Cloud Firestore REST API を使用する
How to fetch data with React Hooks?

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?