npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@twoday/react-openapi-client-generator

v1.0.1

Published

Generate typed hooks and methods for React app from OpenAPI schema.

Downloads

48

Readme

@twoday/react-openapi-client-generator

Generate typed hooks and methods for React app from OpenAPI schema.

TodoMVC example

Setup in Create React App

  1. Install: npm i @twoday/react-openapi-client-generator

  2. Add API schema JSON, e.g. src/petstore.json (examples)

  3. Add scripts to package.json:

    JavaScript:

    "generate-client": "react-openapi-client-generator src/petstore.json src/client.js",
    "prestart": "npm run generate-client",
    "prebuild": "npm run generate-client",

    TypeScript:

    "generate-client": "react-openapi-client-generator src/petstore.json src/client.ts",
    "prestart": "npm run generate-client",
    "prebuild": "npm run generate-client",
  4. Add .gitignore

    # generated
    /src/client.js
  5. Use <Suspense> to show a loading indicator(s)

  6. Use Error Boundary to handle errors

Options

--add-loaders

Include the API schema in the bundle. Example: react-openapi-client-generator src/petstore.json src/client.ts --add-loaders.

This will prefix the import path with !json-loader! and with yaml-loader! in case of YAML schema.

Hooks for data fetching

Each GET operation is available as a hook. Hooks return the response data directly. This is the main approach to fetch data for rendering. Requests are memoized, so it is fine to call the hooks in any component, right where the data is needed.

import { useItems } from './client';

function List() {
  const items = useItems();
  // ...
}

Mutations and updates

After updating the the data in the backend, the UI must be notified to refetch certain paths. For this there are refetch* methods for each GET operation (hook). Calling refetch does nothing if there are no components currently mounted using the corresponding hooks. This means it is safe to call refetch* just in case, whenever the data has been mutated. It is recommended to put these "mutation / what needs to be refetch" rules to a separate file, for example api.js:

import * as client from './client';

export * from './client';

export async function postItem(item) {
  await client.postItem(null, item);

  // Trigger refetching GET /items and rerendering components using
  // `useItems()`.
  // Does nothing, if there are no components mounted using `useItems()`.
  await client.refetchItems();

  // Multiple refetch calls in parallel:
  // await Promise.all([client.refetchX(), client.refetchY(), client.refetchZ()]);
}
// ...

Parameters

See openapi-client-axios documentation for Parameters.

Server-side Rendering

See https://www.npmjs.com/package/@postinumero/use-async#server-side-rendering.

FAQ

How to call hooks conditionally?

It is not allowed by the Rules of Hooks. Instead create a new component and render components conditionally. For example create <Search> component for <input> and query state. Render <SearchResults query={query} /> only when the query is available. The hook can be called unconditionally in SearchResults.

What if the request fails?

You may use react-error-boundary for general error handling. If you make request to an endpoint that may intentionally fail and you need to handle the error in the same component, each hook has a *Safe version for that. For example a search response may have status code 404 and we don't want to use the general error boundary for that:

import { useSearchSafe } from './client';

function SearchResults({ query }) {
  const [
    error, // null | axios error
    data, // undefined | axios response.data
  ] = useSearchSafe({ query });

  if (error) {
    // ...
  }
  // ...
}

How to access response headers?

There are *Raw versions of the hooks and API methods for accessing the complete axios response:

import { useFooRaw, postFooRaw } from './client';

function App() {
  const { headers, data } = useFooRaw();

  async function handleSubmit(data) {
    const { headers, data } = await postFooRaw(null, data);
  }
  // ...
}