Arham Shahzad
Arham Shahzad

Reputation: 141

How to force users to update the app using react native

I have updated my app on app and play store and I want to force my app users to update the new version of app in App store and playstore.

Upvotes: 14

Views: 35900

Answers (5)

Nafees
Nafees

Reputation: 1034

I am using this library github.com/kimxogus/react-native-version-check

but it has some bugs so I had to update node modules and added await before two functions VersionCheck.getAppStoreUrl and VersionCheck.getPlayStoreUrl

let me share the code

const checkAppVersionFirstThenProceed = async () => {
  try {
    const latestVersion = Platform.OS === 'ios'
      ? await fetch(`https://itunes.apple.com/in/lookup?bundleId=com.abc`)
          .then(r => r.json())
          .then((res) => { return res?.results[0]?.version })
      : await VersionCheck.getLatestVersion({
          provider: 'playStore',
          packageName: 'com.abc',
          ignoreErrors: true,
      });

    const currentVersion = VersionCheck.getCurrentVersion();
    console.log(currentVersion , "currentVersion" , latestVersion)

    if (latestVersion > currentVersion) {
      Alert.alert(
        'Update Required',
        'A new version of the app is available. Please update to continue using the app.',
        [
          {
            text: 'Update Now',
            onPress: async () => {
              Linking.openURL(
                Platform.OS === 'ios'
                  ? await VersionCheck.getAppStoreUrl({ appID: 'xxxxxxxxxx' })
                  : await VersionCheck.getPlayStoreUrl({ packageName: 'yourpackagename' })
              );
            },
          },
        ],
        { cancelable: false }
      );
    } else {
    proceedWithApp();
    }
  } catch (error) {
    console.error('Error checking app version:', error);
  }
};

In node_modlues getstoreUrl.js

export const getAppStoreUrl = async (
      option: GetAppStoreUrlOption
    ): Promise<string> => {
      const opt = option || {};
      try {
        if (isNil(opt.appID)) {
          throw new Error('appID is empty.');
        }
    
    
        if (!opt.country) {
          opt.country = await getVersionInfo().getCountry();
        }
    
    
        const countryCode = opt.country ? `${opt.country}/` : '';
    
        // removed country code and mt=8 added
        return `itms-apps://apps.apple.com/app/id${opt.appID}?mt=8`;
      } catch (e) {
        console.error(e)
        if (opt.ignoreErrors) {
          console.warn(e); // eslint-disable-line no-console
        } else {
          throw e;
        }
      }
    };

cheers!

Upvotes: 0

Nate
Nate

Reputation: 535

For future readers.

If you are using Expo managed workflow, install this package react-native-version-check-expo using yarn add react-native-version-check-expo or npm install react-native-version-check-expo.

Consult the package documentation on Github for usage guidelines.

Upvotes: 2

Syed Amir Ali
Syed Amir Ali

Reputation: 1011

import VersionCheck from 'react-native-version-check';

i have used version check lib for this purpose and approach i used is below. if version is lower i'm opening a modal on which an update button appears, and that button redirects to app store/google play

  componentDidMount() {
this.checkAppUpdate();
}


  checkAppUpdate() {
VersionCheck.needUpdate().then(res => {
  if (res.isNeeded) {
    setTimeout(() => {
      this.setState({openModal: true});
    });
  }
});
}

  updateApp = () => {
VersionCheck.getStoreUrl({
  appID: 'com.showassist.showassist',
  appName,
})
  .then(url => {
    Linking.canOpenURL(url)
      .then(supported => {
        if (!supported) {
        } else {
          return Linking.openURL(url);
        }
      })
      .catch(err => console.error('An error occurred', err));
  })
  .catch(err => {
    console.log(`error is: ${err}`);
  });
 };

Upvotes: 2

Hp Sharma
Hp Sharma

Reputation: 379

I'm using react-native-version-check-expo library to achieve this. Working fine for me.

Upvotes: 0

Kaushik
Kaushik

Reputation: 981

You can check for the App Store / Play Store version of your app by using this library react-native-appstore-version-checker.

In expo app you can get the current bundle version using Constants.nativeAppVersion. docs.

Now in your root react native component, you can add an event listener to detect app state change. Every time the app transitions from background to foreground, you can run your logic to determine the current version and the latest version and prompt the user to update the app.

 import { AppState } from 'react-native';


 class Root extends Component {

   componentDidMount() {
     AppState.addEventListener('change', this._handleAppStateChange);
   }



   _handleAppStateChange = (nextState) => {
     if (nextState === 'active') {

        /**
                Add code to check for the remote app version.
                Compare it with the local version. If they differ, i.e.,
                (remote version) !== (local version), then you can show a screen,
                with some UI asking for the user to update. (You can probably show
                a button, which on press takes the user directly to the store)
         */


     }
    }



   componentWillUnmount() {
      AppState.removeEventListener('change', this._handleAppStateChange);

   }

}

Upvotes: 6

Related Questions