<h3 id="662c" class="graf graf--h3 graf-after--figure"><strong><span style="color: #000080;">Firebase</span></strong></h3>
<p id="3765" class="graf graf--p graf-after--h3">A fully managed platform for building<strong> <span style="color: #008000;">iOS, Android, and web apps</span></strong> that provides automatic data synchronization, authentication services, messaging, file storage, analytics, and more.</p>
<p>In this tutorial, I will demonstrate you how we will store our react native application related data in firebase providing services like <span style="color: #000000;">database,storage </span>etc.Here we will create <strong><span style="color: #0000ff;">FriendlyChatApp</span></strong> and its text data i.e messages we will store in <strong><span style="color: #0000ff;">firebase realtime database</span></strong> and captured and picked images in <strong><span style="color: #0000ff;">firebase</span></strong> <strong><span style="color: #0000ff;">storage</span></strong>.</p>
<p>Get <span style="color: #000080;"><strong>GITHUB</strong></span> code from <span style="color: #0000ff;"><a style="color: #0000ff;" href="https://github.com/arunk7839/FriendlyChatApp"><strong>Here</strong></a>.</span></p>
<p><amp-youtube layout="responsive" width="1200" height="675" data-videoid="y_-onrPG85U" title="ReactNative working with Firebase Realtime Database and Storage"><a placeholder href="https://youtu.be/y_-onrPG85U"><img src="https://i.ytimg.com/vi/y_-onrPG85U/hqdefault.jpg" layout="fill" object-fit="cover" alt="ReactNative working with Firebase Realtime Database and Storage"></a></amp-youtube></p>
<h3 data-fontsize="26" data-lineheight="39"><span style="color: #000080;"><strong>Creating Project in Firebase</strong></span></h3>
<ul>
<li>Go to <a href="https://firebase.google.com/"><strong>firebase.google.com</strong></a> and create a new account if not exist or use the existing one and go to console.</li>
<li>Now to create a new firebase project click on <strong><span style="color: #0000ff;">Add project</span></strong>.</li>
<li>Enter <strong><span style="color: #0000ff;">project</span></strong> name , select <span style="color: #0000ff;"><strong>country</strong></span> name and click on <strong><span style="color: #0000ff;">Create project</span></strong> button.</li>
</ul>
<p><img class="aligncenter wp-image-657 size-full" src="https://c1ctech.com/wp-content/uploads/2018/07/abc-1.png" alt="" width="642" height="721" /></p>
<h3 data-fontsize="26" data-lineheight="39"><strong><span style="color: #000080;">Building a FriendlyChatApp with React Native</span></strong></h3>
<p data-fontsize="22" data-lineheight="33"><span style="color: #0000ff;"><strong>Set Up the Initial Project</strong></span></p>
<p>After Firebase (the backend part of our application) is set up, it’s time to work on the frontend.</p>
<ul>
<li>First, initialize the project with the following command:</li>
</ul>
<pre style="padding-left: 30px;"><span style="color: #000000;">react-native init FriendlyChatApp</span></pre>
<ul>
<li>Next, install the libraries that are required for the project:</li>
</ul>
<p style="padding-left: 30px;"><strong><span style="color: #0000ff;">&#8220;react-native-image-picker&#8221;:</span></strong> allows you select a photo/video from the device library or directly from the camera.You can install and configure project from <strong><a href="https://github.com/react-community/react-native-image-picker#install">here</a></strong>.</p>
<p style="padding-left: 30px;"><span style="color: #0000ff;"><strong>&#8220;react-native-vector-icons&#8221;:</strong></span> using which we can use built_in icons for different platforms(android,windows,ios).You can install and configure project from <strong><a href="https://github.com/oblador/react-native-vector-icons">here</a>.</strong></p>
<p style="padding-left: 30px;"><strong><span style="color: #0000ff;">&#8220;react-redux&#8221;:</span></strong> official React bindings for Redux</p>
<p style="padding-left: 30px;"><strong><span style="color: #0000ff;">&#8220;redux&#8221;:</span></strong> a state management library for JavaScript applications</p>
<p style="padding-left: 30px;"><strong><span style="color: #0000ff;">&#8220;redux-thunk&#8221;:</span></strong> middleware that returns functions of actions</p>
<pre style="padding-left: 30px;"><span style="color: #000000;">npm install --save redux react-redux redux-thunk</span></pre>
<ul>
<li>To make sure that the application works properly, For the Android application, run this command:
<div id="crayon-5b4c90a7c1473218200731" class="crayon-syntax crayon-theme-mm-dark-blue crayon-font-monaco crayon-os-mac print-yes notranslate" data-settings=" minimize scroll-mouseover">
<div></div>
<pre class="crayon-main"><span style="color: #000000;">react-native run-android</span></pre>
</div>
<div></div>
</li>
</ul>
<h3 data-fontsize="26" data-lineheight="39"><strong><span style="color: #000080;">Set Up the Redux</span></strong></h3>
<p><span style="color: #0000ff;"><strong>ActionTypes.js</strong></span> defines the action types, on the occurance of which redux state changes.</p>
<p><strong><span style="color: #0000ff;">actionTypes.js</span></strong></p>
<pre><code>export const SET_MESSAGES = 'SET_MESSAGES';
export const UI_START_LOADING = 'UI_START_LOADING';
export const UI_STOP_LOADING = 'UI_STOP_LOADING';</code></pre>
<p><strong><span style="color: #0000ff;">SET_MESSAGES :</span></strong> In this action we will set the array of objects we get from firebase database in redux state.<br />
<strong><span style="color: #0000ff;">UI_START_LOADING :</span></strong> In this action we will display the activityIndicator in our app.<br />
<strong><span style="color: #0000ff;">UI_STOP_LOADING :</span> </strong>In this action the activityIndicator get disappear.</p>
<p>In this app we will create two reducers <strong><span style="color: #008000;">friendlyMessage</span></strong> , <strong><span style="color: #008000;">ui</span></strong>.</p>
<p><strong><span style="color: #0000ff;">friendlyMessage.js</span></strong></p>
<pre><code>import {
 SET_MESSAGES
} from "../actions/actionTypes";

