TypeError Object is not a constructor (evaluating new_pubnubReact.default') - react-native

I am new to react native and am trying to create push notifications for android.
I am using the following tutorial from PubNub.
PubNub tutorial
When I run my app in the android studio emulator after finishing the tutorial I get the following error.
Not quite sure what it means of how to fix it as when I google the problem nothing comes up.
Here is my code
import React from 'react';
import PushNotificationIOS from 'react-native';
import PubNubReact from 'pubnub-react';
const PushNotification = require('react-native-push-notification');
export default class App extends React.Component {
constructor(props) {
super(props);
this.pubnub = new PubNubReact({
publishKey: 'YOUR_PUBNUB_PUBLISH_KEY_HERE',
subscribeKey: 'YOUR_PUBNUB_SUBSCRIBE_KEY_HERE'
});
this.pubnub.init(this);
PushNotification.configure({
// Called when Token is generated.
onRegister: function(token) {
console.log( 'TOKEN:', token );
if (token.os == "ios") {
this.pubnub.push.addChannels(
{
channels: ['notifications'],
device: token.token,
pushGateway: 'apns'
});
// Send iOS Notification from debug console: {"pn_apns":{"aps":{"alert":"Hello World."}}}
} else if (token.os == "android"){
this.pubnub.push.addChannels(
{
channels: ['notifications'],
device: token.token,
pushGateway: 'gcm' // apns, gcm, mpns
});
// Send Android Notification from debug console: {"pn_gcm":{"data":{"message":"Hello World."}}}
}
}.bind(this),
// Something not working?
// See: https://support.pubnub.com/support/solutions/articles/14000043605-how-can-i-troubleshoot-my-push-notification-issues-
// Called when a remote or local notification is opened or received.
onNotification: function(notification) {
console.log( 'NOTIFICATION:', notification );
// Do something with the notification.
// Required on iOS only (see fetchCompletionHandler docs: https://reactnative.dev/docs/pushnotificationios)
// notification.finish(PushNotificationIOS.FetchResult.NoData);
},
// ANDROID: GCM or FCM Sender ID
senderID: "sender-id",
});
}
}

pubnub-react library has been completely changed in version 2.0.0. It no longers includes pubnub JavaScript SDK by default so you have to install it as well.
Here is the link to new PubNub React repository, and in the README.md file you can find examples on how to use it.
If you want to use the older version that is compatible with the tutorial/blog post you may be reading, please install the older version of the PubNub React SDK like so:
$ npm install pubnub-react#1
To summarize the changes, pubnub-react now uses Context and Hooks API to propagate PubNub instance deep into the children tree.
Provider
You need to include the provider somewhere top in the component tree.
import React from 'react'
import PubNub from 'pubnub'
import { PubNubProvider } from 'pubnub-react'
const pubnub = new PubNub({}) // PubNub configuration
export const App = () => {
return <PubNubProvider client={pubnub}>
<Child />
</PubNubProvider>
}
Consumer
To use the PubNub instance somewhere else, you can now just use the usePubNub hook.
import { usePubNub } from 'pubnub-react'
export const Child = () => {
const pubnub = usePubNub()
return <div>I am using PubNub!</div>
}

Related

Expo-notifications background notification reception handling

I am using expo-notifications package in react native (expo) to handle incoming notifications. I am getting notification correctly when the app is in background and foreground - for sending notifications I am using 'expo-server-sdk' package in the backend. I can handle foreground notification reception using addNotificationReceivedListener() function from expo-notification package.For handling background notification reception in the expo documentation (link: - https://docs.expo.dev/versions/latest/sdk/notifications/#handling-incoming-notifications-when-the-app-is-1) they are saying we can use expo-task-manager library to handle it. The code that i have written by referring expo documentation is given below.
...
import * as Notifications from 'expo-notifications';
import * as TaskManager from 'expo-task-manager';
...
//This code is written in root file and outside any react component
const BACKGROUND_NOTIFICATION_TASK = 'BACKGROUND-NOTIFICATION-TASK';
TaskManager.defineTask(
BACKGROUND_NOTIFICATION_TASK,
({ data, error, executionInfo }) =>{
if(error){
console.log('error occurred');
}
if(data){
console.log('data-----',data);
}
})
//This code is written in App.js root component
useEffect(() => {
Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
return()=>{
Notifications.unregisterTaskAsync(BACKGROUND_NOTIFICATION_TASK);
}
},[])
Also in the expo documentation. they say that this background task will not work with expo go app. so O executed expo run:android and build the app into my physical android device. Even After doing all this, When a notification arrives this task is not running and I am not getting any output in the console log from the code console.log('data-----',data); neither getting output for the code console.log('error occurred'); which means 'BACKGROUND-NOTIFICATION-TASK' is not getting executed when notification comes when app is in background. Can anyone please tell me what the problem is?
Basically, the only mistake you made was to call
Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK)
inside useEffect which I am guessing is inside a react component, this code must be written outside the react component as you did with TaskManager.defineTask...
Take a look at this simple App.js example for further clarity
import { StyleSheet, View } from "react-native";
import * as Notifications from "expo-notifications";
import * as TaskManager from "expo-task-manager";
const BACKGROUND_NOTIFICATION_TASK = "BACKGROUND-NOTIFICATION-TASK";
TaskManager.defineTask(
BACKGROUND_NOTIFICATION_TASK,
({ data, error, executionInfo }) => {
if (error) {
console.log("error occurred");
}
if (data) {
console.log("data-----", data);
}
}
);
Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
export default function App() {
return <View style={styles.container}></View>;
}
const styles = StyleSheet.create({
container: {
flex: 1
},
});
No need for useEfect

How to use "promptAsync" from expo-auth-session, old library used in video tutorial was deprecated

I have been following the tinder 2.0 react native tutorial https://youtu.be/qJaFIGjyRms At 1:04:00 he sets the sign in method to: "await Google.logInAsync()" but I have noticed the google app auth library used in the video is now deprecated, I am redirected to use expo auth session instead but I notice there is a slight difference, where they used "await Google.logInAsync()" I must put "promptAsync" instead, when I do this I get the error promptAsync is undefined, I try with google.loginasync and get the same error that it is still undefined, what should I do? screenshot
code:
import React, { createContext, useContext } from 'react'
//import * as Google from 'expo-auth-session/providers/google';
import * as Google from 'expo-google-app-auth';
const AuthContext = createContext({});
const config = {
androidClientId:
'236293699216-9a0nknjdq7ie79h40iubg0tddokgogfv.apps.googleusercontent.com',
iosClientId:
'236293699216-6jdpm0rd6kn5d0qlbh1vgva5afgbqgib.apps.googleusercontent.com',
scopes: ["profile", "email"],
permissions: ["public_profile","email", "gender", "location"],
}
export const AuthProvider = ({ children}) => {
const signInWithGoogle = async() => {
await Google.logInAsync(config).then(async (logInResult) => {
if (logInResult.type === "success") {
// login
}
});
};
return (
<AuthContext.Provider
value={{
user: null,
signInWithGoogle
}}
>
{children}
</AuthContext.Provider>
)
}
export default function useAuth() {
return useContext(AuthContext);
}
I sought help on the forum that belongs to the maker of the video and other people had come across the same issue, one person recommended to go into package.json find the installed dependencies and change “expo-google-app-auth” from “^10.0.0” to “~9.0.0” and then npm I in the terminal, I have done this and I'm now getting the error “no such file or directory /Users/shangefagan/twinder-3/node_modules/expo-google-app-auth/node-modules/react-native/package.json” I have changed it back to “^10.0.0” but still getting the same error, screenshot
do I just npm uninstall expo-google-app-auth and try to use expo-auth-session as I was originally trying? if so What is the correct way to use promptAsync from the expo-auth-session library
I check the docs for both libraries, expo google app auth: https://docs.expo.dev/versions/v43.0.0/sdk/google/ and expo auth session: https://docs.expo.dev/versions/latest/sdk/auth-session/ but I am unsure exactly how to use the new login method "promptAsync"
To use promptAsync you have to use the package expo-auth-session. Like you said expo-google-app-auth is deprecated.

useURL hook expo-linking for background app

The expo-linking React Native package has a hook named useURL that isn't working for me when the app is in the background. From the docs it Returns the initial URL followed by any subsequent changes to the URL. The problem I'm having with my managed expo app is that the hook doesn't work when the app is already open in the background. Here is the hook:
export default function App() {
const isLoadingComplete = useCachedResources();
const url = Linking.useURL();
useEffect(() => {
Alert.alert(url ? url.substring(20) : 'null');
}, [url]);
if (!isLoadingComplete) {
return null;
} else {
return (
...
);
}
}
If I open the URL exp://exp.host/#myprofile/myproject?a=bwhen the app is closed, I get an Alert as expected. If the app is in the background, the Alert doesn't go off. I've tested on an iOS emulator and a physical Android. Any solutions? Note that similar problems happen with Linking.addEventListener().

Not receiving fcm message when app is close in Android with react-native-firebase

I followed the steps mentioned here.
Now, I'm receiving messages when the app is in foreground via firebase.messaging().onMessage and in the background, via a headless task I defined according to the same guide, but I don't receive messages when the app is closed
I am using one plus 6, where I even disabled the Battery optimize option for my phone, tried installing a signing build but none of it is working.
This is my bgMessaging.js
import firebase from 'react-native-firebase';
// Optional flow type
import type { RemoteMessage } from 'react-native-firebase';
export default async (message: RemoteMessage) => {
const channel = new firebase.notifications.Android.Channel('channel-id', 'channel-Name', firebase.notifications.Android.Importance.Max)
.setDescription('Description');
firebase.notifications().android.createChannel(channel);
const localNotification = new firebase.notifications.Notification()
.setNotificationId(message.messageId)
.setTitle("Title")
.setSubtitle('Test')
.setBody("Body")
.setData(message.data)
.android.setChannelId('channel-id')
.android.setAutoCancel(false)
.android.setPriority(firebase.notifications.Android.Priority.High);
firebase.notifications().displayNotification(localNotification);
return Promise.resolve();
}
Even added this on AndroidManifest.xml
<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
Am I missing anything on native side?
You can go to http://pushtry.com/ and set the jSON as :
{
"to":FCM_TOKEN
"notification": {
"body": "body",
"title": "title"
},
"priority":'high'
}

How to pass data to push notification with react native

Im using
React Native Push Notification https://github.com/zo0r/react-native-push-notification
How can I pass my pushMessage(chat) into the notification?
I have this onNotification and PushNotificationIOS error when received push message from server.
error on device
which part should I work on?
ps: im not understand how this work -> notification.finish(PushNotificationIOS.FetchResult.NoData);
App.js
--------
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log( 'NOTIFICATION:', notification );
// process the notification
// required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
});
class App extends Component{
componentDidMount(){
const connection = signalr.hubConnection('https://api.abc.com');
const proxy = connection.createHubProxy('chatHub');
proxy.on('pushMessage', (chat) => {
PushNotification.localNotificationSchedule({
message: "My Notification 1",
date: new Date(Date.now())
});
});
}
}
PushNotificationIOS is an API provided by react-native so maybe you import it from react-native like so
import { PushNotificationIOS } from 'react-native'
PushNotification uses PushNotificationIOS. You have to add and import it.
Do the following.
In the console, run this if using Yarn: yarn add #react-native-community/push-notification-ios...
... or run this if using NPM: npm install #react-native-community/push-notification-ios
Then, in your file where you use PushNotification, add this line among your other imports:
import PushNotificationIOS from "#react-native-community/push-notification-ios"