OpenLiberty / guide-rest-client-reactjs

A guide on how to access a simple RESTful web service and consume its resources with ReactJS in Open Liberty.
https://openliberty.io/guides/rest-client-reactjs.html
Other
1 stars 1 forks source link

// Copyright (c) 2020, 2023 IBM Corporation and others. // Licensed under Creative Commons Attribution-NoDerivatives // 4.0 International (CC BY-ND 4.0) // https://creativecommons.org/licenses/by-nd/4.0/ // // Contributors: // IBM Corporation :projectid: rest-client-reactjs :page-layout: guide-multipane :page-duration: 20 minutes :page-description: Explore how to access a simple RESTful web service and consume its resources with ReactJS in Open Liberty. :page-releasedate: 2020-07-23 :page-related-guides: ['rest-intro', 'rest-client-java'] :page-permalink: /guides/{projectid} :imagesdir: /img/guide/{projectid} :common-includes: https://raw.githubusercontent.com/OpenLiberty/guides-common/prod :source-highlighter: prettify :page-seo-title: Consuming a RESTful Java web service with ReactJS :page-seo-description: A getting started tutorial with examples on how to access a RESTful Java micoservice and deserialize the returned JSON in React Table 7 of ReactJS. :guide-author: Open Liberty = Consuming a RESTful web service with ReactJS

[.hidden] NOTE: This repository contains the guide documentation source. To view the guide in published form, view it on the https://openliberty.io/guides/{projectid}.html[Open Liberty website].

Explore how to access a simple RESTful web service and consume its resources with ReactJS in Open Liberty.

// ================================================================================================= // Introduction // =================================================================================================

== What you'll learn

You will learn how to access a REST service and deserialize the returned JSON that contains a list of artists and their albums by using an HTTP client with the ReactJS library. You will then present this data by using a ReactJS paginated table component.

https://reactjs.org/[ReactJS^] is a JavaScript library that is used to build user interfaces. Its main purpose is to incorporate a component-based approach to create reusable UI elements. With ReactJS, you can also interface with other libraries and frameworks. Note that the names ReactJS and React are used interchangeably.

The React application in this guide is provided and configured for you in the src/main/frontend directory. The application uses the https://reactjs.org/docs/create-a-new-react-app.html[Create React App^] prebuilt configuration to set up the modern single-page React application. The https://github.com/facebook/create-react-app[create-react-app^] integrated toolchain is a comfortable environment for learning React and is the best way to start building a new single-page application with React.

artists.json [source, json, linenums, role="code_column"]

include::finish/src/resources/artists.json[]

The REST service that provides the resources was written for you in advance in the back end of the application, and it responds with the [hotspot]artists.json in the src/resources directory. You will implement a ReactJS client as the front end of your application, which consumes this JSON file and displays its contents on a single-page webpage.

To learn more about REST services and how you can write them, see the https://openliberty.io/guides/rest-intro.html[Creating a RESTful web service^] guide.

// ================================================================================================= // Getting Started // ================================================================================================= [role='command'] include::{common-includes}/gitclone.adoc[]

// ================================================================================================= // Try what you'll build // =================================================================================================

=== Try what you'll build

The finish directory in the root of this guide contains the finished application. The React front end is already pre-built for you and the static files from the production build can be found in the src/main/webapp/static directory.

ifndef::cloud-hosted[] To try out the application, navigate to the finish directory and run the following Maven goal to build the application and deploy it to Open Liberty:

[role='command']

cd finish
mvn liberty:run

endif::[]

ifdef::cloud-hosted[] In this IBM cloud environment, you need to update the URL to access the artists.json. Run the following commands to go to the finish directory and update the files where the URL has been specified:

cd finish
sed -i 's=http://localhost:9080/artists='"https://${USERNAME}-9080.$(echo $TOOL_DOMAIN | sed 's/\.labs\./.proxy./g')/artists"'=' src/main/webapp/static/js/main.2d7e902e.js
sed -i 's=http://localhost:9080/artists='"https://${USERNAME}-9080.$(echo $TOOL_DOMAIN | sed 's/\.labs\./.proxy./g')/artists"'=' /home/project/guide-rest-client-reactjs/finish/src/main/frontend/src/Components/ArtistTable.js