const initialState = {

 messages :[]

};

const reducer = (state = initialState, action) =>; {
 switch (action.type) {

 case SET_MESSAGES:
 return {
 ...state,
 messages: action.messages,

 };
 default:
 return state;
 }
};

export default reducer;</code></pre>
<p><strong><span style="color: #0000ff;">ui.js</span></strong></p>
<pre><code>import { UI_START_LOADING, UI_STOP_LOADING } from "../actions/actionTypes";
const initialState = {
isLoading: false
};

const reducer = (state = initialState, action) =>; {
switch (action.type) {
case UI_START_LOADING:
return {
...state,
isLoading: true
};
case UI_STOP_LOADING:
return {
...state,
isLoading: false
};
default:
return state;
}
};

export default reducer;
</code></pre>
<p>After creating the reducer we will combine the reducers and createStore and then integrate our app with redux store.</p>
<p><strong><span style="color: #0000ff;">configureStore.js</span></strong></p>
<pre><code>import { createStore, combineReducers, compose, applyMiddleware } from "redux";
import thunk from "redux-thunk";

import MessageReducer from "./reducers/friendlyMessage";
import uiReducer from "./reducers/ui";

const rootReducer = combineReducers({
 message: MessageReducer,
 ui: uiReducer,
});

let composeEnhancers = compose;

if (__DEV__) {
 composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
}

const configureStore = () =>; {
 return createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)));
};

export default configureStore;</code></pre>
<p><strong><span style="color: #0000ff;">index.js</span></strong></p>
<pre><code>import React from 'react';
import { AppRegistry } from 'react-native';
import { Provider } from 'react-redux';
import App from './App';
import configureStore from './src/configureStore';

const store = configureStore();

const RNRedux = () =>; (
 <;Provider store={store}>;
 <;App />;
 <;/Provider>;
);

