Build WordPress App with React Native #15 : Forwarding message to inbox 
Tags: firebase, reactnativewordpre
Published: 2019-12-05 08:32:17

---
title: Build WordPress App with React Native #15 : Forwarding message to inbox 
published: true
date: 2019-12-04 18:00:37 UTC
tags: Firebase,React native Wordpre
canonical_url: https://kriss.io/build-wordpress-client-app-with-react-native-15-forwarding-message-to-inbox-with-cloud-function/
cover_image: https://cdn-images-1.medium.com/max/1024/1*0qWyQ1BHUL6FoFfa-uPTYg.png
series: Build Wordpress Client App with React Native
---

This series intends to show how I build app to serve content from my WordPress blog by using react native. Since, my blog is talking about react-native, the series and the articles are interconnected. We will learn how to set-up many packages that make our lives comfortable and learn how to deal with WordPress APIs. Here, the most prominent features talked about in the book are the dark theme , offline mode, infinite scroll and many more. You can discover much more in this series.this inspiration to do this tutorial series came from the [React Native Mobile Templates](https://www.instamobile.io) from instamobile

In case of wanting to learn from the beginning, all the previous parts for this tutorial series are available below:

1. [Build WordPress Client App with React Native #1: Overview](https://kriss.io/build-wordpress-client-app-with-react-native-1-overview/)
2. [Build WordPress Client App with React Native #2: Setting Up Your Environment](https://kriss.io/build-wordpress-client-app-with-react-native-2-setting-up-your-environment/)
3. [Build WordPress Client App with React Native #3: Handle Navigation with React navigation](https://kriss.io/build-wordpress-client-app-with-react-native-3-handle-navigation-with-react-navigation/)
4. [Build WordPress Client App with React Native #4: Add Font Icon](https://kriss.io/build-wordpress-client-app-with-react-native-4-add-font-icon/)
5. [Build WordPress Client App with React Native #5 : Home Screen with React native paper](https://kriss.io/build-wordpress-client-app-with-react-native-5-using-react-native-paper/)
6. [Build WordPress Client App with React Native #6 : Using Html renderer and Moment](https://kriss.io/build-wordpress-client-app-with-react-native-6-using-html-renderer-and-moment/)
7. [Build WordPress Client App with React Native #7: Add pull to refresh and Infinite scroll](https://kriss.io/build-wordpress-client-app-with-react-native-7-add-pull-to-refresh-and-infinite-scroll/)
8. [Build WordPress Client App with React Native #8: Implementing SinglePost Screen](https://kriss.io/build-wordpress-client-app-with-react-native-8-implementing-singlepost-screen/)
9. [Build WordPress Client App with React Native #9: implement simple share](https://kriss.io/build-wordpress-client-app-with-react-native-9-implement-simple-share/)
10. [Build WordPress Client App with React Native #10: Setup and save bookmark](https://kriss.io/build-wordpress-client-app-with-react-native-10-setup-and-save-bookmark/)
11. [Build WordPress Client App with React Native #11: Remove and Render Bookmark](https://kriss.io/build-wordpress-client-app-with-react-native-11-remove-and-render-bookmark/)
12. [Build WordPress Client App with React Native #12: Categories screen](https://kriss.io/build-wordpress-client-app-with-react-native-12-categories-screen/)
13. [Build WordPress Client App with React Native #13: Configuring firebase in contact screen](https://kriss.io/build-wordpress-client-app-with-react-native-13-configuring-firebase-in-contact-screen/)
14. [Build WordPress Client App with React Native #14 : Implementing Settings Screen](https://kriss.io/build-wordpress-client-app-with-react-native-14-implementing-settings-screen/)

Here, we are going to forward the message to the email inbox using the cloud function. Here, will initialize the cloud function. The important thing is that we should initialize it somewhere out of our project because it will produce the node\_module conflict. Now, in order to implement it, we need to install the **firebase-tools** in our project. Hence, we can install using the following command in command prompt:

```
npm install -g firebase-tools
```

Then, we need to run the firebase login in order to authenticate using the following command:

```
firebase login
```

Then, we can start a new project using the following command:

```
firebase init functions
```

Hence, our project structure will appear as shown in the screenshot on the next page:

![](https://kriss.io/wp-content/uploads/2019/12/img_5de7f191599d4.png)

Now, we need to goto **index.js** of the **‘./functions** ’ directory. Then, we need to import the **nodemailler** module in order to send email as shown in the code snippet below:

```
const nodemailer = require('nodemailer');
```

Next, we need to configure the instance for demonstration. We can use Gmail for easy setup. But other services can also be used like Sendgrid or Mailerlite. The implementation is provided in the code snippet below:

```javascript
const gmailEmail = 'your send email';
    const gmailPassword = 'your email';
    const mailTransport = nodemailer.createTransport({
      service: 'gmail',
      auth: {
        user: gmailEmail,
        pass: gmailPassword,
      },
    });
```
Next, we need to define a trigger. Whenever a new node is added to contact, it
will trigger onCreate and get a snapshot of incoming. For that, we can use the
code from the following code snippet:
```javascript
    exports.sendEmailConfirmation = functions.database
      .ref('/contact/{contact_id}')
      .onCreate(async (snapshot, context) => {
    }
```
The further explanation is provided with ref as shown in the code snippet below:

    .ref('/contact/{contact_id}')

Here, we will add prefix {contact_id} for access auto generated id as shown in
the code snippet below:
```javascript
    exports.sendEmailConfirmation = functions.database
      .ref('/contact/{contact_id}')
      .onCreate(async (snapshot, context) => {
        const val = snapshot.val();
        const mailOptions = {
          from: 'your sending email',
          to: 'your receiving email',
          subject: 'Hey new message from ' + val.name,
          html: '<b>' + val.message + '</b>',
        };
        try {
          await mailTransport.sendMail(mailOptions);
          console.log(`New ${val.message ? '' : 'un'} message sent to:`, val.email);
        } catch (error) {
          console.error('There was an error while sending the email:', error);
        }
        return null;
      });
```
We can get the snapshot value with val(). Then, we can assign it to mail object
and send an email out with mailTransport.

Now, we need to run the following command:

    firebase deploy

**Hence, we will get the following result when we go to the firebase console:**

![](https://cdn-images-1.medium.com/max/800/0*shMHvLStSzsdMD3P.png)

We can see our function here.

Next, we need to come back to the app and hit the save message again which will
show the following logs result:

![](https://cdn-images-1.medium.com/max/800/0*tWLPlsPQx2uJ-Lrq.png)

Here, we can see the log display email was sent.

Then, we can see the email received in the device below:

![](https://cdn-images-1.medium.com/max/800/0*B8HqYjJaHhUsCMr9.jpg)

#### Prevent submit multiple time

Here, we are going to prevent the user from submitting the contact form multiple
times. For that, we are going to use **momentjs** . Using moment.js, we get the
submit time and save to AsyncStorage. Then, when the user submits the form, we
are going to hide the form and inform the user that the submission limit has
reached.

First, we need to import the required packages as shown in the code snippet
below in **Contact.js **file:
```javascript
    import AsyncStorage from '@react-native-community/async-storage';
    import moment from 'moment';
```
Then, we need to configure the handleSubmit function again as shown in the code
snippet below:
```javascript
    getSubmitDuration = async () => {
        let now = moment();
        await AsyncStorage.getItem('submit_time').then(submit_time => {
          let diff = moment.duration(now.diff(moment(submit_time))).asMinutes();
          console.log(diff);
          if (diff <= 60) {
            this.setState({block_submit: true});
          }
        });
      };
```
Here, we save submit time to the storage.

Then, we are going to create function in order to get and calculate the block
duration. The overall implementation of the function is provided in the code
snippet below:
```javascript
    render() {
        if (this.state.block_submit) {
          return (
            <View style={{flex:1,justifyContent:'center',alignItems: 'center',}}>
              <Image
                style={{width: 100, height: 100}}
                source={require('../assets/block.png')}
              />
              <Text style={{fontSize:25}}>Your can submit again in next hour</Text>
            </View>
          );
        } else {
          return (
            <View style={styles.container}>
              <Form
                type={ContactForm}
```
Here, we use the condition every time the screen is loaded. For that, we are
going to call the function is the componentDidMount hook as shown in the code
snippet below:
```javascript
    async componentDidMount() {
        this.getSubmitDuration();
      }
```
Now, spamming the save button in the Contact Screen is impossible now. If the limit exceeds, we get the following result in the emulator screen on the next page:

![](file:///Users/krissanawatkaewsanmuang/Desktop/Export-2e7cc216-a998-4bf2-94f6-a17bb4733acd/Contact%20us%20screen/Untitled%2015.png)

![](https://kriss.io/wp-content/uploads/2019/12/img_5de7f404ad3e6.png)

## Summary

In this chapter we leaned how to set up the react-native-firebase in the react native application.Then, we learned how to make use of components from tcomb-form-native package in order to implement the form in the Contact screen. Then, we implemented the sending of message to the firebase. We also used firebase tool package in order to forward the message to the email. Then, we prevented the spamming of save button in the Contact screen as well setting the limit

The post [Build WordPress Client App with React Native #15 : Forwarding message to inbox with Cloud function](https://kriss.io/build-wordpress-client-app-with-react-native-15-forwarding-message-to-inbox-with-cloud-function/) appeared first on [Kriss](https://kriss.io).