To try out the application, run the following Maven goal to build the application and deploy it to Open Liberty:

mvn liberty:run

endif::[]

After you see the following message, your application Liberty instance is ready:

[role="no_copy"]

The defaultServer server is ready to run a smarter planet.

ifndef::cloud-hosted[] Next, point your browser to the http://localhost:9080[http://localhost:9080^] web application root to see the following output: endif::[]

ifdef::cloud-hosted[] When the Liberty instance is running, select Terminal > New Terminal from the menu of the IDE to open another command-line session. Open your browser and check out the application by going to the URL that the following command returns:

echo http://${USERNAME}-9080.$(echo $TOOL_DOMAIN | sed 's/\.labs\./.proxy./g')

See the following output: endif::[]

image::react-table.png[React Paginated Table,align="center"]

[role='command'] include::{common-includes}/twyb-end.adoc[]

// ================================================================================================= // Starting the service // =================================================================================================

== Starting the service

Before you begin the implementation, start the provided REST service so that the artist JSON is available to you.

Navigate to the start directory to begin. // cloud hosted instructions ifdef::cloud-hosted[]

cd /home/project/guide-rest-client-reactjs/start

endif::[]

[role='command'] include::{common-includes}/devmode-lmp33-start.adoc[]

ifndef::cloud-hosted[] After you start the service, you can find your artist JSON at the http://localhost:9080/artists[http://localhost:9080/artists^] URL. endif::[]

ifdef::cloud-hosted[] After the Liberty instance is started, run the following curl command to view your artist JSON.

curl -s http://localhost:9080/artists | jq

endif::[]

All the dependencies for the React front end can be found in src/main/frontend/src/package.json, and they are installed before the front end is built by the frontend-maven-plugin. Additionally, some provided CSS stylesheets files are provided and can be found in the src/main/frontend/src/Styles directory.

// ================================================================================================= // Project configuration // =================================================================================================

== Project configuration

The front end of your application uses Node.js to build your React code. The Maven project is configured for you to install Node.js and produce the production files, which are copied to the web content of your application.

Node.js is a server-side JavaScript runtime that is used for developing networking applications. Its convenient package manager, https://www.npmjs.com/[npm^], is used to run the React build scripts that are found in the package.json file. To learn more about Node.js, see the official https://nodejs.org/en/docs/[Node.js documentation^].

ifndef::cloud-hosted[] The [hotspot=frontend-plugin]frontend-maven-plugin is used to [hotspot=node-resource-install]install the dependencies that are listed in your package.json file from the npm registry into a folder called node_modules. The node_modules folder can be found in your [hotspot=working-dir]working directory. Then, the configuration [hotspot=node-resource-build]produces the production files to the src/main/frontend/build directory. endif::[]

ifdef::cloud-hosted[] Take a look at the pom.xml file.

From the menu of the IDE, select File > Open > guide-rest-client-reactjs/start/pom.xml, or click the following button ::openFile{path="/home/project/guide-rest-client-reactjs/start/pom.xml"}

The frontend-maven-plugin is used to install the dependencies that are listed in your package.json file from the npm registry into a folder called node_modules. The node_modules folder can be found in your working directory. Then, the configuration produces the production files to the src/main/frontend/build directory. endif::[]

The [hotspot=copy-plugin]maven-resources-plugin copies the static content from the [hotspot=directory]build directory to the [hotspot=output-directory]web content of the application.

pom.xml [source, xml, linenums, role='code_column hide_tags=node-tests']

include::finish/pom.xml[]

== Creating the default page

You need to create the entry point of your React application. create-react-app uses the [hotspot file=0]index.js file as the main entry point of the application. This JavaScript file corresponds with the [hotspot file=1]index.html file, which is the entry point where your code runs in the browser.

[role="code_command hotspot", subs="quotes"]

Create the index.js file.

src/main/frontend/src/index.js

index.js [source, javascript, linenums, role='code_column']

include::finish/src/main/frontend/src/index.js[]

index.html [source, html, linenums, role='code_column tags=html hide_tags=copyright']

include::finish/src/main/frontend/public/index.html[]

The [hotspot=import-react file=0]React library imports the [hotspot=import-react file=0]react package. A DOM, or Document Object Model, is a programming interface for HTML and XML documents. React offers a virtual DOM, which is essentially a copy of the browser DOM that resides in memory. The React virtual DOM improves the performance of your web application and plays a crucial role in the rendering process. The [hotspot=react-dom file=0]react-dom package provides DOM-specific methods that can be used in your application to get outside of the React model, if necessary.

The [hotspot=dom-render file=0]render method takes an HTML DOM element and tells the ReactDOM to render your React application inside of this DOM element. To learn more about the React virtual DOM, see the https://reactjs.org/docs/react-dom.html[ReactDOM^] documentation.

// ================================================================================================= // Creating the React components // =================================================================================================

== Creating the React components

A React web application is a collection of components, and each component has a specific function. You will create the components that are used in the application to acquire and display data from the REST API.

The main component in your React application is the App component. You need to create the [hotspot file=0]App.js file to act as a container for all other components.

[role="code_command hotspot file=0", subs="quotes"]

Create the App.js file.

src/main/frontend/src/Components/App.js

App.js [source, javascript, linenums, role='code_column']

include::finish/src/main/frontend/src/Components/App.js[]

The App.js file returns the [hotspot=react-component file=0]ArtistTable function to create a reusable element that encompasses your web application.

Next, create the ArtistTable function that fetches data from your back end and renders it in a table.

[role="code_command hotspot file=1", subs="quotes"]

Create the ArtistTable.js file.

src/main/frontend/src/Components/ArtistTable.js

ArtistTable.js [source, javascript, linenums, role='code_column hide_tags=get-posts,useEffect,axios-library']

include::finish/src/main/frontend/src/Components/ArtistTable.js[]

The [hotspot=react-library file=1]React library imports the react package for you to create the [hotspot=ArtistTable file=1]ArtistTable function. This function must have the export declaration because it is being exported to the App.js module. The [hotspot=posts file=1]posts object is initialized using a React Hook that lets you add a state to represent the state of the posts that appear on the paginated table.

To display the returned data, you will use pagination. Pagination is the process of separating content into discrete pages, and it can be used for handling data sets in React. In your application, you'll render the columns in the paginated table. The [hotspot=table-info file=1]columns constant is used to define the table that is present on the webpage.

The [hotspot=useTable file=1]useTable hook creates a paginated table. The useTable hook takes in the [hotspot=table-info file=1]columns, [hotspot=posts file=1]posts, and setPosts objects as parameters. It returns a paginated table that is assigned to the [hotspot=table file=1]table constant. The [hotspot=table file=1]table constant renders the paginated table on the webpage. The [hotspot=return-table file=1]return statement returns the paginated table. The [hotspot=useSortBy file=1]useSortBy hook sorts the paginated table by the column headers. The [hotspot=usePagination file=1]usePagination hook creates the pagination buttons at the bottom of the table that are used to navigate through the paginated table.

// ================================================================================================= // Importing the HTTP client // =================================================================================================

=== Importing the HTTP client

Your application needs a way to communicate with and retrieve resources from RESTful web services to output the resources onto the paginated table. The https://github.com/axios/axios[Axios^] library will provide you with an HTTP client. This client is used to make HTTP requests to external resources. Axios is a promise-based HTTP client that can send asynchronous requests to REST endpoints. To learn more about the Axios library and its HTTP client, see the https://www.npmjs.com/package/axios[Axios documentation^].

The [hotspot=get-posts]GetArtistsInfo() function uses the Axios API to fetch data from your back end. This function is called when the ArtistTable is rendered to the page using the [hotspot=useEffect]useEffect() React lifecycle method.

