Home » React-native » How to implement firebase remote config in React native

How to implement firebase remote config in React native

Pro Level React-native

Hi Guys, In this article, we are going to learn about How to implement firebase remote config in React native. This is Firebase’s one of the important feature which used to transfer data dynamically in published Application. you can transfer the base URL in the Application through the Firebase Remote Config. you don’t have to upload a new build version to the Play store & App store. also, you can use Remote config for force update app bypassing new version in Application and display a popup to users for update your application. So in this article will implement remote config in React Native application. let’s start with an example.

1. Create a new project on Firebase console

Goto this link and create a new project on the firebase console

Follow steps, add project name, SHA key complete set of project. to generate SHA-1 use the following commands

  • Get SHA key from Windows machine
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
  • Get SHA key from Linux or Mac OS
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

After successfully project setup, goto dashboard left navigation Remote config option and add key & default values in it like follow


After adding all keys and values you need to publish changes as follows

In my case, I have added four keys as follows

  • base_url: This is the main base URL on which Webservices will points.
  • is_force_update: This is a boolean value that decides whether the app should popup force update alert to users.
  • build_version: This will be the latest update build version of the application
  • playstore_url: This is the play store identifier URL

2. Config Remote config in React native application

Firstly, set up the firebase app module in your project using the following commands

npm install @react-native-firebase/app   //<-- Firebase app

npm install @react-native-firebase/remote-config   //<-- Remote config

// If you are working with iOS then you should do pod install 
cd ios/ && pod install

If you are using an older version of react-native then you have to link Firebase manually. check this post for Android & iOS

3. Create RemoteConfig.js

Create RemoteConfig.js file in your project and add the following code to it.

import React, {Component} from 'react';
import {AsyncStorage, View, Text, Alert, Linking} from 'react-native';
import * as CONSTANTS from '../assets/constants/Constant';
import remoteConfig from '@react-native-firebase/remote-config';
import VersionNumber from 'react-native-version-number';


export default class RemoteConfig extends Component {
  async componentDidMount() {
    await remoteConfig()
      .setDefaults({
        base_url: CONSTANTS.baseURL,
      })
      .then(() => remoteConfig().fetchAndActivate())

      .then(fetchedRemotely => {
        if (fetchedRemotely) {
          console.log(
            '+++Configs were retrieved from the backend and activated.',
          );
          console.log(fetchedRemotely);
        } else {
          console.log(
            '+++++No configs were fetched from the backend, and the local configs were already activated',
          );
        }
      });

    //Code to get All parameters from Firebase Remote config
    const parameters = remoteConfig().getAll();
    Object.entries(parameters).forEach($ => {
      const [key, entry] = $;
      console.log('--Key: ', key);
      console.log('--Source: ', entry.getSource());
      console.log('--Value: ', entry.asString());
      console.log('--------------------------------');
    });


    //Get Firebase remote config parameters by key
    const baseUrl = remoteConfig().getValue('base_url');
    const is_force_update = remoteConfig().getBoolean('is_force_update');
    const build_version = remoteConfig().getValue('build_version');
    const playstore_url = remoteConfig().getValue('playstore_url');
    var bnewBuildVersion = build_version.asString();
    var playstoreUrl = playstore_url.asString();
    //console.log('+++++++ force update ' + is_force_update);
    //console.log('++++++baseUrl' + baseUrl.asString());
    //  console.log(parameters);

    AsyncStorage.setItem('base_url', baseUrl.asString());
    console.log(
      '++++++++ ' +
        VersionNumber.appVersion +
        '+ ' +
        is_force_update +
        ' ' +
        playstoreUrl,
    );

  }

  render() {
    return <></>;
  }
} 

As you can see in the above code there are two different ways to get parameter data from Firebase remote config, one with forEach loop and another is with getValue key. then save these data in AsyncStorage.setItem. now the important thing is How to trigger this remote config class in your project to do this you can trigger this class at the very first time in App.js as follows

4. How to Trigger remote config in App.js

Check the following App.js code

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
} from 'react-native';

import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import SplashScreen from './js/ui/SplashScreen';
import Dashboard from './js/ui/DashboardScreen';
import LoginScreen from './js/ui/LoginScreen';
import ProfileScreen from './js/ui/ProfileScreen';

import RemoteConfig from './js/firebase/RemoteConfig';

const MainNavigator = createStackNavigator({
  splashScreen: {
    screen: SplashScreen,
    navigationOptions: {
      header: null,
    },
  },
  mainScreen: {
    screen: MainScreen,
    navigationOptions: {
      header: null,
      headerTintColor: '#000000',
      headerBackTitle: null,
    },
  },
  LoginScreen: {
    screen: LoginScreen,
    navigationOptions: {
      header: null,
      headerTintColor: '#000000',
      headerBackTitle: null,
    },
  },
  profileScreen: {screen: ProfileScreen}
});

const Apps = createAppContainer(MainNavigator);

class App extends React.Component {
  render() {
    return (
      <Apps>
        <RemoteConfig />    //<-- Call Remote Config here
      </Apps>
    );
  }
}

export default App;

This will start remote config at the time of Application start. you can see results in console.log()

Hope you will like this article, Please comment out your queries, Thank you 🙂

 

 

 

Related Posts

2 thoughts on “How to implement firebase remote config in React native

  1. Hello,

    I can’t fetch firebase remote config in my react native application.

    remoteConfig().fetchAndActivate()), fetchedRemotely its not working. Can you help in this please.

    await remoteConfig()
    .setDefaults({
    //base_url: CONSTANTS.baseURL,
    })
    .then(() => remoteConfig().fetchAndActivate())

    .then(fetchedRemotely => {
    if (fetchedRemotely) {
    console.log(
    ‘+++Configs were retrieved from the backend and activated.’,
    );
    console.log(fetchedRemotely);
    } else {
    console.log(
    ‘——No configs were fetched from the backend, and the local configs were already activated’,
    );
    }
    });

    1. Hi, Uninstall the previous app & install a new fresh build again it should work. Please let me know if the issue still persists.

      Also, the above code is only to set default values & initialize the firebase.

      You can fetch data using the following code

      //Code to get All parameters from Firebase Remote config
      const parameters = remoteConfig().getAll();
      Object.entries(parameters).forEach($ => {
      const [key, entry] = $;
      console.log(‘–Key: ‘, key);
      console.log(‘–Source: ‘, entry.getSource());
      console.log(‘–Value: ‘, entry.asString());
      console.log(‘——————————–‘);
      });

      //Get Firebase remote config parameters by key
      const baseUrl = remoteConfig().getValue(‘base_url’);

Leave a Reply

Your email address will not be published. Required fields are marked *