Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to develop Web Application based on RethinkDB + React Native

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to develop Web applications based on RethinkDB + React Native". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's ideas to study and learn "how to develop Web applications based on RethinkDB + React Native".

Brief introduction

A real-time application can give the user time to know what he wants to know. Users do not have to constantly refresh the user interface to get message updates, the server side of the application will automatically update the client application. In this article, we will use the popular RethinkDB + React Native framework to develop a real-time mobile Web application.

The following figure shows a run-time snapshot of the sample project.

Next, let's first analyze the coding of mobile applications, and then discuss the programming of server-side components, which will use technologies such as Node, Express, Socket.io and RethinkDB.

Installation dependency

Navigate to the NewsShare directory from the project you cloned, and then execute the command npm install to install the following project dependencies:

1.react-native: this is the React Native (native) framework.

2.lodash: used to manage an array of news items so that the array is limited and sorted by the number of votes.

3.react-native-modalbox: used to create modal dialogs to share a piece of news.

The 4.react-native-button:React Native modal dialog box depends on it and is used to create buttons.

5.react-native-vector-icons: used to create icons using popular icon sets such as FontAwesome and Ionicons. This is mainly used to create icons for voting buttons.

Client component of 6.socket.io-client:Socket.io, which is a real-time application framework.

Link icon

After installing the dependencies, an additional step is to make the icons work properly, that is, to link them to the application. This is done by using rnpm--React Native's package manager.

We will use npm to install rnpm in the following format:

Npm install rnpm-g

You can then link the icons by executing the rnpm link command in the NewsSharer directory.

Develop mobile client programs

The contents of the file index.android.js are shown below:

