Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only one device is receiving the notification #2423

Open
fjerbi opened this issue Sep 4, 2024 · 0 comments
Open

Only one device is receiving the notification #2423

fjerbi opened this issue Sep 4, 2024 · 0 comments

Comments

@fjerbi
Copy link

fjerbi commented Sep 4, 2024

I'm having a weird behavior in my APP while working on a push notification functionality that sends notifications to a team when a camping is created.

I console logged, and notifications were sent to all team, but only the camping creator receives the notification.

I'm running two emulators, I tried the same thing using messaging in the Firebase console, and only one emulator device receives the notification.

Did anyone faced similar situation?

const postSubmit = async () => {
    const userIds = team;
    const campData = {
      meetingPoint,
      description: `You've been invited to a camping at ${selectedCamping?.name}`,
      startingDate,
      endingDate,
    };
  
    if (selectedCamping && selectedCamping._id) {
      setCamping(selectedCamping._id.toString());
    } else {
      console.error('Selected camping is invalid:', selectedCamping);
      return;
    }
  
    setLoading(true);
  
  await  axios
      .post(`API`, {
        sender: user.user.id,
        team: userIds,
        objects,
        camping,
        meetingPoint,
        description: `You've been invited to a camping at ${selectedCamping?.name}. Click here to view details.`,
        users: userIds,
        startingDate: selectedDates.start,
        endingDate: selectedDates.end,
        notes,
      })
      .then(async function (response) {
        console.log(camping);
        SuccessAdventureCreation(selectedCamping?.name);
  
        // After successful adventure creation, send notifications
        for (const userId of userIds) {
          try {
            // Assuming each user has an associated FCM token
            const token = await getTokenForUser(userId); // function to get the user's FCM token
  
            const notificationData = {
              "message": {
                "token": token,
                "notification": {
                  "title": "New Invitation",
                  "body": `You've been invited Check it out!`,
                },
                "data": {
                  "campId": `${response.data.campId}`, // Assuming the response contains an campId
                },
              },
            };
  
            await axios.post(
              `https://fcm.googleapis.com/v1/projects/app-id/messages:send`,
              notificationData,
              {
                headers: {
                  "Content-Type": "application/json",
                  "Authorization": `Bearer ${API_KEY}`, 
                },
              }
            );
  
            console.log(`Notification sent to user ${userId}`);
          } catch (notificationError) {
            console.error(`Failed to send notification to user ${userId}:`, notificationError);
          }
        }
  
        setTimeout(() => {
          setLoading(false);
          navigation.goBack();
        }, 1000);
      })
      .catch(function (error) {
        console.log(error.response.data);
        FailToastFavorite("Error occurred, please try again!");
        setLoading(false);
      });
  };

App.tsx

useEffect(() => {
  PushNotification.createChannel(
    {
      channelId: "my-channel", // Same as channelId in LocalNotification
      channelName: "Test Channel",
      channelDescription: "A channel to categorize your notifications",
      soundName: "default", // Optional
      importance: 4, // High importance
      vibrate: true, // Optional
    },
    (created) => console.log(`createChannel returned '${created}'`)
  );

  if (requestUserPermission()) {
    messaging()
      .getToken()
      .then((token) => {
        console.log(token);
      })
      .catch((error) => {
        console.error("Error getting token: ", error);
      });
  } else {
    console.log('Permission not granted');
  }

  messaging()
    .getInitialNotification()
    .then(async (remoteMessage) => {
      if (remoteMessage) {
        console.log(remoteMessage.notification);
      }
    })
    .catch((error) => {
      console.error("Error getting initial notification: ", error);
    });

  messaging().onNotificationOpenedApp((remoteMessage) => {
    console.log(remoteMessage.notification);
  });

  messaging().setBackgroundMessageHandler(async (remoteMessage) => {
    if (remoteMessage.notification) {
      LocalNotification.showNotification(
        remoteMessage.notification.title,
        remoteMessage.notification.body
      );
    }
  });

  messaging()
  .getInitialNotification()
  .then(async (remoteMessage) => {
    if (remoteMessage && remoteMessage.notification) {
      LocalNotification.showNotification(
        remoteMessage.notification.title,
        remoteMessage.notification.body
      );
    }
  })
  .catch((error) => {
    console.error("Error getting initial notification: ", error);
  });

  messaging().onNotificationOpenedApp((remoteMessage) => {
    if (remoteMessage.notification) {
      LocalNotification.showNotification(
        remoteMessage.notification.title,
        remoteMessage.notification.body
      );
    }
  });
  const unsubscribe = messaging().onMessage(async (remoteMessage) => {
    if (remoteMessage.notification) {
      LocalNotification.showNotification(
        remoteMessage.notification.title,
        remoteMessage.notification.body
      );
    }
  });

  return unsubscribe;
}, []);
@fjerbi fjerbi changed the title Firebase Push Notification : Only one device is receiving the notification Only one device is receiving the notification Sep 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant