Im using Expo example to get the token for the device:
async function registerForPushNotificationsAsync() {
let token;
if (Constants.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== 'granted') {
alert('Failed to get push token for push notification!');
return;
}
token = (await Notifications.getExpoPushTokenAsync()).data;
} else {
alert('Must use physical device for Push Notifications');
}
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
console.log("token -> ", token);
firebase.database().ref('users')
.child(firebase.auth().currentUser.uid)
.set({
expoToken: token
}, { merge: true });
return token;
}
useEffect(() => {
let subscriber;
firebase.auth().onAuthStateChanged((user) => {
if (user && !subscriber) {
registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
subscriber = firebase.firestore()
.collection('users')
.doc(user.uid)
.onSnapshot(documentSnapshot => {
setUser(documentSnapshot.data())
})
}
})
return () => subscriber();
},[])
Im calling my function in useEffect() and im also logging the Token
console.log("token -> ", token);
Im getting two logs
One is the token is undefined and then its logs it again with the token.
The problem is, im trying to save the token to firebase:
firebase.database().ref('users')
.child(firebase.auth().currentUser.uid)
.set({
expoToken: token
}, { merge: true });
But im getting:
[Unhandled promise rejection: Error: Reference.set failed: second argument must be a valid function.]
I think its trying to save the token but the token is undefined at the start and then it gets it.