[role="code_command hotspot", subs="quotes"]

Update the ArtistTable.js file.

src/main/frontend/src/Components/ArtistTable.js

ArtistTable.js [source, javascript, linenums, role='code_column']

include::finish/src/main/frontend/src/Components/ArtistTable.js[]

[role="edit_command_text"] Add the [hotspot=axios-library]axios library and the [hotspot=get-posts]GetArtistsInfo() function.

The [hotspot=axios]axios HTTP call is used to read the artist JSON that contains the data from the sample JSON file in the resources directory. When a response is successful, the state of the system changes by assigning [hotspot=response-data]response.data to [hotspot=posts]posts. The [hotspot=for-artists]artists and their albums JSON data are manipulated to allow them to be accessed by the ReactTable. The [hotspot=spread-one]...rest or [hotspot=spread-two]...album object spread syntax is designed for simplicity. To learn more about it, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals[Spread in object literals^].

ifdef::cloud-hosted[] Finally, run the following command to update the URL to access the artists.json in the ArtistTable.js file:

sed -i 's=http://localhost:9080/artists='"https://${USERNAME}-9080.$(echo $TOOL_DOMAIN | sed 's/\.labs\./.proxy./g')/artists"'=' /home/project/guide-rest-client-reactjs/start/src/main/frontend/src/Components/ArtistTable.js

endif::[]

// ================================================================================================= // Building and packaging the front end // =================================================================================================

== Building and packaging the front end

After you successfully build your components, you need to build the front end and package your application. The Maven process-resources goal generates the Node.js resources, creates the front-end production build, and copies and processes the resources into the destination directory.

In a new command-line session, build the front end by running the following command in the start directory:

// Static guide instruction ifndef::cloud-hosted[] [role='command']

mvn process-resources

endif::[] // Cloud hosted guide instruction ifdef::cloud-hosted[]

cd /home/project/guide-rest-client-reactjs/start
mvn process-resources

endif::[]

The build may take a few minutes to complete. You can rebuild the front end at any time with the Maven process-resources goal. Any local changes to your JavaScript and HTML are picked up when you build the front end.

ifndef::cloud-hosted[] Navigate to the http://localhost:9080[http://localhost:9080^] web application root to view the front end of your application. endif::[]

ifdef::cloud-hosted[] Open your browser and view the front end of your application by going to the URL that the following command returns:

echo http://${USERNAME}-9080.$(echo $TOOL_DOMAIN | sed 's/\.labs\./.proxy./g')

endif::[]

// ================================================================================================= // Testing the React client // =================================================================================================

== Testing the React client

New projects that are created with create-react-app comes with a test file called [hotspot file]App.test.js, which is included in the src/main/frontend/src directory. The App.test.js file is a simple JavaScript file that tests against the App.js component. There are no explicit test cases that are written for this application. The create-react-app configuration uses https://jestjs.io/[Jest^] as its test runner. To learn more about Jest, go to their documentation on https://jestjs.io/docs/en/tutorial-react[Testing React apps^].

App.test.js [source, javascript, linenums, role='code_column']

include::finish/src/main/frontend/src/App.test.js[]

[role="code_command hotspot file=1", subs="quotes"]

Update the pom.xml file.

pom.xml

pom.xml [source, xml, linenums, role='code_column']

include::finish/pom.xml[]

[role="edit_command_text"] To run the default test, you can add the [hotspot=node-tests file=1]testing configuration to the frontend-maven-plugin. Rerun the Maven process-resources goal to rebuild the front end and run the tests.

Although the React application in this guide is simple, when you build more complex React applications, testing becomes a crucial part of your development lifecycle. If you need to write application-oriented test cases, follow the official https://reactjs.org/docs/testing.html[React testing documentation^].

When you are done checking the application root, exit dev mode by pressing CTRL+C in the shell session where you ran the Liberty.

== Great work! You're done!

Nice work! You just accessed a simple RESTful web service and consumed its resources by using ReactJS in Open Liberty.

include::{common-includes}/attribution.adoc[subs="attributes"]