ExpoFirebaseと接続する。
前回詰まったので記事を新しく書く
ExpoでFirebaseと接続してデータを表示するだけのデモアプリを前回作ってみたが期待してたものと違うものができていた気がする😅
Expoの公式を今日は朝から眺めていたのですが意外としっかりしてる気がした。これを参考にすればいいのでは?
Expo Goを使って実機でビルドすれば前回の問題は解決できていた気がする。仮装デバィスだと失敗するのだろうか?
Androidだけ前回ダメだった😇
こちらを参考にしてみよう。
ダミーのデータは前回記事と同じものを使用した。
☕まずは公式の解説を読むか
Use Firebase
A guide on getting started and using Firebase JS SDK and React Native Firebase library.
Firebaseを使う
Firebase JS SDK と React Native Firebase ライブラリの使い方のガイドです。
Firebase is a Backend-as-a-Service (BaaS) app development platform that provides hosted backend services such as real-time database, cloud storage, authentication, crash reporting, analytics, and so on. It is built on Google's infrastructure and scales automatically.
There are two different ways you can use Firebase in your projects:
Using Firebase JS SDK
Using React Native Firebase
React Native supports both the JS SDK and the native SDK. The following sections will guide you through when to use which SDK and all the configuration steps required to use Firebase in your Expo projects.
Firebaseは、リアルタイムデータベース、クラウドストレージ、認証、クラッシュレポート、分析などのホスト型バックエンドサービスを提供するBaaS(Backend-as-a-Service)アプリ開発プラットフォームです。Googleのインフラ上に構築され、自動的に拡張される。
プロジェクトで Firebase を使用するには、2つの異なる方法があります:
Firebase JS SDKの使用
React Native Firebaseの使用
React Nativeは、JS SDKとネイティブSDKの両方をサポートしています。以下のセクションでは、どのSDKをいつ使用するか、またExpoプロジェクトでFirebaseを使用するために必要なすべての設定手順について説明します。
Prerequisites
Before proceeding, make sure that you have created a new Firebase project or have an existing one using the Firebase console.
前提条件
先に進む前に、Firebase コンソールを使用して新しい Firebase プロジェクトを作成したか、既存のプロジェクトがあることを確認してください。
設定さえできていればOK
プロジェクトを作成する。
bunx create-expo-app expo-firebase -t expo-template-blank-typescript
ライブラリを追加する。私はbunでやってます。
bun add firebase
Initialize the SDK in your project
To initialize the Firebase instance in your Expo project, you must create a config object and pass it to the initializeApp() method imported from the firebase/app module.
The config object requires an API key and other unique identifiers. To obtain these values, you will have to register a web app in your Firebase project. You can find these instructions in the Firebase documentation.
After you have the API key and other identifiers, you can paste the following code snippet by creating a new firebaseConfig.js file in your project's root directory or any other directory where you keep the configuration files.
プロジェクトで SDK を初期化する
Expo プロジェクトで Firebase インスタンスを初期化するには、config オブジェクトを作成し、firebase/app モジュールからインポートされた initializeApp() メソッドに渡す必要があります。
configオブジェクトには、APIキーとその他の一意の識別子が必要です。これらの値を取得するには、Firebase プロジェクトにウェブアプリを登録する必要があります。この手順はFirebaseのドキュメントを参照してください。
APIキーとその他の識別子を取得したら、プロジェクトのルートディレクトリか、その他の設定ファイルを置いているディレクトリに、新しいfirebaseConfig.jsファイルを作成することで、以下のコードスニペットを貼り付けることができます。
firebaseConfig.ts
を作成する。Webアプリ用のAPI KEYを作成して貼り付けるだけ良い。
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
// Initialize Firebase
const firebaseConfig = {
apiKey: "*************************",
authDomain: "***********************",
projectId: "***********************",
storageBucket: "***********************",
messagingSenderId: "***********************",
appId: "***********************",
measurementId: "***********************"
};
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
デモアプリのコードを App.tsx
に書く。これだけで良い。まずは接続して動かす方法から学んでそれから、Bassを使ったアプリの開発を勉強していきましょう。
全体のコード
import { useEffect, useState } from 'react';
import { StyleSheet, Text, View, ScrollView, ActivityIndicator } from 'react-native';
import { collection, getDocs } from 'firebase/firestore';
import { db } from './firebaseConfig';
interface User {
id: string;
name: string;
}
export default function App() {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let isMounted = true;
const fetchUsers = async () => {
try {
console.log('Fetching users...');
const querySnapshot = await getDocs(collection(db, 'users'));
console.log('QuerySnapshot:', querySnapshot.size, 'documents found');
if (isMounted) {
const userList = querySnapshot.docs.map(doc => {
const data = doc.data();
console.log('Document data:', { id: doc.id, data });
return {
id: doc.id,
name: data.name || ''
};
});
console.log('Processed user list:', userList);
setUsers(userList);
}
} catch (err) {
console.error('Error details:', err);
if (isMounted) {
setError('データの取得に失敗しました');
}
} finally {
if (isMounted) {
setLoading(false);
}
}
};
fetchUsers();
return () => {
isMounted = false;
};
}, []);
if (loading) {
return (
<View style={styles.centerContainer}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
);
}
if (error) {
return (
<View style={styles.centerContainer}>
<Text style={styles.errorText}>{error}</Text>
</View>
);
}
return (
<View style={styles.container}>
<Text style={styles.title}>ユーザー一覧</Text>
{users.length === 0 ? (
<View style={styles.centerContainer}>
<Text style={styles.noData}>ユーザーデータがありません</Text>
<Text style={styles.subText}>Firestoreのusersコレクションにデータを追加してください</Text>
</View>
) : (
<ScrollView style={styles.scrollView}>
{users.map((user) => (
<View key={user.id} style={styles.userCard}>
<Text style={styles.userName}>{user.name}</Text>
</View>
))}
</ScrollView>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
padding: 20,
paddingTop: 50,
},
centerContainer: {
flex: 1,
backgroundColor: '#fff',
justifyContent: 'center',
alignItems: 'center',
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 20,
},
scrollView: {
flex: 1,
},
userCard: {
padding: 15,
marginBottom: 10,
backgroundColor: '#f5f5f5',
borderRadius: 8,
},
userName: {
fontSize: 16,
},
errorText: {
color: 'red',
fontSize: 16,
},
noData: {
fontSize: 18,
color: '#666',
marginBottom: 10,
},
subText: {
fontSize: 14,
color: '#999',
},
});
ビルドするとこんな感じです。
感想
Webの言語で普段Firebaseを使うことがあまりないので、コードの書き方に慣れていく必要がありましたが、よく使い方の例で紹介されているのが、JavaScriptで書かれたコードなので情報量は多いかも?
Firebase V9からだとコードが変更されておりますが。
Discussion