Skip to main content

@web3api/react

npm

The purpose of the Web3API React library is to simplify integration of Web3API into React applications.

Installation#

npm install @web3api/react

Usage#

Web3ApiProvider#

To start using the Web3API React library, wrap your application in a Web3ApiProvider:

import React from 'react';
import { Web3ApiProvider } from '@web3api/react';
export const App: React.FC = () => {
return (
<Web3ApiProvider>
<HelloWorld />
</Web3ApiProvider>
);
};

The Web3ApiProvider instantiates the Web3ApiClient for all queries below it in the component tree.

The Web3ApiProvider also accepts URI redirects as props.

You can pass the redirects array into the provider component like so:

<Web3ApiProvider redirects={ [] }/>

If you need to use multiple providers, you can do so using the createWeb3ApiProvider("...") method, which accepts the name of your provider as an argument. For example:

import { createWeb3ApiProvider } from '@web3api/react';
const CustomWeb3ApiProvider = createWeb3ApiProvider('custom');
export const CustomProvider = ({ children }: { children: JSX.Element }) => {
return (
<CustomWeb3ApiProvider>
{children}
</CustomWeb3ApiProvider>
);
};

useWeb3ApiQuery#

The useWeb3ApiQuery is the primary API for executing queries. To run a query within a React component, call useWeb3ApiQuery and pass it a GraphQL query string. When your component renders, useWeb3ApiQuery returns an object from the Web3API client that contains execute, data, loading, and error properties you can use to render your UI.

Here's an example query that you could send:

const { execute, data, errors, loading } = useWeb3ApiQuery({
uri: 'ens/api.helloworld.polywrap.eth',
query: `{
logMessage(message: "Hello World!")
}`,
});
tip

By default, the useWeb3ApiQuery hook uses the first Web3ApiProvider found in the DOM's hierarchy. If you'd like to specify a specific provider to be used, simply set the provider: property:

const { execute, data, errors, loading } = useWeb3ApiQuery({
provider: "custom",
uri: 'ens/api.helloworld.polywrap.eth',
query: `{
logMessage(message: "Hello World!")
}`,
});

useWeb3ApiInvoke#

The useWeb3ApiInvoke hook works the same as the useWeb3ApiQuery hook, but uses the client's invoke syntax instead.

Here's what our "hello world" query from above would look like with useWeb3ApiInvoke.

const { execute, data, error, loading } = useWeb3ApiInvoke({
uri: 'ens/api.helloworld.polywrap.eth',
module: "query",
method: "logMessage",
input: {
message: "Hello World!",
},
});

useWeb3ApiClient#

You can obtain a copy of the client instance from your Web3ApiProvider using the useWeb3ApiClient hook.

const client = useWeb3ApiClient();