Index.js
import FCM from "react-native-fcm";
class Register extends Component {
constructor(props) {
super(props);
componentDidMount () {
// this method generate fcm token.
FCM.requestPermissions();
FCM.getFCMToken().then(token => {
console.log("TOKEN (getFCMToken)", token);
});
// This method get all notification from server side.
FCM.getInitialNotification().then(notif => {
console.log("INITIAL NOTIFICATION", notif)
});
// This method give received notifications to mobile to display.
this.notificationUnsubscribe = FCM.on("notification", notif => {
console.log("a", notif);
if (notif && notif.local_notification) {
return;
}
this.sendRemote(notif);
});
// this method call when FCM token is update(FCM token update any time so will get updated token from this method)
FCM.on("refreshToken", token => {
console.log("TOKEN (refreshUnsubscribe)", token);
this.props.onChangeToken(token);
});
}
sendRemote(notif) {
console.log('send');
FCM.presentLocalNotification({
title: notif.title,
message: notif.message,
priority: "high",
click_action: notif.click_action,
show_in_foreground: true,
local: true
});
}
componentWillUnmount() {
this.refreshUnsubscribe();
this.notificationUnsubscribe();
}
This is a portion of my code for generating token and handling notification from server. What wrong i am doing? Can't figure out.Please help.
Thanks in advance. Below is the screenshot of warning error i got.
I understand that this is too late but having faced the same issue I fixed it by importing
import FCM, {FCMEvent} from "react-native-fcm";
and then using FCMEvent for subscribing the events:
this.notificationSubscribe = FCM.on(FCMEvent.Notification, notif => {
this.showNotification(notif);
});
Related
I need to store notifications while my app is in a closed state. I am receiving notifications when the app is closed but can not store it somewhere.
I want to save notification, and display a count and the notification when I re-open the app. Right now I am using async storage but its not working for me. Can you suggest me something?
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Message handled in the background!', remoteMessage);
try {
const notificationArrayText = await AsyncStorage.getItem('notificationArrayText');
let updatedNotificationArrayText;
if (notificationArrayText) {
updatedNotificationArrayText = JSON.parse(notificationArrayText);
updatedNotificationArrayText.push({ message: remoteMessage.notification.body, IsRead: false });
} else {
updatedNotificationArrayText = [{ message: remoteMessage.notification.body, IsRead: false }];
}
await AsyncStorage.setItem('notificationArrayText', JSON.stringify(updatedNotificationArrayText));
} catch (error) {
console.error(error);
}
});
I made alert service using FCM, it works fine in my local server. but after I deployed my server in ec2, trying alert function on ec2 app gives me this error :
[ient-SecureIO-1] o.a.t.websocket.pojo.PojoEndpointBase : No error handling configured for [springboot.utils.WebsocketClientEndpoint] and the following error occurred
java.lang.IllegalArgumentException: Exactly one of token, topic or condition must be specified
Reading the error message, i guess that there's no token in my server.
In notification.js, I'm trying to get token and request POST to '/register'
const firebaseModule = (function () {
async function init() {
// Your web app's Firebase configuration
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/firebase-messaging-sw.js')
.then(registration => {
var firebaseConfig = {
configuration Information
};
// Initialize Firebase
console.log("firebase Initialization");
firebase.initializeApp(firebaseConfig);
// Show Notification Dialog
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function() {
console.log("Permission granted to get token");
return messaging.getToken();
})
.then(async function(token) {
console.log("Token: ", token);
await fetch('/register', { method: 'post', body: token })
messaging.onMessage(payload => {
const title = payload.notification.title
const options = {
body : payload.notification.body
}
navigator.serviceWorker.ready.then(registration => {
registration.showNotification(title, options);
})
})
})
.catch(function(err) {
console.log("Error Occured : " +err );
})
})
})
}
}
And by debugging it by console.log(), I found out that code is stopped before "if ('serviceWorker' in navigator) {"
So I need to make it proceed. But to be honest, it's been a while since i made this function, and I don't know almost anything about Javascript. I don't even know what navigator means(I googled it, but couldn't find clear answer) I'm having trouble figuring out what is wrong and how can I fix it. Can someone help me??
I am implementing agora chat in vue js where there is object which emits 6 events. How can I listen to those in VUE JS. Here is its code in core javascript:
this.agora.conn = new AC.connection({
appKey: this.agora.appKey,
});
this.agora.conn.addEventHandler("connection&message", {
// Occurs when the app is connected to Agora Chat.
onConnected: () => {
console.log("App connected.");
},
// Occurs when the app is disconnected from Agora Chat.
onDisconnected: () => {
console.log("App disconnected.")
},
// Occurs when a text message is received.
onTextMessage: (message) => {
console.log("Message Recieved: ",message);
},
// Occurs when the token is about to expire.
onTokenWillExpire: (params) => {
console.log("Token is about to expire. ",params)
this.refreshToken(this.agora.username, this.agora.password);
},
// Occurs when the token has expired. You need to get a token from your app server to log in to Agora Chat.
onTokenExpired: (params) => {
console.log("Token is expired. ",params)
this.refreshToken(this.agora.username, this.agora.password);
},
onError: (error) => {
console.log("on error: ", error);
},
});
Here agora is the data member in the component and this above code is in mounted hook.
I have noticed console the SDK is dispatching the events but this listener is not catching any. Here is agora data member:
agora : {
baseUrl : "https://a41.chat.agora.io",
appKey : "******",
username : "fana",
password: "123",
conn : null
}
I need to enable push notifications in my project. I have already integrated twilio conversations.
I followed this documentation and seems to be ok, but there is a problem with the setPushRegistrationId method.
I have this code:
import { getMessaging, getToken, onMessage } from "firebase/messaging";
import initFirebase from "../firebase/initFirebase";
export const handleNotifications = async (conversationClientInstance) => {
const app = initFirebase();
const messaging = getMessaging(app);
getToken(messaging, {
vapidKey:
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
})
.then((currentToken) => {
if (currentToken) {
console.log("currentToken", currentToken);
//Here is the problem <----------
conversationClientInstance
.setPushRegistrationId("fcm", currentToken)
.then((el) => console.log("el", el));
onMessage((payload) => {
conversationClientInstance.handlePushNotification(payload);
});
} else {
// Show permission request UI
console.log(
"No registration token available. Request permission to generate one."
);
// ...
}
})
.catch((err) => {
console.log("An error occurred while retrieving token. ", err);
// ...
});
};
I am getting this error on the twilio dashboard:
I also replicated this situation in this github repo. It is deployed, so you can try it live.
In console I can see the FCM token, but setPushRegistrationId returns undefined (the console.log('el', el))
I think I forgot something, but I can't figure out what. What do you thik?
I'm trying to display a toast when a async request is finished.
I've implemented this process:
Single File Component calls updateUserProfile() actions in my VueX store
updateUserProfile() actions makes a outgoing HTTP request on a server using Axios
When succeeded, I use a mutation to update the user profile in my store and i would like to show a toast from my single file component.
Problem is that the response object is always undefined in my component. Where is my mistake ?
Error :
profile.vue?a62a:328 Uncaught (in promise) TypeError: Cannot read
property 'data' of undefined
at eval (profile.vue?a62a:328)
Store:
/*
* Action used to fetch user data from backend
*/
updateUserProfile ({commit, state}, userData) {
// Inform VueX that we are currently loading something. Loading spinner will be displayed.
commit('SET_IS_LOADING', true);
axiosBackend.put('/user/profile', userData, { headers: { Authorization: state.authString } } ).then(res => {
console.log('PUT /user/profile', res);
// Set user Data in VueX Auth store
commit('SET_USER_DATA', {
user: res.data.data
});
// Reset is Loading
commit('SET_IS_LOADING', false);
return res.data;
})
.catch(error => {
// Reset isLoading
commit('SET_IS_LOADING', false);
});
}
Component:
methods: {
// mix the getters into computed with object spread operator
...mapActions([
'updateUserProfile'
]),
// Function called when user click on the "Save changes" btn
onSubmit () {
console.log('Component(Profile)::onSaveChanges() - called');
const userData = {
firstName: this.firstname,
}
this.updateUserProfile(userData).then( (response) => {
console.log('COMPONENT', response);
if (response.data.status === 200) {
toastr.success("Your profile has been successfully updated.");
}
});
}
}
Well,
It would be better idea if You trigger the toast from the Vuex store itself as mentioned below.
callAddToCart: ({ commit }, payload) => {
axiosBackend.put('/user/profile', userData, { headers: { Authorization:
state.authString }}).then(response => {
commit("setLoading", false, { root: true });
payload.cartKey = response.key;
commit("setNotification", {
type: 'success',
title: `title`,
});
commit("ADD_TO_CART", payload);
});
},
and inside mutation you can have a general notification toast and you can pass type, message and title as below.
setNotification(state, {type, message, title}) {
state.flash = {
type,
title,
message
}
}
NOTE: Do not forget to load toast element at the root level in order to display in the UI.
Here is working example
Hope this helps!