AppRegistry.registerComponent('FriendlyChatApp', () =>; RNRedux);</code></pre>
<h3></h3>
<h3><span style="color: #000080;"><strong>Storing Messages in Firebase Database</strong></span></h3>
<p><span style="color: #0000ff;"><strong>Set Rules to public</strong></span></p>
<p>After opening your firebase project go to <strong><span style="color: #0000ff;">Database</span></strong> click on <strong><span style="color: #0000ff;">Rules</span></strong> and after setting rules as public as shown below click on <span style="color: #0000ff;"><strong>publish</strong></span>.</p>
<p><img class="size-medium wp-image-665 aligncenter" src="https://c1ctech.com/wp-content/uploads/2018/07/rules-300x188.png" alt="" width="300" height="188" /></p>
<p>React Native provides the<strong><span style="color: #000080;"> <a style="color: #000080;" href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">Fetch API</a> </span></strong>for your networking needs.In order to send data into the database go to firebase database and just copy the <strong><span style="color: #008000;">URL</span></strong> as shown below and pass it in <strong><span style="color: #008000;">fetch()</span> </strong>as first argument.</p>
<p><img class="alignnone size-full wp-image-664" src="https://c1ctech.com/wp-content/uploads/2018/07/database-3377661486-1581434059245.png" alt="database" width="1151" height="171" />Fetch also takes an optional second argument that allows you to customize the HTTP request.Here we will pass the second argument as object which contains two properties :</p>
<p><strong><span style="color: #0000ff;">method: &#8220;POST&#8221; :</span> </strong>specifies that we want to send data at this url.</p>
<p><strong><span style="color: #0000ff;">body: JSON.stringify(messageData) :</span> </strong>specifies what to send at this url.When sending data to a server, the data has to be a string and <strong><span style="color: #008000;">JSON.stringify()</span></strong> converts a JavaScript object into a string.</p>
<pre><code>export const sendMessage = (message, userName) =>; {

 return dispatch =>; {

 dispatch(uiStartLoading());
 const messageData = {
 message: message,
 userName: userName

 };
 fetch("<span style="color: #ff0000;">WRITE_YOUR_DATABASE_URL</span>", {
 method: "POST",
 body: JSON.stringify(messageData)

 })
 .catch(err =>; {
 console.log(err);
 alert("Something went wrong, please try again!");
 dispatch(uiStopLoading());
 })
 .then(res =>; res.json())
 .then(parsedRes =>; {
 
 dispatch(uiStopLoading());
 });
 }
 };</code></pre>
