DEV Community

Subramanya Chakravarthy
Subramanya Chakravarthy

Posted on • Updated on

React Native Local Notifications In Expo

Notifications provide short, timely information about events in your app while it's not in use. Every app wants it users to engage with their app for more time. I think Notifications are the best way to remind user gently about the presence and provide some actionable stuff like If the app is based about workouts, you can remind user not to loose streak.

I am using expo to demonstrate Local Notifications. In order to show notifications to user, firstly we have to take permission from the user

Here is the Source Code to follow along

In order to ask permissions to use expo I use this beautiful async function which returns a Boolean status of notifications

import * as Notifications from "expo-notifications";
import * as Permissions from "expo-permissions";

askPermissions = async () => {
  const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
  let finalStatus = existingStatus;
  if (existingStatus !== "granted") {
    const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
    finalStatus = status;
  }
  if (finalStatus !== "granted") {
    return false;
  }
  return true;
};

There are two ways we can use Local Notifications, one is immediate notification and other is scheduled Notification

Let's create a function which sends immediate Notification

import * as Notifications from "expo-notifications";

sendNotificationImmediately = async () => {
  let notificationId = await Notifications.presentLocalNotificationAsync({
    title: 'This is crazy',
    body: 'Your mind will blow after reading this',
  });
  console.log(notificationId); // can be saved in AsyncStorage or send to server
};

import Notifications first and then calling presentLocalNotificationAsync from Notifications and it takes LocalNotification object which contains title, body, data, and some other options for android and ios. It returns the Notification Id which can be used to dismiss programmatically.

You can dismiss Notifications in two ways, One dismiss All Notifications or dismiss Notification By id

To dismiss all notifications call Notifications.dismissAllNotificationsAsync()

To dismiss Notification by id call Notifications.dismissNotificationAsync(localNotificationId)

Now Let's create a function which schedules Notification

scheduleNotification = async () => {
  let notificationId = Notifications.scheduleLocalNotificationAsync(
    {
      title: "I'm Scheduled",
      body: 'Wow, I can show up even when app is closed',
    },
    {
      repeat: 'minute',
      time: new Date().getTime() + 10000,
    },
  );
  console.log(notificationId);
};

The scheduleLocalNotificationAsync takes two arguments, first is notification object and second one takes schedulingOptions object. The options are whether to repeat or not and other is at what time notification should pop. In above example I'm using repeat every minute and then scheduling notification after 10 secs from current time.

Now you have scheduled notification, but what if you want to cancel a scheduled one. It's the same as dismissing notifications. You can dismiss all scheduled notifications by calling Notifications.dismissAllNotificationsAsync() or Notifications.cancelScheduledNotificationAsync(localNotificationId) based on notification id.

If you have any questions shoot me a direct message in twitter

Edit: Updated imports (Thanks to @majklfly )

Top comments (8)

Collapse
 
webuijorgegl profile image
Jorge Suarez

This article needs a little update.

Notifications.scheduleNotificationAsync({
content: {
title: 'title here',
body: 'text here',
data: {
url: screen
//more data here
}
},
trigger: {
repeats: false,
seconds: 10,
channelId: screen
}
});

Do you know the way to trigger a notification on a specific date in the future?

Collapse
 
chakrihacker profile image
Subramanya Chakravarthy

you can do something like this

trigger: {
    seconds: calculateSecondsToSpecifiedDate(date)
}
Enter fullscreen mode Exit fullscreen mode

and calculateSecondsToSpecifiedDate will return seconds

Hope this helps you

Collapse
 
webuijorgegl profile image
Jorge Suarez

Yes... a few days ago I did this. Thank you.

Collapse
 
majklfly profile image
Michal Mucha

Hello Subramanya, I would like couple changes in your code.

1) import * as Notifications from "expo-notifications";
import * as Permissions from "expo-permissions";

2) if (existingStatus !== "granted") {
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
finalStatus = status;
}
if (finalStatus !== "granted") {
return false;
} ---> the granted is a string...

apart from that...thank you helping me bringing the idea :)

Collapse
 
saralhossain profile image
Alamdar Hussain

what if user doesn't allowed?? jokes apart, Actually I want it should be repeat like if I want it once, like if he logged in and on basis of other action performed where do I include code, like if he logged in send notification and stop??

Collapse
 
believegautam profile image
believe-gautam

is there any way can get the user clicked on the notification title or another button
something like this problem Click Here

Collapse
 
saralhossain profile image
Alamdar Hussain

btw it was good explaination :)

Collapse
 
nivethamani12 profile image
Nivetha Mani

Can we do Scheduled a push Notification based on expo firebase