Skip to main content

push notification with Expo - React Native APP


store expoPushToken in local storage if can't find it,
1. form screen
useEffect => fetchStorage

2. For android, download google-services.json
app.json
"googleServicesFile": "./google-services.json",

3. onSumbmit:
const input = {
...rest,
photos: JSON.stringify(photoUrls),
type: form,
accountId: ACCOUNT_ID,
expoPushToken
}

4. on api: add notification:
const pushTokens = contacts.map(contact => contact.expoPushToken)
pushNotification(pushTokens, body)

5. admin portal:
add/send notification

Test notification:
https://expo.io/notifications

steps:

  1. getting a user's Expo Push Token
  2. calling Expo's Push API with the token when you want to send a notification
  3. responding to receiving the notification in your app (maybe upon opening, you want to jump to a particular screen that the notification refers to)


Apollo Server:
yarn add expo-server-sdk

expo-server-sdk-node





import { Expo } from 'expo-server-sdk'

const pushNotification = (pushTokens, body) => {
// Create a new Expo SDK client
let expo = new Expo()

// Create the messages that you want to send to clents
let messages = []
for (let pushToken of pushTokens) {
// Each push token looks like ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]

// Check that all your push tokens appear to be valid Expo push tokens
if (!Expo.isExpoPushToken(pushToken)) {
console.error(`Push token ${pushToken} is not a valid Expo push token`)
continue
}

// Construct a message (see https://docs.expo.io/versions/latest/guides/push-notifications)
messages.push({
to: pushToken,
sound: 'default',
body: body,
data: { withSome: 'data' }
})
}

// The Expo push notification service accepts batches of notifications so
// that you don't need to send 1000 requests to send 1000 notifications. We
// recommend you batch your notifications to reduce the number of requests
// and to compress them (notifications with similar content will get
// compressed).
let chunks = expo.chunkPushNotifications(messages)
let tickets = []
;(async () => {
// Send the chunks to the Expo push notification service. There are
// different strategies you could use. A simple one is to send one chunk at a
// time, which nicely spreads the load out over time:
for (let chunk of chunks) {
try {
let ticketChunk = await expo.sendPushNotificationsAsync(chunk)
console.log(ticketChunk)
tickets.push(...ticketChunk)
// NOTE: If a ticket contains an error code in ticket.details.error, you
// must handle it appropriately. The error codes are listed in the Expo
// documentation:
// https://docs.expo.io/versions/latest/guides/push-notifications#response-format
} catch (error) {
console.error(error)
}
}
})()
}

export { pushNotification }

Android:


firebase for  push notification

Using FCM for Push Notifications

1. Client Setup:
{
  ...
  "android": {
    "googleServicesFile": "./google-services.json",
    ...
  }
}
2. Uploading Server Credentials

expo push:android:upload --api-key <your-token-here>
AAAAIckC1Mc:APA91bFqM8-bMbBChBXmEamBjai_EOsCOp0jNnRrVJhmQT1pVD7jJXQYdvceCOwXfKthN6wGoHt4L3x3mUIXMwYxgMpsMbV_pvBtChRA8j5Bvn5F2hkkOVHy-65KTP9kSsV-zvDrI4uz

Comments

Popular posts from this blog

for loop in javascript - promise - .eslintrc for "for of"

the vast majority of cases  map ,  forEach ,  find  etc. can be used.  async function printFiles () { const files = await getFilePaths(); await Promise.all(files. map (async (file) => { const contents = await fs.readFile(file, 'utf8') console.log(contents) })); } const inventory = [ { name : 'apples' , quantity : 2 } , { name : 'bananas' , quantity : 0 } , { name : 'cherries' , quantity : 5 } ] ; const result = inventory . find ( ( { name } ) => name === 'cherries' ) ;   function getFirstMatching(array) { for (let item of array) { const result = heavyTransform(item); if (result) { return result; } } } Specifically this shuts down the whole no-restricted-syntax. If you want to cherry-pick, here is the current definition: 'no-restricted-syntax' : [ 'error' , { selector : 'ForInStatement' , message...

Apollo client - cache APIs - auto update cache - erase cache - reactive variables - deletion - addition

Apollo Client 3  Local only fields Reactive Variables const cache = new InMemoryCache ( { typePolicies : { Todo : { // If one of the keyFields is an object with fields of its own, you can // include those nested keyFields by using a nested array of strings: keyFields : [ "date" , "user" , [ "email" ] ] , } } , } ) ; This internal data is intended to be easily  JSON-serializable , so you can take a snapshot with  cache.extract() , save it somewhere, and later restore with  cache.restore(snapshot) . Here’s a mutation called  EditTodo  that returns the new  todo  value in the mutation response. mutation EditTodo ( $id : Int ! , $text : String ! ) { editTodo ( id : $id , text : $text ) { success todo { # <- Returning it here id text completed } error { ... on TodoNotFoundError { message } ... on TodoValidationE...

window.URL.createObjectURL is not (yet) available in jest-dom - testing scenario

Since  window.URL.createObjectURL  is not (yet) available in jest-dom, you need to provide a mock implementation for it. Don't forget to reset the mock implementation after each test. describe ( "your test suite" , () => { window . URL . createObjectURL = jest . fn (); afterEach (() => { window . URL . createObjectURL . mockReset (); }); it ( "your test case" , () => { expect ( true ). toBeTruthy (); }); });