Depending on a user set preference from AsyncStorage I need to initialize one of two Firebase environments. I have the snippet from the javascript file I'm using to set up the Firebase database, but as you can clearly see it will give me a syntax error on the await call.
What would be the best way to export the firebase symbol, but only after the appropriate initializeApp call has been made?
Thanks,
Red
import firebase from 'firebase';
import { AsyncStorage } from 'react-native';
import { FIREBASE_CONFIG, FIREBASE_CONFIG_DEMO, DATA_ENVIRONMENT_STORAGE_KEY } from '../../../shared/env';
async function initializeFirebase()
{
value = await AsyncStorage.getItem(DATA_ENVIRONMENT_STORAGE_KEY);
if ((value == null) || (value == 'live'))
firebase.initializeApp(FIREBASE_CONFIG);
if (value == 'demo')
firebase.initializeApp(FIREBASE_CONFIG_DEMO);
}
await initializeFirebase();
export var db = firebase.database();
export default firebase;
If what I understand is correct, you want is to initialize firebase, then create a db reference and export it.
Try this:
initializeFirebase.js
import firebase from 'firebase';
import { AsyncStorage } from 'react-native';
import {
FIREBASE_CONFIG,
FIREBASE_CONFIG_DEMO,
DATA_ENVIRONMENT_STORAGE_KEY
} from '../../../shared/env';
async function initializeFirebase() {
const value = await AsyncStorage.getItem(DATA_ENVIRONMENT_STORAGE_KEY);
let firebaseConfig = null;
if ((value === null) || (value === 'live')) {
firebaseConfig = FIREBASE_CONFIG;
} else if (value === 'demo') {
firebaseConfig = FIREBASE_CONFIG_DEMO;
}
if (firebaseConfig !== null) {
await firebase.initializeApp(firebaseConfig);
return firebase.database();
}
}
export default initializeFirebase;
someOtherFile.js
import initializeFirebase from './initializeFirebase.js';
async someOtherFunction() {
// ...
const database = await initializeFirebase();
// ... do something with 'database'
}