question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Any way to use React Context within onRegister?

See original GitHub issue

I need to save the returned fcm/apns token to the the app context by using useContext so that later on my app may access that same context and send the token to the api if the user logs in.

I tried doing the following, but it seems to be causing errors:

function PushNotificationHandler() {
  const { setTokenInformation } = useContext(AppContext);
  const [taskAlertsMarkAsRead] = useMutation(taskAlertsMarkAsReadMutation, {
    refetchQueries: [{ query: taskAlertsUnreadQuery }],
  });

  function onNotification(notification) {
    console.log('NotificationHandler:', notification);
    if (notification.userInteraction) {
      if (notification.data.taskId) {
        taskAlertsMarkAsRead({ variables: { taskId: notification.data.taskId } });
      }
      const redirectTo = JSON.parse(notification.data.redirectTo);
      reset(redirectTo);
    } else {
      PushNotification.localNotification({
        id: 0,
        largeIcon: 'ic_launcher',
        smallIcon: 'ic_notification',
        vibrate: true,
        vibration: 300,
        channelId: 'rn-push-notification-channel-id-4-ding-300',
        onlyAlertOnce: false,
        invokeApp: true,
        title: notification.data.title,
        message: notification.data.body,
        userInfo: notification.data,
        playSound: true,
        soundName: 'default',
        number: 10,
      });
    }
  }

  function onRegister(tokenInfo) {
    console.log('NotificationHandler:', tokenInfo);
    setTokenInformation(tokenInfo);
  }

  function onAction(notification) {
    console.log('Notification action received:');
    console.log(notification.action);
    console.log(notification);

    if (notification.action === 'Yes') {
      PushNotification.invokeApp(notification);
    }
  }

  // (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
  function onRegistrationError(err) {
    console.log('Error', err);
  }
}

const handler = PushNotificationHandler();

PushNotification.configure({
  // (optional) Called when Token is generated (iOS and Android)
  onRegister: handler.onRegister,

  // (required) Called when a remote or local notification is opened or received
  onNotification: handler.onNotification,

  // (optional) Called when Action is pressed (Android)
  onAction: handler.onAction,

  // (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
  onRegistrationError: handler.onRegistrationError,

  // IOS ONLY (optional): default: all - Permissions to register.
  permissions: {
    alert: true,
    badge: true,
    sound: true,
  },

  // Should the initial notification be popped automatically
  // default: true
  popInitialNotification: false,

  /**
   * (optional) default: true
   * - Specified if permissions (ios) and token (android and ios) will requested or not,
   * - if not, you must call PushNotificationsHandler.requestPermissions() later
   */
  requestPermissions: true,
});

Is there possibly a better way to do it? I need help badly. Thank you.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:9

github_iconTop GitHub Comments

1reaction
rarenatoecommented, Nov 11, 2020

@Dallas62 It’s a react hook.

0reactions
rarenatoecommented, Oct 17, 2022

Closing since this is issue is too old and dusty

Read more comments on GitHub >

github_iconTop Results From Across the Web

Context - React
Context provides a way to pass data through the component tree without having to pass props down manually at every level. In a...
Read more >
How to use React Context like a pro - Devtrium
I'm sharing them in this article so you can start using React Contexts like a pro! As a quick reminder before we start,...
Read more >
Injectable services in React – The Guild
Let me explain. So far, when we wanted a component to use an external service, we would simply implement it in a separate...
Read more >
useForm - register - Simple React forms validation
This method allows you to register an input or select element and apply validation rules to React Hook Form. Validation rules are all...
Read more >
How to use React Context effectively - Kent C. Dodds
How to create and expose React Context providers and consumers. ... React Context can help you manage state well in any React application....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found