LoginSignup
0
0

More than 1 year has passed since last update.

Expo - React NativeでFirestoreを使うとき、複数のファイルに分割する方法

Last updated at Posted at 2023-01-21

状況

Firestoreのライブラリを作っていくとき、 [Firestoreの公式](https://firebase.google.com/docs/web/setup)には、このように1つのファイルに書いていく方法しか、記載がありません。
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';
// Follow this pattern to import other Firebase services
// import { } from 'firebase/<service>';

// TODO: Replace the following with your app's Firebase project configuration
const firebaseConfig = {
  //...
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

// Get a list of cities from your database
async function getCities(db) {
  const citiesCol = collection(db, 'cities');
  const citySnapshot = await getDocs(citiesCol);
  const cityList = citySnapshot.docs.map(doc => doc.data());
  return cityList;
}

これらのFirebaesへのメソッドを、複数ファイルにしていくとき、
initializeAppを複数回呼び出すと以下のエラーが発生します。
(initializeAppを呼び出せるのは1回)

The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most 
cases you only need to call initializeApp() once. But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name.

解決方法

firebaes.firestore()をexportして、他のファイルから参照できるようにします。

index.ts
export const fireStore = firebase.firestore();

そして、他のファイルから参照して使用。

function.ts
import { fireStore } from "./firebase";

await fireStore.collection....

参考

https://nipo-plus-doc.sndbox.jp/tech/separate-files/index.html https://yasutomo.hatenablog.com/entry/2021/01/13/215631
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