Why does Pusher update the UI only after navigating to another tab? - mongodb

I used pusher to add real-time updates to my web app. Like if a user hits the like button on a post, the number of likes increases instantaneously in the UI.
That works fine when I run the app locally (illustrative GIF).
But when I deployed the app to Vercel, Pusher doesn't update the UI, unless I navigate to another tab and then return back to my app tab (GIF).
Vercel logs show that everything works as expected. The React component subscribes properly to Pusher channel and gets the new data. However, the UI never updates while I'm viewing the tab.
// Setting up pusher
import Pusher from "pusher";
const pusher = new Pusher({
appId: PUSHER_APP_ID,
key: PUSHER_KEY,
secret: PUSHER_SECRET,
cluster: us2,
useTLS: false,
});
export default pusher;
// Subscribing the component to Pusher channel
useEffect(
function subscribeToPusher() {
const pusher = new Pusher(PUSHER_KEY, {
cluster: us2,
forceTLS: true,
});
const channel = pusher.subscribe("reviews");
channel.bind("updated", updateReview);
},
[]
);
// Listen to MongoDB's ChangeStream
changeStream.on("change", async (change) => {
console.log("change: ", change);
switch (change.operationType) {
case "update": {
const document = change.fullDocument;
pusher.trigger(collectionName, "updated", document);
break;
}
}
});
Note: the deployed version works as expected when I run npm run dev locally which is a bit strange.

It was Vercel. It worked once I tried Heroku.

Related

Detect if user is connected to firebase app

I want to implement an "isActive" feature on my app that is built using firebase firestore. I am using firebase functions along with authentication in my React App.
Is there a way of detecting if the user is "active" or "inActive" on my app by triggering a cloud function when they login or disconnect to the app?
If i can determine this i would store the value in firestore and handle it in the frontend to display a UI.
Thanks
I see two aspects to the question here:
Auth state: You want to track the logged-in duration of the user.
Focus state: You want to track when the user is active on the app.
For #1, you will have to listen to the auth state changes, and you may also want to change your auth state persistence strategy accordingly. From https://firebase.google.com/docs/auth/web/auth-state-persistence:
Enum
Value
Description
firebase.auth.Auth.Persistence.LOCAL
'local'
Indicates that the state will be persisted even when the browser window is closed or the activity is destroyed in React Native. An explicit sign out is needed to clear that state. Note that Firebase Auth web sessions are single host origin and will be persisted for a single domain only.
firebase.auth.Auth.Persistence.SESSION
'session'
Indicates that the state will only persist in the current session or tab, and will be cleared when the tab or window in which the user authenticated is closed. Applies only to web apps.
firebase.auth.Auth.Persistence.NONE
'none'
Indicates that the state will only be stored in memory and will be cleared when the window or activity is refreshed.
import { getAuth, setPersistence, signInWithRedirect, inMemoryPersistence, GoogleAuthProvider } from "firebase/auth";
const auth = getAuth();
setPersistence(auth, inMemoryPersistence)
.then(() => {
const provider = new GoogleAuthProvider();
// In memory persistence will be applied to the signed in Google user
// even though the persistence was set to 'none' and a page redirect
// occurred.
return signInWithRedirect(auth, provider);
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
});
You don't need a cloud function for th
For #2, you might want to check out this blog. https://javascript.plainenglish.io/validate-your-apps-session-on-focus-892f610f7e23.
import { useLocation } from '#reach/router';
import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
export function WindowFocusHandler() {
const dispatch = useDispatch()
const location = useLocation()
useEffect(() => {
window.addEventListener("focus", onFocus)
return () => {
window.removeEventListener("focus", onFocus)
}
}, [])
const onFocus = () => dispatch(session.effects.checkSessionOnFocus(location))
return <></>
}
The Focus event on a window might get triggered more often if it is a browser app. Depending on what you want to achieve, both things should be possible in
your front-end code without the need for cloud functions. Although, you might opt to code the logic as a firebase function and invoke it from your react code when onFocus.

Run action before Ionic Vue closes or app runs in background

How can i detect in Ionic Vue if the app closes or if the app is send to the background?
this.platformor platform isn't available or does not work?!
You can subscribe to the appStateChange event, like described here: https://capacitorjs.com/docs/apis/app
Example:
import { App } from '#capacitor/app'
export default {
created () {
App.addListener('appStateChange', state => {
if (!state.isActive) { // if isActive is true, App got sent to foreground, if it is false, it got sent to the background
...
}
})
}
}

I can't receiving notifications when the app is closed or swiped away on huawei device?

