I wrote this tutorial to help you quickly generate react hooks library for your organization from your swagger files and get familiar with how it works. πŸ€“

Prerequisites

It is ideal for you if you have little knowledge and experience with react, swagger and react hooks. Incase you are yet to explore those, here are some quick links.

Introduction

Assuming you have the required knowledge, let’s begin with the introduction! 😎

For this tutorial, we are going to use the Swagger Petstore.

https://petstore.swagger.io/v2/swagger.json

We are going to create a react hooks library for the swagger pet store that we would be using in our front end applications powered by react.

The goal of this tutorial is to auto generate these hooks avoiding any manual code needed.

The developers would then use this auto generated hooks library to interact with the API.

Getting Started

Let us begin by creating a boilerplate code using the create-react-library npm package.

create-react-library has an easy to use CLI. It handles all the modern JS features and bundles into commonjs and es module formats perfect for our react library.

Install Globally

For this package to work, you need node >= v10.

npm install -g create-react-library

Or Use npx

npx create-react-library

npx comes with npm 5.2+ and higher

Create Boilerplate Code

Boilerplate Code Animated GIF

In the parent directory of the project, run the following command

create-react-library petstore-hooks

Follow the prompts in the terminal. This will create a petstore-hooks project with the template files and install the dependencies via yarn or npm based on your selection. It also initializes an git repo with the boilerplate code.

Your project should look like this

β”œβ”€β”€ README.md
β”œβ”€β”€ example
|  β”œβ”€β”€ README.md
|  β”œβ”€β”€ package.json
|  β”œβ”€β”€ public
|  β”œβ”€β”€ src
|  β”œβ”€β”€ tsconfig.json
|  └── yarn.lock
β”œβ”€β”€ node_modules
β”œβ”€β”€ package.json
β”œβ”€β”€ src
|  β”œβ”€β”€ index.test.tsx
|  β”œβ”€β”€ index.tsx
|  β”œβ”€β”€ styles.module.css
|  └── typings.d.ts
β”œβ”€β”€ tsconfig.json
β”œβ”€β”€ tsconfig.test.json
└── yarn.lock

Add Dependencies

We are going to use restful-react npm package to generate the react hooks.

restful-react is able to generate React hooks with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in yaml or json formats.

Let’s add that as a peer dependency. This means that any project using this library would need to have restful-react installed.

yarn add --peer restful-react

Also add as devdependency for development.

yarn add -D restful-react

We do not add this as a project dependency just to lighten the package size of our npm module. To know more about peer dependencies, click here.

Configure

Let us create a configuration file for the restful-react to generate the hooks for us.

Using a Swagger URL

// ./restful-react.config.js
module.exports = {
  petstore: {
    output: 'src/client/petstore.tsx',
    url: 'https://petstore.swagger.io/v2/swagger.json',
    customProps: {
      base: `"https://petstore.swagger.io/v2"`,
    },
  },
};

Using a Swagger file

Copy the swagger file to the ./src folder in the project.

Then make the following change to the configuration.

module.exports = {
  petstore: {
    output: 'src/client/petstore.tsx',
-   url: 'https://petstore.swagger.io/v2/swagger.json',
+   file: 'src/PATH_TO_JSON_OR_YML_FILE',
    customProps: {
      base: `"https://petstore.swagger.io/v2"`,
    },
  },
};

Add Script to package.json

{
  ...
  "scripts": {
    ...
    "gen": "restful-react import --config restful-react.config.js",
    "prebuild": "run-s gen"
  },
  ...
}

Generate

Now, run the following command

yarn run gen

This will generate a typescript file src/client/petstore.tsx with all the react hooks!

Export the hooks

Let’s export the hooks from the src/index.tsx file, so that the hooks could be used externally. Replace contents of the src/index.tsx file with the following:

// ./src/index.tsx
export * from './client/petstore';

Build the library

The prebuild command in the package.json would automatically generate the react hooks and then build the library.

Using the library

create-react-library comes with an example folder to start testing your library right out of the box.

Using hooks

Let’s open the example/src/App.tsx file in editor. In a terminal run the command yarn start in the library root folder. In another terminal run the same command in example folder.

The terminals would watch the library and rebuild incase a change occurs.

Let us use a simple get hook that we generated from the petstore swagger.

Your file should look like this

// ./example/src/App.tsx
import React from 'react';

import { ExampleComponent } from 'petstore-hooks';
import 'petstore-hooks/dist/index.css';

const App = () => {
  return <ExampleComponent text="Create React Library Example πŸ˜„" />;
};

export default App;

let’s start making changes to add hooks

import React from 'react';

- import { ExampleComponent } from 'petstore-hooks';
+ import { useGetPetById } from 'petstore-hooks';
- import 'petstore-hooks/dist/index.css';

- const App = () => {
+ const App = ({ id }) => {
+   const { data, loading, error } = useGetPetById({ lazy: !id, petId: id });
+ if (loading) return <div>Loading...</div>;
+ if (error) return <div>Error!</div>;
-  return <ExampleComponent text="Create React Library Example πŸ˜„" />;
+ return <div>{JSON.stringify(data)}</div>;
};

export default App;

Your code should look like this:

import React from 'react';
import { useGetPetById } from 'petstore-hooks';

const App = ({ id }) => {
  const { data, loading, error } = useGetPetById({ lazy: !id, petId: id });
  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error!</div>;
  return <div>{JSON.stringify(data)}</div>;
};

export default App;

Publish

To publish the generated hooks library to npm run the following command. Make sure that you are already logged in!

yarn publish

Use Locally

You could also use the package locally in any other npm projects using yarn link. Run the following command in the project root.

yarn link

Then, in the project that want to add this library to, run the command again

yarn link "petstore-hooks"

Conclusion

Congratulations πŸ₯³ !

You just created your very own react hooks library using auto generated code!

To get more details and example uses, please refer the restful-react documentation.

I hope that this tutorial was easy enough to follow. You could now use these hooks in your frontend and accelerate your development skills and time!

Until next time!

Buy Me A Coffee