Import React, {Component} from 'react'; import {AppRegistry, StyleSheet, View} from' react-native'; import Main from'. / components/Main'; class NewsSharer extends Component {render () {return ();}} const styles = StyleSheet.create ({container: {flex: 1, justifyContent: 'center', alignItems:' center', backgroundColor:'# F5FCFFF,}}) AppRegistry.registerComponent ('NewsSharer', () = > NewsSharer)

This file is the entry point file for the Android application. If you want to deploy it to iOS, you can copy the above code into the file index.ios.js.

The main task of this file is to import Main components, which are the core of the application. This can greatly reduce the repetition of programming when you import components instead of repeatedly coding for each platform.

Write the main application component

Create the file Main.js under the path components/Main.js, as follows:

Import React, {Component} from 'react'; import {AppRegistry, StyleSheet, Text, View, TextInput, TouchableHighlight, Linking, ListView} from' react-native'; import Button from 'react-native-button'; import Modal from' react-native-modalbox'; import Icon from 'react-native-vector-icons/Octicons'; import ".. / UserAgent"; import io from' socket.io-client/socket.io'; import _ from 'lodash' Var base_url = 'http://YOUR_DOMAIN_NAME_OR_IP_ADDRESS:3000'; export default class Main extends Component {constructor (props) {super (props); this.socket = io (base_url, {transports: [' websocket']}) This.state = {is_modal_open: false, news_title:', news_url:', news_items_datasource: new ListView.DataSource ({rowHasChanged: (row1, row2) = > row1! = = row2,}), is_news_loaded: false, news: {}, news_items: []} getNewsItems () {fetch (base_url +'/ news') .then (response) = > {return response.json () ) .then ((news_items) = > {this.setState ({'news_items': news_items}); var news_datasource = this.state.news_items_datasource.cloneWithRows (news_items); this.setState ({' news': news_datasource, 'is_news_loaded': true}); return news_items;}) .catch ((error) = > {alert (' Error occured while fetching news items');}) } componentWillMount () {this.socket.on ('news_updated', (data) = > {var news_items = this.state.news_items; if (data.old_val = null) {news_items.push (data.new_val);} else {_ .map (news_items, function (row, index) {if (row.id = = data.new_val.id) {news_ items [index] .upvotes = data.new_val.upvotes;}})) } this.updateUI (news_items);} updateUI (news_items) {var ordered_news_items = _ .orderBy (news_items, 'upvotes',' desc'); var limited_news_items = _ .slice (ordered_news_items, 0,30); var news_datasource = this.state.news_items_datasource.cloneWithRows (limited_news_items) This.setState ({'news': news_datasource,' is_news_loaded': true, 'is_modal_open': false,' news_items': limited_news_items});} componentDidMount () {this.getNewsItems () } upvoteNewsItem (id, upvotes) {fetch (base_url +'/ upvote-newsitem', {method: 'POST', headers: {' Accept': 'application/json',' Content-Type': 'application/json',}, body: JSON.stringify ({news_id: id, upvotes: upvotes + 1})}) .catch (err) = > {alert (' Error occured while trying to upvote');}) } openModal () {this.setState ({is_modal_open: true});} closeModal () {this.setState ({is_modal_open: false}) } shareNews () {fetch (base_url +'/ save-newsitem', {method: 'POST', headers: {' Accept': 'application/json',' Content-Type': 'application/json',}, body: JSON.stringify ({news_title: this.state.news_title, news_url: this.state.news_url,})}) .then (response) = > {alert (' News was sharedness') This.setState ({news_title:', news_url:'});}) .catch ((err) = > {alert ('Error occured while sharing news');});} openPage (url) {Linking.canOpenURL (url) .then (supported = > {if (supported) {Linking.openURL (url);}}) } renderNews (news) {return ({news.upvotes} {news.title}) } render () {return (News Sharer Share News {this.state.is_news_loaded & &} Share News this.setState ({news_title: text})} value= {this.state.news_title} placeholder= "Title" / > this.setState ({news_url: text})} value= {this.state.news_url} placeholder= "URL" keyboardType= "url "/ > Share) } const styles = StyleSheet.create ({container: {flex: 1, alignSelf: 'stretch', backgroundColor:' # F5FCFFF,}, header: {flex: 1, backgroundColor:'# 3B3738, flexDirection: 'row'}, app_title: {flex: 7, padding: 10}, header_text: {fontSize: 20, color:' # FFF', fontWeight: 'bold'} Header_button_container: {flex: 3}, body: {flex: 19}, btn: {backgroundColor: "# 0***5D1", color: "white", margin: 10}, modal: {height: 300}, modal_header: {margin: 20,}, modal_body: {alignItems: 'center'}, input_row: {padding: 20} Modal_header_text: {fontSize: 18, fontWeight: 'bold'}, share_btn: {width: 100}, news_item: {paddingLeft: 10, paddingRight: 10, paddingTop: 15, paddingBottom: 15, marginBottom: 5, borderBottomWidth: 1, borderBottomColor:' # ccc', flex: 1, flexDirection: 'row'}, news_item_text: {color:' # 5757}, fontSize: 18} Upvote: {flex: 2, paddingRight: 15, paddingLeft: 5, alignItems: 'center'}, news_title: {flex: 18, justifyContent:' center'}, upvote_text: {fontSize: 18, fontWeight: 'bold'}}) AppRegistry.registerComponent ('Main', () = > Main)

Let's analyze the above code. First, import the built-in React Native and third-party components needed for programming:

Import React, {Component} from 'react'; import {AppRegistry, StyleSheet, Text, View, TextInput, TouchableHighlight, Linking, ListView} from' react-native'; import Button from 'react-native-button'; import Modal from' react-native-modalbox'; import Icon from 'react-native-vector-icons/Octicons'; import ".. / UserAgent"; import io from' socket.io-client/socket.io'; import _ from 'lodash'

Note that you imported the code from another file you developed in the following ways:

Import ".. / UserAgent"

This is the UserAgent.js file you see in the root directory NewsSharer. It contains code that sets the user agent to react-native--Socket.io, or it assumes that the program is running in a browser environment.

Window.navigator.userAgent = 'react-native'

Next, determine the base URL that the application will request. If you are doing local testing, this may be the internal IP address of your computer. In order for this to work, you must make sure your phone or tablet is connected to the same network as your computer.

Var base_url = 'http://YOUR_DOMAIN_NAME_OR_IP_ADDRESS:3000';

Next, in the constructor, initialize the socket connection:

This.socket = io (base_url, {transports: ['websocket']})

Then, set the default state of the application:

This.state = {is_modal_open: false, / / for showing/hiding the modal news_title:', / / default value for news title text field news_url:', / / default value for news url text field / / initialize a datasource for the news items news_items_datasource: new ListView.DataSource ({rowHasChanged: (row1, row2) = > row1! = = row2,}), / / for showing/hiding the news items is_news_loaded: false, news: {} / / the news items datasource news_items: [] / / the news items}

The function of this function is to retrieve news items from the server using the built-in fetch method. It makes an GET request to the news route and then extracts the news_items object from the response. This object is used later to create the news data source required by the client-side ListView component. Once created, it updates the status with the news data source; in this way, the content of the news items in the user interface can be updated accordingly.

GetNewsItems () {fetch (base_url +'/ news') .then (response) = > {return response.json ();}) .then (news_items) = > {this.setState ({'news_items': news_items}); var news_datasource = this.state.news_items_datasource.cloneWithRows (news_items); this.setState ({' news': news_datasource, 'is_news_loaded': true}); return news_items ) .catch ((error) = > {alert ('Error occured while fetching news items');});}

The following ComponentWillMount method is one of the lifecycle methods of React. This allows you to execute your own custom code before the initialization rendering occurs. It is also here that you listen for news_updated events emitted by the server component of Socket.io; when this event occurs, it may be one of two things-either when users share news items or when they vote yes to existing news items.

It is worth noting that RethinkDB's changefeed returns a null value for old_val when a new news item appears. This is how we distinguish between the above two possibilities. If the user shares a news item, push it to the news_items array; otherwise, find the news item that voted yes and update its yes vote count. You can now update the user interface to reflect your changes.

ComponentWillMount () {this.socket.on ('news_updated', (data) = > {var news_items = this.state.news_items; if (data.old_val = null) {/ / a new news item is shared / / push the new item to the news_items array news_items.push (data.new_val) } else {/ / an existing news item is upvoted / / find the news item that was upvoted and update its upvote count _ .map (news_items, function (row, index) {if (row.id = = data.new_val.id) {news_ items [index] .upvotes = data.new_val.upvotes;});} / / update the UI to reflect the changes this.updateUI (news_items);});}

Next, the UpdateUI function uses the number of yes votes to subscribe to news items from high to low. Once sorted, the first 30 news items are extracted and the status updated at the same time.

UpdateUI (news_items) {var ordered_news_items = _ .orderBy (news_items, 'upvotes',' desc'); var limited_news_items = _ .slice (ordered_news_items, 0,30); var news_datasource = this.state.news_items_datasource.cloneWithRows (limited_news_items) This.setState ({'news': news_datasource,' is_news_loaded': true, 'is_modal_open': false,' news_items': limited_news_items});}

The ComponentDidMount method described below is another React lifecycle method, which is called after the initial rendering. In this method, we implement to get the news item from the server side.

[note] if you want to make a request before installing the component, you can also get the news item from the server side from the componentWillMount method.

ComponentDidMount () {this.getNewsItems ();}

The next upvoteNewsItem method sends a request to the server to vote for the news item:

UpvoteNewsItem (id, upvotes) {fetch (base_url +'/ upvote-newsitem', {method: 'POST', headers: {' Accept': 'application/json',' Content-Type': 'application/json',}, body: JSON.stringify ({news_id: id, upvotes: upvotes + 1})}) .catch ((err) = > {alert (' Error occured while trying to upvote');});}

Next, the openModal and closeModal methods are responsible for showing and hiding modal dialogs that share news content, respectively.

OpenModal () {this.setState ({is_modal_open: true});} closeModal () {this.setState ({is_modal_open: false});}

Moving on, the shareNews function is used to send a request to create a news item:

ShareNews () {fetch (base_url +'/ save-newsitem', {method: 'POST', headers: {' Accept': 'application/json',' Content-Type': 'application/json',}, body: JSON.stringify ({news_title: this.state.news_title, news_url: this.state.news_url,})}) .then (response) = > {alert (' News was sharedness') This.setState ({news_title:', news_url:'});}) .catch ((err) = > {alert ('Error occured while sharing news');});}

Next, the openPage function is used to open the URL corresponding to the news item in the browser:

OpenPage (url) {Linking.canOpenURL (url) .then (supported = > {if (supported) {Linking.openURL (url);}});}

Next, the RenderNews function returns UI for each news item. This method is also responsible for displaying the "upvote" button, the number of votes in favor, and news headlines. The news headlines are encapsulated in a TouchableHighlight component. This allows us to open the corresponding URL by executing the openPage function. The same should be done with regard to the number of votes in favour.

[note] this code uses TouchableHighlight components instead of Button components, because Button components cannot contain View or Text components.

RenderNews (news) {return ({news.upvotes} {news.title});}

Further down, the render function is responsible for returning the UI portion of the entire application:

Render () {...}

In the render function, you create a title that contains the title of the application and a button that opens the modal dialog box to share news items.

News Sharer Share News

For the body section, use the ListView component to render news items. It has three required parameters: initialListSize,dataSource and renderRow. Where InitialListSize is set to 1; in this way, ListView can be rendered line by line for each frame of the content section. If you want to display all the rows at once, you can also change this value to a larger one. DataSource corresponds to news items, and the renderRow function is used to render news items in each line.

{this.state.is_news_loaded & &}

The next step is to define the modal dialog box for sharing news. Two text fields are used in this dialog box to enter the title and the news URL, and a button is used to submit the news to the server. The text field is implemented using the TextInput component. Because the label control is not used, you need to enter placeholder text in the TextInput component to prompt the user for what to enter.

Both text fields have an onChangeText method that is used when the text value is updated. KeyboardType's Url is used in the text field of the news URL; in this way, it opens the device's keyboard and enables optimized support for input URL. Users do not have to enter content manually, they can use copy and paste. At the bottom of the text field are buttons for sharing news. The click of the button calls the previously defined shareNews function.

Share News this.setState ({news_title: text})} value= {this.state.news_title} placeholder= "Title" / > this.setState ({news_url: text})} value= {this.state.news_url} placeholder= "URL" keyboardType= "url" / > Share

Next, style the component:

Const styles = StyleSheet.create ({container: {flex: 1, alignSelf: 'stretch', backgroundColor:' # F5FCFFF,}, header: {flex: 1, backgroundColor:'# 3B3738, flexDirection: 'row'}, app_title: {flex: 7, padding: 10}, header_text: {fontSize: 20, color:' # FFF', fontWeight: 'bold'} Header_button_container: {flex: 3}, body: {flex: 19}, btn: {backgroundColor: "# 0***5D1", color: "white", margin: 10}, modal: {height: 300}, modal_header: {margin: 20,}, modal_body: {alignItems: 'center'}, input_row: {padding: 20} Modal_header_text: {fontSize: 18, fontWeight: 'bold'}, share_btn: {width: 100}, news_item: {paddingLeft: 10, paddingRight: 10, paddingTop: 15, paddingBottom: 15, marginBottom: 5, borderBottomWidth: 1, borderBottomColor:' # ccc', flex: 1, flexDirection: 'row'}, news_item_text: {color:' # 5757}, fontSize: 18} Upvote: {flex: 2, paddingRight: 15, paddingLeft: 5, alignItems: 'center'}, news_title: {flex: 18, justifyContent:' center'}, upvote_text: {fontSize: 18, fontWeight: 'bold'}})

Develop server-side components

Now is the time to move to the server component's application, where you will learn how to save and RethinkDB,upvote news projects and how to notify the application that changes have taken place in the database.

Create a database

I assume that you have installed RethinkDB on your computer. Otherwise, please follow the instructions on the RethinkDB website (https://www.rethinkdb.com/docs/install/) should be installed first.

After installation, you can now open a browser to access http://localhost:8080 to view the RethinkDB Management console. Click on the Tables tab, and then click the Add Database button. This opens a modal window that allows you to enter the name of the database, call it newssharer, and * Click Click.

Now create the table in which you want to save the news item. Click the Add Table button, name it news_items, and then click Create Table.

Installation dependency

You can navigate to the root directory of the project (that is, where the newssharer-server.js and package.json files are located) and execute the npm install command to install the following server dependencies:

1.Express: a Node.js-based web framework that allows you to create web servers that respond to specific routes.

2.Body-parser: makes it easy to extract JSON strings from the body of the request.

RethinkDB client for 3.Rethinkdb:Node.js.

4.socket.io: a real-time framework that allows you to connect to all clients when someone shares news or votes yes to existing news.

Server-side programming

The code for the file newssharer-server.js is as follows:

Var r = require ('rethinkdb'); var express = require (' express'); var app = express (); var server = require ('http'). CreateServer (app); var io = require (' socket.io') (server); var bodyParser = require ('body-parser'); app.use (bodyParser.json ()); var connection; r.connect ({host:' localhost', port: 28015}, function (err, conn) {if (err) throw err; connection = conn R.db ('newssharer'). Table (' news_items') .orderBy ({index: r.desc ('upvotes')}) .changes () .run (connection, function (err, cursor) {if (err) throw err; io.sockets.on (' connection', function (socket) {cursor.each (function (err, row) {if (err) throw err; io.sockets.emit ('news_updated', row);}) App.get ('/ create-table', function (req, res) {r.db ('newssharer'). Table (' news_items'). IndexCreate ('upvotes') .run (connection, function (err, result) {console.log (' boom'); res.send ('ok')});}) App.get ('/ fill', function (req, res) {r.db ('newssharer'). Table (' news_items'). Insert ([{title:'A Conversation About Fantasy User Interfaces', url: 'https://www.subtraction.com/2016/06/02/a-conversation-about-fantasy-user-interfaces/', upvotes: 30}, {title:' Apple Cloud Services Outage', url: 'https://www.apple.com/support/systemstatus/', Upvotes: 20}]) .run (connection, function (err, result) {if (err) throw err Res.send ('news_items table was filings');});}); app.get ('/ news', function (req, res) {res.header ("Content-Type", "application/json"); r.db ('newssharer'). Table (' news_items') .orderBy ({index: r.desc ('upvotes')}) .limit (30) .run (connection, function (err, cursor) {if (err) throw err Cursor.toArray (function (err, result) {if (err) throw err; res.send (result);}); app.post ('/ save-newsitem', function (req, res) {var news_title = req.body.news_title; var news_url = req.body.news_url) R.db ('newssharer'). Table (' news_items'). Insert ([{'title': news_title,' url': news_url, 'upvotes': 100},]) .run (connection, function (err, result) {if (err) throw err; res.send (' ok');}); app.post ('/ upvote-newsitem', function (req, res) {var id = req.body.news_id) Var upvote_count = req.body.upvotes; r.db ('newssharer'). Table (' news_items') .filter (r.row ('id') .eq (id)) .update ({upvotes: upvote_count}) .run (connection, function (err, result) {if (err) throw err; res.send (' ok');});}) App.get ('/ test/upvote', function (req, res) {var id = '144f7d7d-d580-42b3-8704-8372e9b2a17c); var upvote_count = 350; r.db (' newssharer'). Table ('news_items') .filter (r.row (' id') .eq (id)) .update ({upvotes: upvote_count}) .run (connection, function (err, result) {if (err) throw err; res.send ('ok');});}) App.get ('/ test/save-newsitem', function (req, res) {r.db ('newssharer'). Table (' news_items'). Insert ([{'title':' banana', 'url':' http://banana.com', 'upvotes': 190,' downvotes': 0},]) .run (connection, function (err, result) {if (err) throw err; res.send ('ok');});}) Server.listen (3000)

In the above code, you first import the dependency:

Var r = require ('rethinkdb'); var express = require (' express'); var app = express (); var server = require ('http') .CreateServer (app); var io = require (' socket.io') (server); var bodyParser = require ('body-parser'); app.use (bodyParser.json ())

Then, create a variable to store the current RethinkDB connection.

Var connection

Listen for change

Connect to the RethinkDB database and run RethinkDB by default on port 28015 (that is, the address where the connection was created). If you want to use a different port, you can replace 28015 with the port you use.

R.connect ({host: 'localhost', port: 28015}, function (err, conn) {if (err) throw err; connection = conn;...})

Also in the database connection code, query the table news _ items in the newssharer database and sort the items by vote count. Then, use the Changefeeds feature of RethinkDB to listen for changes in the table (database sort log). This notification is issued every time a change occurs in the table (CRUD operation).

R.db ('newssharer'). Table (' news_items') .orderBy ({index: r.desc ('upvotes')}) .changes () .run (connection, function (err, cursor) {.})

In the callback function in the run method, initialize the socket connection and loop through the contents of the cursor. Cursor describes the changes made in the table. The cursor.each function is triggered each time a change occurs.

[note] this function does not contain all data changes. Get to replace the previous change whenever there is a new change. This means that only a single line can be traversed at any given time. This will allow you to use socket.io to send changes to the client.

If (err) throw err; / / check if there are errors and return it if any io.sockets.on ('connection', function (socket) {cursor.each (function (err, row) {if (err) throw err; io.sockets.emit (' news_updated', row);})

If news items are shared, each line has the following structure:

{"old_val": null, "new_val": {"id": 1, "news_title": "Google", "news_url": "http://google.com"," upvotes ": 0}

This is why null is checked in the previous code, because a new news item will not have an old_val.

If the user votes in favor of a news item:

{"old_val": {"id": 1, "news_title": "Google", "news_url": "http://google.com"," upvotes ": 0}" new_val ": {" id ": 1," news_title ":" Google "," news_url ":" http://google.com", "upvotes": 1}}

Then, the complete structure in the row corresponding to the old and new values is returned. This means that you can update multiple fields on one client and send all these changes to other connected clients. With the help of the changfeeds feature of RethinkDB, it is very easy to develop real-time applications based on RethinkDB.

Add an index to the Upvotes field

The following route adds an index to the upvotes field:

App.get ('/ add-index', function (req, res) {r.db ('newssharer'). Table (' news_items'). IndexCreate ('upvotes') .run (connection, function (err, result) {res.send (' ok')});})

The above index creation operation is necessary for the orderBy function because it requires that the fields you sort have an index.

.orderBy ({index: r.desc ('upvotes')})

When the server is running, be sure to open the URL http://localhost:3000/add-index in your browser before testing the application. Note that the above route only needs to be called once.

Add an empty news item

The following route inserts an empty entry in the news_ items table. In fact, this is an optional feature for testing purposes; in this way, you will immediately see a new item in the table without using the program addition.

App.get ('/ fill', function (req, res) {r.db ('newssharer'). Table (' news_items'). Insert ([{title:'A Conversation About Fantasy User Interfaces', url: 'https://www.subtraction.com/2016/06/02/a-conversation-about-fantasy-user-interfaces/', upvotes: 30}, {title:' Apple Cloud Services Outage', url: 'https://www.apple.com/support/systemstatus/', Upvotes: 20}]) .run (connection, function (err, result) {if (err) throw err Res.send ('news_items table was filtered');});})

Return to news items

The following route returns the news item:

App.get ('/ news', function (req, res) {res.header ("Content-Type", "application/json"); r.db ('newssharer'). Table (' news_items') .orderBy ({index: r.desc ('upvotes')}) .limit (30) .run (connection, function (err, cursor) {if (err) throw err; cursor.toArray (function (err, result) {if (err) throw err; res.send (result);}) );})

Note that the news item is sorted in the order from the highest to the lowest number of votes in favour and is limited to a maximum of 30. In addition, instead of using cursor.each to traverse news items, you use cursor.toArray to convert news items into an array with the following structure:

[{"title": "A Conversation About Fantasy User Interfaces", "url": "https://www.subtraction.com/2016/06/02/a-conversation-about-fantasy-user-interfaces/"," upvotes ": 30}, {" title ":" Apple Cloud Services Outage "," url ":" https://www.apple.com/support/systemstatus/", "upvotes": 20}]

Create and save news items

The following routes implement the function of creating and saving news items:

App.post ('/ save-newsitem', function (req, res) {var news_title = req.body.news_title; var news_url = req.body.news_url; r.db ('newssharer'). Table (' news_items'). Insert ([{'title': news_title,' url': news_url, 'upvotes': 100},]) .run (connection, function (err, result) {if (err) throw err; res.send (' ok') );})

The above route is invoked when a user shares a news item in the application. It receives news headlines and URL data from the Request Body. The initial number of yes votes is set to 100, but you can choose another number.

Vote in favour of news items

The following routing implements the ability to vote for news items:

App.post ('/ upvote-newsitem', function (req, res) {var id = req.body.news_id; var upvote_count = req.body.upvotes; r.db ('newssharer'). Table (' news_items') .filter (r.row ('id') .eq (id)) .update ({upvotes: upvote_count}) .run (connection, function (err, result) {if (err) throw err; res.send (' ok');});})

The routing function above will be called when the user votes yes to the news item in the program. This function uses the ID of the news item to retrieve the news data and update it.

[note] you have added 1 to the upvotes value in your application; therefore, you have provided the data in the request Request Body.

Test save and vote yes function

So far, we have established several routes. Now, you might as well test the save function and vote yes function. The time to implement this test is when the application is already running on a mobile device. In this way, you can see UI updates. We will discuss how to run the program in the next section.

The following routing implements the test save function:

App.get ('/ test/save-newsitem', function (req, res) {r.db ('newssharer'). Table (' news_items'). Insert ([{'title':' banana', 'url':' http://banana.com', 'upvotes': 190,' downvotes': 0},]) .run (connection, function (err, result) {if (err) throw err; res.send ('ok');});})

The following route implements the test function of voting yes to news items. Remember to replace the ID in the program with the ID of the existing news items for the test to work properly:

App.get ('/ test/upvote', function (req, res) {var id = '144f7d7d-d580-42b3-8704-8372e9b2a17c); var upvote_count = 350; r.db (' newssharer'). Table ('news_items') .filter (r.row (' id') .eq (id)) .update ({upvotes: upvote_count}) .run (connection, function (err, result) {if (err) throw err; res.send ('ok');});})

Run the server-side program

At this point, I assume that RethinkDB has been running in the background. If it's not already up and running, run it first. Once RethinkDB is running, you can execute the command node newssharer-server.js from the project root to run the server-side components of the program.

Thank you for your reading, the above is the content of "how to develop Web applications based on RethinkDB + React Native". After the study of this article, I believe you have a deeper understanding of how to develop Web applications based on RethinkDB + React Native. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report