Skip to content

Latest commit

 

History

History
378 lines (281 loc) · 19.9 KB

README.adoc

File metadata and controls

378 lines (281 loc) · 19.9 KB

Consuming a RESTful web service with ReactJS

Note
This repository contains the guide documentation source. To view the guide in published form, view it on the Open Liberty website.

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

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.

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 Next.js, a React-powered framework, to set up the modern React application. The Next.js framework provides a powerful environment for learning and building React applications, with features like server-side rendering, static site generation, and easy API routes. It is the best way to start building a highly performant React application.

artists.json

link:finish/src/resources/artists.json[role=include]

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 artists.json file 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 web page.

To learn more about REST services and how you can write them, see the Creating a RESTful web service guide.

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/_next/static directory.

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:

cd finish
mvn process-resources
mvn liberty:run

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

The defaultServer server is ready to run a smarter planet.

Next, point your browser to the http://localhost:9080 web application root to see the following output:

React Paginated Table

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.

After you start the service, you can find your artist JSON at the http://localhost:9080/artists URL.

All the dependencies for the React front end are listed in the src/main/frontend/src/package.json file and are installed before the build process by the frontend-maven-plugin. Also, CSS stylesheets files are available in the src/main/frontend/src/styles directory.

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, 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 Node.js documentation.

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.

The maven-resources-plugin copies the static content from the build directory to the web content of the application.

pom.xml

link:finish/pom.xml[role=include]

Creating the default page

Create the entry point of your React application. The latest version of Next.js recommends you use the App Router, which centralizes routing logic under the app directory.

To construct the home page of the web application, create a page.jsx file.

Create the page.jsx file.
src/main/frontend/src/app/page.jsx

page.jsx

link:finish/src/main/frontend/src/app/page.jsx[role=include]

The page.jsx file is a container for all other components. When the Home React component is rendered, the ArtistTable components content are displayed.

To render the pages correctly, add a layout.jsx file that defines the RootLayout containing the UI that are shared across all routes.

Create the layout.jsx file.
src/main/frontend/src/app/layout.jsx

layout.jsx

link:finish/src/main/frontend/src/app/layout.jsx[role=include]

For more detailed information, see the Next.js documentation on Pages and Layouts.

Creating the React component

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

Create the ArtistTable function that fetches data from your back-end and renders it in a table.

Create the ArtistTable.jsx file.
src/main/frontend/src/app/ArtistTable.jsx

ArtistTable.jsx

link:finish/src/main/frontend/src/app/ArtistTable.jsx[role=include]

At the beginning of the file, the use client directive indicates the ArtistTable component is rendered on the client side.

The React library imports the react package for you to create the ArtistTable function. This function must have the export declaration because it is being exported to the page.jsx module. The 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 you can use it for handling data sets in React. In your application, you’ll render the columns in the paginated table. The columns constant defines the table that is present on the web page.

The useReactTable hook creates a table instance. The hook takes in the columns and posts as parameters. The getCoreRowModel function is included for the generation of the core row model of the table, which serves as the foundational row model upon pagination and sorting build. The getPaginationRowModel function applies pagination to the core row model, returning a row model that includes only the rows that should be displayed on the current page based on the pagination state. In addition, the getSortedRowModel function sorts the paginated table by the column headers then applies the changes to the row model. The paginated table instance is assigned to the table constant, which renders the paginated table on the web page.

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 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 Axios documentation.

The 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 useEffect() React lifecycle method.

Update the ArtistTable.jsx file.
src/main/frontend/src/app/ArtistTable.jsx

ArtistTable.jsx

link:finish/src/main/frontend/src/app/ArtistTable.jsx[role=include]

Add the axios library and the GetArtistsInfo() function.

The 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 response.data to posts. The artists and their albums JSON data are manipulated to allow them to be accessed by the ReactTable. The …​rest or …​album object spread syntax is designed for simplicity. To learn more about it, see Spread in object literals.

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:

mvn process-resources

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.

Navigate to the http://localhost:9080 web application root to view the front end of your application.

Testing the React client

Next.js supports various testing tools. This guide uses Vitest for unit testing the React components, with the test file App.test.jsx located in src/main/frontend/tests/ directory. The App.test.jsx file is a simple JavaScript file that tests against the page.jsx component. No explicit test cases are written for this application. To learn more about Vitest, see Setting up Vitest with Next.js.

App.test.jsx

link:finish/src/main/frontend/__tests__/App.test.jsx[role=include]
Update the pom.xml file.
pom.xml

pom.xml

link:finish/pom.xml[role=include]

To run the default test, you can add the testing configuration to the frontend-maven-plugin. Rerun the Maven process-resources goal to rebuild the front end and run the tests.

mvn process-resources

If the test passes, you see a similar output to the following example:

[INFO]  ✓ __tests__/App.test.jsx  (1 test) 96ms
[INFO]
[INFO]  Test Files  1 passed (1)
[INFO]       Tests  1 passed (1)
[INFO]    Start at  10:43:25
[INFO]    Duration  3.73s (transform 264ms, setup 0ms, collect 343ms, tests 96ms, environment 408ms, prepare 1.16s)

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 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.