<p>Here catch will throw only <strong><span style="color: #008000;">NETWORK</span></strong> related errors instead of <strong><span style="color: #000000;">4xxx</span></strong> and <strong>5xxx</strong> related errors occurs while sending data.If no error occur then fetchApi will return promise. Now we convert the response into <strong><span style="color: #008000;">JSON</span></strong> using <strong>res.json()</strong>. <span style="color: #008000;"><strong>res.json()</strong></span> again return a promise that resolves with the result of parsing the body text as JSON.</p>
<p>Now the messages get saved into the database like this :</p>
<h3><img class="aligncenter wp-image-674 size-full" src="https://c1ctech.com/wp-content/uploads/2018/07/db.png" alt="" width="536" height="395" /><strong><span style="color: #000080;">Storing Images in Firebase Storage</span></strong></h3>
<p><span style="color: #0000ff;"><strong>Set Rules to public</strong></span></p>
<p>After opening your firebase project go to <strong><span style="color: #0000ff;">Storage</span></strong> ,click on <strong><span style="color: #0000ff;">Rules</span></strong> and after setting rules as public as shown below click on <span style="color: #0000ff;"><strong>publish</strong></span>.</p>
<p><img class="aligncenter wp-image-677 size-full" src="https://c1ctech.com/wp-content/uploads/2018/07/fbrule.png" alt="" width="548" height="221" /></p>
<p>In the below code we get the image as a <strong><span style="color: #008000;">base64 </span></strong><span style="color: #008000;"><span style="color: #000000;">string .Although it is a string but technically it is a file contains image data.So we cannot store it in database we have to store it in <strong><span style="color: #0000ff;">Storage</span></strong>.</span></span></p>
<pre><code>imagePickerHandler = ()=>;{
ImagePicker.showImagePicker({title: "Pick an Image", maxWidth: 800, maxHeight: 600}, res =>; {
 if (res.didCancel) {
 console.log("User cancelled!");
 } else if (res.error) {
 console.log("Error", res.error);
 } else {
 this.setState({
 pickedImage: { uri: res.uri , <strong><span style="color: #008000;">base64:</span></strong> res.data}
 });

this.props.onImagePicked(
 this.state.pickedImage,
 this.state.userName
 );

 }
 });

};</code></pre>
<p>But the issue is that Storage is accessible through <span style="color: #008000;"><strong>firebase SDK</strong></span> and it has a <span style="color: #008000;"><strong>javascript SDK</strong></span> .You can use this SDK to send HTTP request and that would work but you cannot access <strong><span style="color: #008000;">Storage </span></strong>using it.</p>
<p>Now For storage unlike the database has no API we can easily target.But firebase has another cool feature we can use to work around that is <span style="color: #008000;"><strong>Firebase Cloud Functions</strong></span>.Cloud Functions for Firebase lets you automatically run backend code in response to events triggered by HTTP request.What we will do we will send request to some url and when we do this a specific function will run and execute code and there we will write code to accept an image and stored it temporarily at some path then we get the image from that path and stored it in firebase <span style="color: #008000;"><strong>Storage,</strong></span> which(Storage) we can access from within function since that run not on our client but on firebase sounds a bit complex but it is not, this approach here will work very well with firebase.</p>
<p>Since we don&#8217;t want to use the <span style="color: #008000;"><strong>SDK</strong></span> we will write the <strong><span style="color: #008000;">cloud function</span></strong>.</p>
<ul>
<li>Before writing the <strong><span style="color: #008000;">cloud function </span></strong>we need the <strong><span style="color: #0000ff;">firebase tools</span></strong> which really allows us to write such a function.We install it globally on our machine ,write :</li>
</ul>
<pre style="padding-left: 30px;"><span style="color: #000000;">npm install -g firebase-tools</span></pre>
<p style="padding-left: 30px;"><span style="color: #008000;"><strong>firebase tools</strong></span> is just a <strong><span style="color: #008000;">cli</span></strong> that makes it easy to put this project under control of firebase and in the end it makes it very convenient to write and deploy cloud function from here.</p>
<ul>
<li>Now write the below command and make sure that you are in your project&#8217;s root folder (i.e <span style="color: #008000;"><strong>FriendlyChatApp</strong></span>):</li>
</ul>
<p style="padding-left: 30px;"><strong><span style="color: #0000ff;">firebase init</span></strong></p>
<ul>
<li>Now it will ask you what you want to use , the default is <strong><span style="color: #008000;">D</span><span style="color: #008000;">atabase</span></strong> but you navigate down to <span style="color: #008000;"><strong>Function</strong></span> press space for selection then click enter.</li>
<li>Now it will ask you to select a firebase project from which you want to link your app? ReactAppUsingFirebase</li>
<li>what language would you like to use to write cloud functions?select Javascript</li>
<li>Do you want to use ESlint to catch probable bugs and enfource style?say No</li>
<li>Do you want to install dependencies with npm now?say Yes</li>
</ul>
<p>Later it will display message at the end like <span style="color: #0000ff;"><strong>Firebase Initialization Complete</strong></span>.Now the <span style="color: #0000ff;"><strong>functions</strong></span> directory get integrated in your project root folder.</p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>

<ul>
<li>Open <strong><span style="color: #0000ff;">index.js</span></strong> inside <strong><span style="color: #008000;">functions</span></strong> directory and create <span style="color: #008000;"><strong>storeImage</strong></span> as a function which we will target later via <strong><span style="color: #008000;">http</span></strong> request.</li>
<li>Here you get a request and response ,we are writing code with <span style="color: #008000;"><strong>node.js</strong></span> that&#8217;s the restriction we can&#8217;t use other language .If you want to use other language then use your own <span style="color: #008000;"><strong>beckend</strong></span> .</li>
<li>The goal of the <strong><span style="color: #0000ff;">storeImage</span></strong> function is to extract the <strong><span style="color: #008000;">image</span></strong> from request and store the image in <strong><span style="color: #008000;">firebase cloud Storage</span></strong> and then return the <strong><span style="color: #008000;">response</span></strong> once we are done.</li>
</ul>
<h3><strong><span style="color: #000080;">Add Libraries to Functions Directory</span></strong></h3>
<ul>
<li>Firstly navigate into the <strong><span style="color: #008000;">functions</span></strong> folder and install the external package <strong><span style="color: #0000ff;">@google-cloud/storage </span></strong>:</li>
</ul>
<pre style="padding-left: 30px;"><span style="color: #000000;">cd functions</span>

