codebee
codebee

Reputation: 844

React Native Render Modal onMessage Firebase Notification

I have registered an onMessage() Firebase Notification Listener in a Service class (not a React Component) in my app.

Inside the method I'm invoking a React Component that renders a Modal. Problem is that the Component is never invoked (I tried adding debug statement in constructor() and render() methods of the Component but they are not printed.

Here is my listener code:

this.notificationListener = messaging().onMessage(async notification => {
    console.log("listener is invoked"); //this is printed.
    <MyModalComponent />
}

Updated Class code based on Riwen's comment:

class NotificationService extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
           dummy: false,
        }
    }

    render() {
        return(<></>);
    }

    async registerNotifications() {
        await this.checkPermissions();

        this.registerNotificationsListeners();
    }

    registerNotificationsListeners() {
        this.notificationListener = messaging().onMessage(async notification => {
            console.log('there is a notification ', notification); //this gets printed
            this.setState({dummy: true});
            {this.state.dummy && <MyModalComponent />}
        }
    }
}

<NotificationService />

Component is still not invoked.

Upvotes: 1

Views: 384

Answers (1)

Riwen
Riwen

Reputation: 5190

Try this:

class NotificationService extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
           dummy: false,
        }
    }

    render() {
        return(<>{this.state.dummy && <MyModalComponent />}</>);
    }

    registerNotificationsListeners() {
        this.notificationListener = messaging().onMessage(async notification => {
            console.log('there is a notification ', notification); //this gets printed
            this.setState({dummy: true});
        }
    }
}

Also make sure you actually register for notification listener, such as in componentDidMount.

Upvotes: 1

Related Questions