Change default firebase database programmatically and run the same firebase functions both on default and secondary database

Viewed 2135

Background - I'm setting up a new feature that allows users to select which city they are in, since my app is a public transportation app. I would like cities to be in separate databases, and for that I have created a secondary database in my firebase project. It's a React Native App and I'm using react-native-firebase.

Question 1 - When the users selects a different city, I would like that database to be his default database. I couldn't figure out how to do this, can anyone help?

I've tried initializing and just changing the databaseURL, and even though I connected to the second DB once, it didn't do so every time. Seemed like an unstable solution.

The other solution I found would be to pass the url to every "firebase.database(url)", but that seems like a bad solution.

Question 2 - Since the app is exactly the same on both cities, I would like to run the same functions I already run on DB1, on DB2. They are completely separate DBs, but with the exact same nodes. Both have a "location" node, for example, and then I have a listener for changes there. How do I set up listeners on both databases with just one function? Or do I need to get a reference to DB2 and just duplicate the functions?

1 Answers

There is no concept of a default database per user. That means that you'll want to initialize Firebase from your JavaScript code as shown in the React Native Firebase documentation:

// pluck values from your `GoogleService-Info.plist` you created on the firebase console
const iosConfig = {
  clientId: 'x',
  appId: 'x',
  apiKey: 'x',
  databaseURL: 'x',
  storageBucket: 'x',
  messagingSenderId: 'x',
  projectId: 'x',

  // enable persistence by adding the below flag
  persistence: true,
};

// pluck values from your `google-services.json` file you created on the firebase console
const androidConfig = {
  clientId: 'x',
  appId: 'x',
  apiKey: 'x',
  databaseURL: 'x',
  storageBucket: 'x',
  messagingSenderId: 'x',
  projectId: 'x',

  // enable persistence by adding the below flag
  persistence: true,
};

const kittensApp = firebase.initializeApp(
  // use platform specific firebase config
  Platform.OS === 'ios' ? iosConfig : androidConfig,
  // name of this app
  'kittens',
);

// dynamically created apps aren't available immediately due to the
// asynchronous nature of react native bridging, therefore you must
// wait for an `onReady` state before calling any modules/methods
// otherwise you will most likely run into `app not initialized` exceptions
kittensApp.onReady().then((app) => {
   // --- ready ---
   // use `app` arg, kittensApp var or `app('kittens')` to access modules
   // and their methods. e.g:
   firebase.app('kittens').auth().signInAnonymously().then((user) => {
       console.log('kittensApp user ->', user.toJSON());
   });
});
Related