<span style="color: #000000;">npm install --save @google-cloud/storage</span></pre>
<p style="padding-left: 30px;"><strong><span style="color: #008000;">@google-cloud/storage :</span></strong> We need this package because firebase Storage is based on <span style="color: #008000;"><strong>Google cloud storage</strong></span> and there are some useful <span style="color: #008000;"><strong>SDK</strong></span> we can use to conveniently store data in there.</p>
<ul>
<li>We also need another external package <strong><span style="color: #008000;">cors</span></strong>.</li>
</ul>
<p style="padding-left: 30px;"><strong><span style="color: #008000;">cors :</span></strong> It is required because it allows access to our function from other origins.</p>
<pre style="padding-left: 30px;"><span style="color: #000000;">npm install --save cors</span></pre>
<ul>
<li>To write or save this image in <span style="color: #008000;"><strong>Storage</strong></span> I will temporarily need to save it <strong><span style="color: #008000;">cloud function</span></strong> and this will be automatically removed by firebase whenever function execution finished.For this we need another constant fs (file service) .<strong><span style="color: #008000;">fs</span></strong> is a default node.js package ,no need to install.</li>
<li>To generate a unique Id for each image install:</li>
</ul>
<pre style="padding-left: 30px;"><span style="color: #000000;">npm install --save uuid-v4</span></pre>
<ul>
<li>Now the <strong><span style="color: #008000;">storeImage</span></strong> function is ready ,move back to the root directory and deploy your function by writing below line :</li>
</ul>
<pre style="padding-left: 30px;"><span style="color: #000000;">cd..</span>

<span style="color: #000000;">firebase deploy </span></pre>
<ul>
<li>Firebase deploy will give you the <strong><span style="color: #0000ff;">url</span></strong> of cloud function i.e <strong><span style="color: #008000;">storeImage</span></strong>.</li>
</ul>
<p><strong><span style="color: #0000ff;">index.js</span></strong></p>
<pre><code>const functions = require('firebase-functions');
const cors = require("cors")({ origin: true });
const fs = require("fs");
const UUID = require("uuid-v4");
<strong><span style="color: #008000;">//how you get your firebase projectId and keyFilename I have explained it below.</span></strong>
const gcconfig = {
 projectId: "<span style="color: #ff0000;">YOUR_FIREBASE_PROJECT_ID</span>",
 keyFilename: "<span style="color: #ff0000;">YOUR_FIREBASE_PROJECT_GENERATED_KEY_FILE</span>"
};

const gcs = require("@google-cloud/storage")(gcconfig);