I'm using onsignal notifications with my flutter app,I've tested my app on three Samsunge devices and notifcations working perfectly in all these devices when the app on foreground, background, and also when I swiped it away.
after that I tested the app on huawei device which using EMUI 9.0.1 Os
the notifications only works if the app is active or on background
if I swiped it away I can't receiving any notifications.
Any help would be greatly appreciated, I've been struggling with this for a long time. I'll post my code for setting onesignal below
Future<void> initPlatformState() async {
if (!mounted) return;
OneSignal.shared.setLogLevel(OSLogLevel.verbose, OSLogLevel.none);
OneSignal.shared.setRequiresUserPrivacyConsent(true);
OneSignal.shared.consentGranted(true);
var settings = {
OSiOSSettings.autoPrompt: false,
OSiOSSettings.promptBeforeOpeningPushUrl: true
};
OneSignal.shared.setNotificationReceivedHandler((notification) {
this.setState(() {
print('Notifiaction received');
});
});
OneSignal.shared
.setNotificationOpenedHandler((OSNotificationOpenedResult result) {
this.setState(() {
newUrl = result.notification.payload.additionalData['url'].toString();
});
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => WebNotification(newUrl)));
});
// NOTE: Replace with your own app ID from https://www.onesignal.com
await OneSignal.shared
.init("xxxx-xxxx-xxxx-xxxx-xxxx", iOSSettings: settings);
OneSignal.shared
.setInFocusDisplayType(OSNotificationDisplayType.notification);
OneSignal.shared.inFocusDisplayType();
}
You need to set up a service extension. Take a look at our docs on Background Notifications. Also, consider Notification Behavior when designing your implementation
make sure you sue latest version of onesignal
for huwaii use HMS if possible ( onesignal support HMS )
In your root build.gradle, under buildscript, add the following 2 new lines to your existing repositories and dependencies sections
buildscript {
repositories {
// ...
maven { url 'https://plugins.gradle.org/m2/' } // Gradle Plugin Portal
}
dependencies {
// ...
// OneSignal-Gradle-Plugin
classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.8, 0.99.99]'
}
}
Add the following to the top of your app/build.gradle
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
you need to make user add your app to ignore battry optmztion in huwaii it is (protacted app )
in flutter you can make button and attach it to the app setting ( use these plugin https://pub.dev/packages/app_settings)

Ionic FCM push notifications observable does not emit

I am doing the following in an ionic application:
When a user is logged in, subscribe to their user ID topic
When a push notification arrives, console.log something.
this.authState.subscribe((state) => {
if (state) {
this.fcmPush.subscribeToTopic(state.uid);
this.fcmPush.onNotification().subscribe(notification => {
if (notification.wasTapped) {
console.log('Received in background', notification);
} else {
console.log('Received in foreground', notification);
}
});
}
});
Source: https://github.com/AmitMY/ionic-starter-firebase/blob/master/src/app/app.component.ts#L118
Sending a notification to my own topic arrives (after a few minutes), but I never see anything in console, both from outside the app, and inside the app.
What am I doing wrong?
Sending a notification from firebase messaging does not work.
However, using the sdk I must add:
click_action: "FCM_PLUGIN_ACTIVITY",
Which is in the usage guide but I missed

Ionic 1 push notification

Does someone have experience with ionic 1 push notifications? Is there any alternative to cloud solution that they suggest? And can someone show example of implementatio? And please have on mind that I'm completly new in ionic
I use this plugin https://github.com/phonegap/phonegap-plugin-push to handle push notification.
var pushOptions = {
android: {
senderID: "1234567890",
icon: "push_icon",
iconColor: "#FFF"
},
ios: {
alert: true,
badge: true,
sound: true
}
};
var push = PushNotification.init(pushOptions);
push.on('registration', function () {});
push.on('notification', function () {});
After test several push servicies (ionic push service, parse, pushwoosh and one signal) we choose one signal as push notification provider. Right now we use it in 30+ production applications in our company. In 10 minutes or less you can set up an app for first push notification use in android or iOS (platforms we are working right now)
The platform has an easy set up guide.
The only code in app for basic setup is:
$ionicPlatform.ready(function() {
// Enable to debug issues.
// window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});
var notificationOpenedCallback = function(jsonData) {
console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
};
window.plugins.OneSignal
.startInit("YOUR_APPID")
.handleNotificationOpened(notificationOpenedCallback)
.endInit();
// Call syncHashedEmail anywhere in your app if you have the user's email.
// This improves the effectiveness of OneSignal's "best-time" notification scheduling feature.
// window.plugins.OneSignal.syncHashedEmail(userEmail);
})
Just modify "YOUR_APPID" by yours and thats all.
Follow de docs above for make it works in your desired platform.
Check out OneSignal. It's free, easy to use and multi-platform Push Notification framework.