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

@dankeroni/react-openapi-client

v0.1.7

Published

Consume OpenAPI-enabled APIs with React Hooks

Downloads

1

Readme

React OpenAPI Client

CI Dependencies npm version bundle size License Sponsored Buy me a coffee

Consume OpenAPI-enabled APIs with React Hooks

Uses openapi-client-axios under the hood.

Why?

Instead of:

import React, { useEffect, useState } from 'react';

const MyComponent = (props) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState();
  const [error, setError] = useState();

  useEffect(() => {
    (async () => {
      setLoading(true);
      try {
        const res = await fetch(`https://petstore.swagger.io/api/v3/pet/${props.id}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
          credentials: 'include',
        });
        const data = await res.json();
        setData(data);
      } catch (err) {
        setError(err);
      }
      setLoading(false);
    })();
  }, [props.id]);

  // ...
};

You can do this:

import React, { useEffect } from 'react';
import { useOperation } from 'react-openapi-client';

const MyComponent = (props) => {
  const { loading, data, error } = useOperation('getPetById', props.id);
  // ...
};

Getting Started

Install react-openapi-client as a dependency

npm install --save react-openapi-client

Wrap your React App with an OpenAPIProvider, passing your OpenAPI definition as a prop.

import React from 'react';
import { render } from 'react-dom';
import { OpenAPIProvider } from 'react-openapi-client';

const App = () => (
  <OpenAPIProvider definition="http://petstore.swagger.io:8080/api/v3/openapi.json">
    <PetDetails id={1} />
  </OpenAPIProvider>
);

Now you can start using the useOperation and useOperationMethod hooks in your components.

import { useOperation } from 'react-openapi-client';

const PetDetails = (props) => {
  const { loading, data, error } = useOperation('getPetById', props.id);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error}</div>;
  }

  return (
    <div className="App">
      <img src={data.image} alt={data.name} />
      <h3>{data.name}</h3>
      <ul>
        <li>
          <strong>id:</strong> {data.id}
        </li>
        <li>
          <strong>status:</strong> {data.status}
        </li>
      </ul>
    </div>
  );
};

See a full Create-React-App example under examples/

useOperation hook

The useOperation hook is a great way to declaratively fetch data from your API.

Important! Calling useOperation() always immediately calls the API endpoint.

Parameters:

useOperation passes the arguments to an OpenAPI Client Axios Operation Method matching the operationId given as the first parameter.

  • operationId (string) Required. the operationId of the operation to call
  • parameters (object | string | number) Optional. Parameters for the operation
  • data (object | string | Buffer) Optional. Request payload for the operation
  • config (AxiosRequestConfig) Optional. Request payload for the operation

Return value:

useOperation returns an object containing the following state properties:

  • loading (boolean) whether the API request is currently ongoing.
  • data (any) the parsed response data for the operation.
  • response (any) the raw axios response object for the operation.
  • error (Error) contains an error object, in case the request fails
  • api (OpenAPIClientAxios) reference to the API client class instance

Example usage:

const { loading, data, error } = useOperation('getPetById', 1, null, { headers: { 'x-api-key': 'secret' } });

useOperationMethod hook

The useOperationMethod hook can be used to obtain a callable operation method.

Unlike useOperation, calling useOperationMethod() has no side effects.

Parameters:

useOperationMethod gets the corresponding OpenAPI Client Axios Operation Method matching the operationId.

  • operationId (string) Required. the operationId of the operation to call

Return value:

useOperationMethod returns a tuple (javascript array), where the first element is the callable operation method, and the second method contains the same object as useOperation's return value.

See OpenAPI Client Axios documentation for more details on how to use the Operation Methods.

Example usage:

const [createPet, { loading, response, error }] = useOperationMethod('createPet');

OpenAPIProvider

The OpenAPIProvider component provides OpenAPIContext to all nested components in the React DOM so they can use the useOperation and useOperationMethod hooks.

Internally, the Provider instantiates an instance of OpenAPIClientAxios, which is then used by the hooks to call the API operations.

In addition to the definition file, you can pass any constructor options accepted by OpenAPIClientAxios as props to the OpenAPIProvider component.

Example usage:

const App = () => (
  <OpenAPIProvider definition="http://petstore.swagger.io:8080/api/v3/openapi.json" axiosConfigDefaults={{ withCredentials: true }}>
    <ApplicationLayout />
  </OpenAPIProvider>
)

You can also access the OpenAPIClientAxios instance by using the React useContext hook:

import React, { useContext } from 'react';
import { OpenAPIContext } from 'react-openapi-client';

const MyComponent = () => {
  const { api } = useContext(OpenAPIContext);
  const client = api.client;
  const definition = api.definition;
  // ...
}

Contributing

React OpenAPI Client is Free and Open Source Software. Issues and pull requests are more than welcome!