exports.storeImage = functions.https.onRequest((request, response) =>; {
 return cors(request, response, () =>; {
 const body = JSON.parse(request.body);
 fs.writeFileSync("/tmp/uploaded-image.jpg", body.image, "base64", err =>; {
 console.log(err);
 return response.status(500).json({ error: err });
 });
 const bucket = gcs.bucket("<span style="color: #ff0000;">WRITE_YOUR_FIREBASE_PROJECT_STORAGE_URL</span>");
 const uuid = UUID();

 return bucket.upload(
 "/tmp/uploaded-image.jpg",
 {
 uploadType: "media",
 destination: "/images/" + uuid + ".jpg",
 metadata: {
 metadata: {
 contentType: "image/jpeg",
 firebaseStorageDownloadTokens: uuid
 }
 }
 },
 (err, file) =>; {
 if (!err) {
 return response.status(201).json({
 imageUrl:
 "https://firebasestorage.googleapis.com/v0/b/" +
 bucket.name +
 "/o/" +
 encodeURIComponent(file.name) +
 "?alt=media&;token=" +
 uuid
 });
 } else {
 console.log(err);
 return response.status(500).json({ error: err });
 }
 }
 );
 });
 });</code></pre>
<p><span style="color: #008000;"><strong>keyFilename :</strong></span></p>
<ul>
<li>Open the firebase project click on the gear icon at the top and select <strong><span style="color: #0000ff;">Project Settings</span></strong>.</li>
<li>Choose service accounts and there you leave node.js checked and click on <strong><span style="color: #0000ff;">Generate new private key</span></strong> and<br />
then click <strong><span style="color: #0000ff;">Generate key</span></strong>.</li>
<li>Now download the file and store it in the <strong><span style="color: #008000;">functions</span></strong> folder of your root directory.</li>
</ul>
<p><img class="wp-image-670 size-large aligncenter" src="https://c1ctech.com/wp-content/uploads/2018/07/key-1024x681.png" alt="" width="685" height="456" /></p>
<p><span style="color: #008000;"><strong>projectId :</strong></span></p>
<ul>
<li>Open the firebase project click on the gear icon at the top and select <strong><span style="color: #0000ff;">Project Settings</span></strong>.</li>
<li>By default <strong><span style="color: #008000;">General</span></strong> get open now from here you copy project id and paste it in <strong><span style="color: #008000;">projectId</span></strong> property.</li>
</ul>
<p><img class="aligncenter wp-image-671 size-large" src="https://c1ctech.com/wp-content/uploads/2018/07/key2-1024x366.png" alt="" width="685" height="245" /></p>
<h3></h3>
<h3><span style="color: #000080;"><strong>Sending Image to storeImage Cloud Function</strong></span></h3>
<ul>
<li>Inside <strong><span style="color: #008000;">imagePicked</span></strong> actionCreator we will send the captured image to the deployed <span style="color: #008000;"><strong>storeImage</strong></span> cloud function and inside the storeImage function we have write the code which accepts the image and stored it in firebase <strong><span style="color: #008000;">Storage</span></strong>.</li>
<li>Now we get the <span style="color: #008000;"><strong>imageUrl</strong></span> of the captured image inside <strong><span style="color: #008000;">pickedImage</span></strong> property and stored it into the database .</li>
</ul>
<pre><code>export const imagePicked = (pickedImage, userName) =>; { 
return dispatch =>; {
 dispatch(uiStartLoading());
fetch("<span style="color: #ff0000;"><strong>WRITE_THE_URL_YOU_GET_FROM_FIREBASE_DEPLOY</strong></span>", {
 method: "POST",
 body: JSON.stringify({
 image: pickedImage.base64
 })
 })
 .catch(err =>; {
 console.log(err);
 alert("Something went wrong, please try again!");
 dispatch(uiStopLoading());
 })
 .then(res =>; res.json())
 .then(parsedRes =>; {
 const ImageData = {

 userName: userName,
 pickedImage: parsedRes.imageUrl


 };

 return fetch("<span style="color: #ff0000;">WRITE_YOUR_DATABASE_URL</span>", {
 method: "POST",
 body: JSON.stringify(ImageData)
 })
 })
 .catch(err =>; {
 console.log(err);
 alert("Something went wrong, please try again!");
 dispatch(uiStopLoading());
 })
 .then(res =>; res.json())
 .then(parsedRes =>; {
 console.log(parsedRes);
 dispatch(getMessages());
 dispatch(uiStopLoading());
 });
};
};</code></pre>
<p><span style="color: #0000ff;"><strong>Firebase Functions</strong></span></p>
<figure id="attachment_678" aria-describedby="caption-attachment-678" style="width: 1553px" class="wp-caption aligncenter"><img class="wp-image-678 size-full" src="https://c1ctech.com/wp-content/uploads/2018/07/func.png" alt="" width="1553" height="130" /><figcaption id="caption-attachment-678" class="wp-caption-text"><span style="color: #003366;"><strong>Firebase Functions</strong></span></figcaption></figure>
<p><strong><span style="color: #0000ff;">Firebase Storage</span></strong></p>
<figure id="attachment_675" aria-describedby="caption-attachment-675" style="width: 1223px" class="wp-caption aligncenter"><img class="wp-image-675 size-full" src="https://c1ctech.com/wp-content/uploads/2018/07/storage.png" alt="" width="1223" height="256" /><figcaption id="caption-attachment-675" class="wp-caption-text"><span style="color: #003366;"><strong>Firebase Storage</strong></span></figcaption></figure>
<p><span style="color: #0000ff;"><strong>Firebase Database</strong></span></p>
<figure id="attachment_676" aria-describedby="caption-attachment-676" style="width: 953px" class="wp-caption aligncenter"><img class="wp-image-676 size-full" src="https://c1ctech.com/wp-content/uploads/2018/07/dbst.png" alt="" width="953" height="509" /><figcaption id="caption-attachment-676" class="wp-caption-text"><strong><span style="color: #003366;">Firebase Database</span></strong></figcaption></figure>
<p> ;</p>
<ul>
<li>Here <strong><span style="color: #0000ff;">getMessages</span></strong> actionCreator get all the data from the firebase database .It passes the array of data to another actionCreator <strong><span style="color: #0000ff;">setMessages</span></strong> and then we will stored it in <strong><span style="color: #0000ff;">redux</span></strong>.</li>
</ul>
<pre><code>export const getMessages = () =>;
{
 return dispatch =>; {
 dispatch(uiStartLoading());
 return fetch(
 "<span style="color: #ff0000;">WRITE_YOUR_DATABASE_URL</span>"

 )
 .catch(err =>; {
 console.log(err);
 alert("Something went wrong, please try again!");
 dispatch(uiStopLoading());
 })
 .then(res =>; res.json())
 .then(parsedRes =>; {

 const messages = [];
 for (let key in parsedRes) {
 messages.push({
 ...parsedRes[key],

 key: key
 });

 }

 <strong><span style="color: #008000;">dispatch(setMessages(messages))</span></strong>;
 dispatch(uiStopLoading());
 }).catch(err =>; {
 alert("Something went wrong, sorry :/");
 console.log(err);
 dispatch(uiStopLoading());
 });

 };
 };


