I've setup react native push notifications with Firebase and local push notifications - both work fine.
On receiving a notification when the app is in the foreground (opened and focused) I am calling a local push notification which works fine as well.
Then, when the user clicks on the local notification, in the utility class there is an OnNotification method that is called and I need to set some state there which of course doesn't work.
So instead, I am trying to callback a function on the parent file (App.js) which does has access to state management. problem is the function in App.js is not accessible in the utility class (it's not a class component).
How can this be achieved?
Thanks in advance :)
Below is an simplified example of both files.
// App.js
import React, {useState, useEffect} from 'react';
import Notifications from './src/utils/Notifications/Notifications'; // import the utility class.
const App = () => {
// handles remote notification when app is in the FOREGROUND
useEffect(() => {
const unsubscribe = messaging().onMessage(async (remoteMessage = {}) => {
// CALL FUNCTION ON UTILITY CLASS
Notifications.localNotification(remoteMessage.data);
});
return unsubscribe;
}, []);
// THE CALLBACK FUNCTION PART
const [someState, setSomeState] = useState('');
const [someMoreState, setSomeMoreState] = useState('');
const myFunc = (returnedData) => {
setSomeState(returnedData.value_1)
setSomeMoreState(returnedData.value_2)
}
return (
<></>
);
};
export default App;
// Notifications.js - utityly class.
import PushNotification from 'react-native-push-notification';
class Notifications {
constructor() {
PushNotification.configure({
onNotification: function (notification) {
if (notification.userInteraction) {
// THIS IS TRIGGERED AFTER THE USER CLICKS THE NOTIFICATION - WORKS FINE.
// HOW TO CALL FUNCTION HERE THAT NEEDS TO HANDLE STATE (function is in app.js)
// example:
const returnedData = {
value_1: 'A',
value_2: 'B',
}
myFunc(returnedData); // this function is in app.js
}
},
});
}
localNotification(data) {
}
}
export default new Notifications();
CodePudding user response:
Accessing a function in App.js from components is not a good approach. As I understand it, you only need to access this function to set some state variables. A much better solution to your problem would be to use a shared state like Redux or Context API.
You can then access this state from anywhere in your project and change it accordingly
CodePudding user response:
Answering my own question in case it might help somebody. The only thing that worked for me is to refactor the Notifications class into App.js inside a useEffect()