4

I use React Native FCM for messaging, and when the user logs out the application I want to delete the FCM token so that the user doesn't get Notified again.

Below is my code for logout.

_signOutAsync = async () => {
    this.logoutEvent()
    API.post('customer/auth/logout', null, {
      headers: {
        Authorization:
          'Bearer ' + (await AsyncStorage.getItem(Config.ACCESS_TOKEN))
      }
    }).then((response) => {
      console.log(response)
    })
    this.clearData()
  }

Thanks.

zidniryi
  • 1,212
  • 3
  • 15
  • 36

4 Answers4

3

Simply add below given code in your logout function -

for react-native-firebase <= v5.x.x

firebase.messaging().deleteToken()

for > 5.x.x or using @react-native-firebase/messaging

import messaging from '@react-native-firebase/messaging';

messaging().deleteToken()
Kailash
  • 777
  • 4
  • 19
  • 3
    this doesn't work as even after deleting the token it will generate the same FCM token again. – Deepak Kumar Oct 30 '20 at 08:27
  • If you face this issue, then refer to my solution. – Shyam Jan 25 '21 at 22:41
  • 1
    this didn't work for me, after deleteToken, logging in and and calling getToken would not log you back in. Instead, using unregisterDeviceForRemoteMessages / registerDeviceForRemoteMessages worked. See https://rnfirebase.io/reference/messaging#registerDeviceForRemoteMessages – Ghan Aug 06 '21 at 19:02
0
await firebase.messaging().deleteToken();

is the solution.

BUT, if you get the same token even after deleting, install the npm package react-native-restart, and do the below step to get a new token

messaging()
            .deleteToken(undefined,'*')
            .then(() => {
                RNRestart.Restart();
Shyam
  • 633
  • 7
  • 13
0

Install the npm package react-native-restart and Simply call like this:

const logoutAndClearAsyncStorage = async () => {
  try {
    await AsyncStorage.clear()
    await firebase.messaging().deleteToken().then(() => {
      RNRestart.Restart()
      navigation.replace('LoginStack', { screen: 'WelcomeScreen' });
    })
  } catch (error) {
    console.log(error, 'logout')
  }
};
Dharman
  • 30,962
  • 25
  • 85
  • 135
0

Recently I try to use FCM too, and found the issue usually due to the function comes from, i.e. where to import the functions.

I think you already have installed firebase package, call the function below will trigger delete token on firebase.

import { getMessaging, deleteToken } from 'firebase/messaging';

const messaging = getMessaging(firebaseApp);
deleteToken(messaging);
Chiu
  • 374
  • 2
  • 10
  • Please read [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others. – Saeed Zhiany Jul 04 '22 at 02:48