export const setMessages = messages =>; {
 return {
 type: SET_MESSAGES,
 messages: messages
 };
};</code></pre>
<p><span style="color: #000080;"><strong>When you run the app it will fetch the data from the database and it look like this :</strong></span></p>
<h3><img class="aligncenter wp-image-672 " src="https://c1ctech.com/wp-content/uploads/2018/07/Screenshot_1531811791-576x1024.png" alt="" width="415" height="738" /></h3>
<h3><strong><span style="color: #000080;">Complete code :</span></strong></h3>
<p><strong><span style="color: #0000ff;">App.js</span></strong></p>
<pre><code>import React, { Component } from 'react';
import {
 StyleSheet,
 TextInput,
 Button,
 TouchableOpacity,
 ActivityIndicator,
 View
 } from 'react-native';
import { connect } from "react-redux";
import Icon from 'react-native-vector-icons/Ionicons';
import ImagePicker from "react-native-image-picker";
import validate from "./src/validation";
import { sendMessage,getMessages,imagePicked } from "./src/actions/index";
import MessageList from "./src/components/MessageList/MessageList";

 class App extends Component {

constructor(props) {
 super(props);
 this.props.onLoadMessages();
 }

 state = {

 pickedImage : null,
 message : "",
 userName :"Arun Kumar",
 validText : false

 };

imagePickerHandler = ()=>;{
ImagePicker.showImagePicker({title: "Pick an Image", maxWidth: 800, maxHeight: 600}, res =>; {
 if (res.didCancel) {
 console.log("User cancelled!");
 } else if (res.error) {
 console.log("Error", res.error);
 } else {
 this.setState({
 pickedImage: { uri: res.uri , base64: res.data}
 });

this.props.onImagePicked(
 this.state.pickedImage,
 this.state.userName
 );

 }
 });

};

sendButtonHandler = ()=>;
{

if (this.state.message.trim() === "") {
 return;
 }
 else {

 this.props.onSendMessage(
 this.state.message,
 this.state.userName
 );
this.setState({
message: "",
 validText : false
 });

 }
};


textChangedHandler = val=>;{

this.setState({
 message: val,
 validText : validate(val)
 });
};

 render() {
let showProgressBar = null;


 if (this.props.isLoading) {
 showProgressBar = (
 <;View style={styles.progressBar}>;
 <;ActivityIndicator size="large" color="#0000ff"/>;
 <;/View>;
 );
 }
 else
 {
 showProgressBar = (<;MessageList
 messages={this.props.messages}
 />;
 );
 }


 return (
 <;View style={styles.container}>;

 {showProgressBar}

 <;View style={styles.innerContainer}>;

 <;View>;
 <;TouchableOpacity onPress={this.imagePickerHandler}>;
 <;View >;
 <;Icon

 size={40}
 name={ "md-image" }
 color="#841584"
 />;
 <;/View>;
 <;/TouchableOpacity>;
 <;/View>;

 <;TextInput
 style={styles.textInput}
 onChangeText={this.textChangedHandler}>;
 {this.state.message}
 <;/TextInput>;

 <;Button
 onPress={this.sendButtonHandler}
 title="Send"
 color="#841584"
 disabled={
 !this.state.validText
 }
 />;

 <;/View>;

 <;/View>;
 );
 }
}

