Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/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://github.com/openliberty/guide-rest-client-reactjs
Last synced: 27 days ago
JSON representation
A guide on how to access a simple RESTful web service and consume its resources with ReactJS in Open Liberty.
- Host: GitHub
- URL: https://github.com/openliberty/guide-rest-client-reactjs
- Owner: OpenLiberty
- License: other
- Created: 2020-03-19T18:29:31.000Z (almost 5 years ago)
- Default Branch: prod
- Last Pushed: 2024-12-04T16:44:31.000Z (about 2 months ago)
- Last Synced: 2024-12-04T17:38:52.400Z (about 2 months ago)
- Language: JavaScript
- Homepage: https://openliberty.io/guides/rest-client-reactjs.html
- Size: 4.92 MB
- Stars: 2
- Watchers: 5
- Forks: 1
- Open Issues: 1
-
Metadata Files:
- Readme: README.adoc
- Contributing: CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
README
// Copyright (c) 2020, 2024 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-majorupdateddate: 2024-08-22
: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 https://nextjs.org/[Next.js^], a https://react.dev/learn/start-a-new-react-project[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
[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` 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 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/_next/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 process-resources
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:
```bash
cd finish
mvn process-resources
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/webapp/_next/static/chunks/app/page-*.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/app/ArtistTable.jsx
```To try out the application, run the following Maven goal to build the application and deploy it to Open Liberty:
```bash
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, click the following button to check out the application:::startApplication{port="9080" display="external" name="Visit application" route="/"}
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[]
```bash
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.
```bash
curl -s http://localhost:9080/artists | jq
```
endif::[]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
// =================================================================================================== 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
Create the entry point of your React application. The latest version of `Next.js` recommends you use the https://nextjs.org/docs/app/building-your-application/routing/defining-routes[App Router^], which centralizes routing logic under the `app` directory.
To construct the home page of the web application, create a [hotspot file=0]`page.jsx` file.[role="code_command hotspot file=0", subs="quotes"]
----
#Create the `page.jsx` file.#
`src/main/frontend/src/app/page.jsx`
----page.jsx
[source, javascript, linenums, role='code_column']
----
include::finish/src/main/frontend/src/app/page.jsx[]
----The `page.jsx` file is a container for all other components. When the [hotspot=createHome file=0]`Home` React component is rendered, the [hotspot=displayArtistTable file=0]`ArtistTable` components content are displayed.
To render the pages correctly, add a [hotspot file=1]`layout.jsx` file that defines the `RootLayout` containing the UI that are shared across all routes.
[role="code_command hotspot file=1", subs="quotes"]
----
#Create the `layout.jsx` file.#
`src/main/frontend/src/app/layout.jsx`
----layout.jsx
[source, javascript, linenums, role='code_column']
----
include::finish/src/main/frontend/src/app/layout.jsx[]
----For more detailed information, see the `Next.js` documentation on https://nextjs.org/docs/app/building-your-application/routing/pages[Pages^] and https://nextjs.org/docs/app/building-your-application/routing/layouts-and-templates[Layouts^].
// =================================================================================================
// Creating the React component
// =================================================================================================== 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.
[role="code_command hotspot file=0", subs="quotes"]
----
#Create the `ArtistTable.jsx` file.#
`src/main/frontend/src/app/ArtistTable.jsx`
----ArtistTable.jsx
[source, javascript, linenums, role='code_column hide_tags=get-posts,useEffect,axios-library']
----
include::finish/src/main/frontend/src/app/ArtistTable.jsx[]
----At the beginning of the file, the [hotspot=render-client file=0]`use client` directive indicates the `ArtistTable` component is rendered on the client side.
The [hotspot=react-library file=0]`React` library imports the `react` package for you to create the [hotspot=ArtistTable file=0]`ArtistTable` function. This function must have the `export` declaration because it is being exported to the `page.jsx` module. The [hotspot=posts file=0]`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 [hotspot=table-info file=0]`columns` constant defines the table that is present on the web page.
The [hotspot=useReactTable file=0]`useReactTable` hook creates a table instance. The hook takes in the [hotspot=table-info file=0]`columns` and [hotspot=posts file=0]`posts` as parameters. The [hotspot=getCoreRowModel file=0]`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 [hotspot=getPaginationRowModel file=0]`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 [hotspot=getSortedRowModel file=0]`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 [hotspot=table file=0]`table` constant, which renders the paginated table on the web page.
// =================================================================================================
// 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.jsx` file.#
`src/main/frontend/src/app/ArtistTable.jsx`
----ArtistTable.jsx
[source, javascript, linenums, role='code_column']
----
include::finish/src/main/frontend/src/app/ArtistTable.jsx[]
----[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.jsx*** file:
```bash
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/app/ArtistTable.jsx
```
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[]
```bash
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[]
Click the following button to view the front end of your application:::startApplication{port="9080" display="external" name="Visit application" route="/"}
endif::[]// =================================================================================================
// Testing the React client
// =================================================================================================== Testing the React client
`Next.js` supports various testing tools. This guide uses `Vitest` for unit testing the React components, with the test file [hotspot 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 https://nextjs.org/docs/app/building-your-application/testing/vitest[Setting up Vitest with Next.js^].
App.test.jsx
[source, javascript, linenums, role='code_column']
----
include::finish/src/main/frontend/__tests__/App.test.jsx[]
----[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.ifndef::cloud-hosted[]
[role='command']
----
mvn process-resources
----
endif::[]
// Cloud hosted guide instruction
ifdef::cloud-hosted[]
```bash
cd /home/project/guide-rest-client-reactjs/start
mvn process-resources
```
endif::[]If the test passes, you see a similar output to the following example:
[source, role='no_copy']
----
[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 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"]