const styles = StyleSheet.create({
 container: {
 flex: 1

 },
 innerContainer: {

 flexDirection: 'row',
 justifyContent: 'space-between',
 alignItems: 'flex-end',
 margin:10

 },
 textInput: {
 width: "70%",
 borderColor: "transparent",
 padding: 8,
 },
 progressBar: {
 flex: 1,
 alignItems: 'center',
 justifyContent: 'center'

 }

});

const mapStateToProps = state =>; {
 return {
 messages: state.message.messages,
 isLoading: state.ui.isLoading
 };
};

const mapDispatchToProps = dispatch =>; {
 return {
 onSendMessage: (message, userName) =>;
 dispatch(sendMessage(message, userName)),
 onImagePicked: (pickedImage, userName) =>;
 dispatch(imagePicked(pickedImage, userName)),
 onLoadMessages: () =>; dispatch(getMessages())
 };
};

export default connect( mapStateToProps ,mapDispatchToProps)(App);</code></pre>
<p><strong><span style="color: #0000ff;">ListItem.js</span></strong></p>
<pre><code>import React , { Component }from "react";
import { View, Text, StyleSheet, Image } from "react-native";

class ListItem extends Component {

render(){

let chatMessage = null;
 if (this.props.obj.hasOwnProperty("pickedImage")) {
 chatMessage = (
<;View style={styles.innerContainer}>;
 <;Image source={{uri: this.props.obj.pickedImage}} style={styles.image} />;
 <;Text style={styles.userName}>;{this.props.obj.userName}<;/Text>;
<;/View>;
 );
 }
 else {
 chatMessage = (
<;View style={styles.innerContainer}>;
 <;Text style={styles.message}>;{this.props.obj.message}<;/Text>;
 <;Text style={styles.userName}>;{this.props.obj.userName}<;/Text>;
<;/View>;
 );
 }

return(
 <;View style={styles.container}>;

 {chatMessage}

 <;/View>;

);
}
}

const styles = StyleSheet.create({
 container: {
 width: "100%",
 },
 innerContainer: {
 marginTop: 10,
 padding :10
 },
 image: {
 height: 300,
 width: 300
 },
 userName: {
 fontSize: 16,
 },
 message: {
 fontSize: 22,
 fontWeight: "bold",
 color: 'black'
 }
});

export default ListItem;</code></pre>
<p><strong><span style="color: #0000ff;">MessageList.js</span></strong></p>
<pre><code>import React from "react";
import { StyleSheet, FlatList } from "react-native";
import ListItem from "../ListItem/ListItem";

const messageList = props =>; {

return (
<;FlatList
style={styles.listContainer}
data={props.messages}
renderItem={(info) =>; (
<;ListItem
obj={info.item}
/>;
)}
/>;
);
};

const styles = StyleSheet.create({
listContainer: {
width: "100%"
}
});


export default messageList;</code></pre>


