React

Use the Bearer client for React on your frontend to call APIs, connect users to OAuth APIs and save API credentials.

Installing

React
npm install @bearer/react

Calling APIs

React
import * as React from "react";
import bearer from "@bearer/js";
import { CLIENT_ID } from "./constants";
const bearerClient = bearer(CLIENT_ID);
const github = bearerClient.integration("github");
class Repositories extends React.Component<{ authId: string }, { data: any }> {
constructor(props) {
super(props);
this.state = { data: "" };
}
fetch = () => {
github
.auth(this.props.authId)
.get("/repositories", {
headers: { accept: "application/json" },
query: { since: 364 }
})
.then(({ data }) => {
this.setState({ data: JSON.stringify(data) });
});
};
componentWillMount() {
this.fetch();
}
render() {
return <pre>{this.state.data}</pre>;
}
}
export default Repositories;

Replace the CLIENT_ID with your Client ID that can be found on your Developer Keys page.

By default, calling APIs from a client-side context is deactivated for security reasons. You can enable this option on the Settings page of the integration.

We strongly recommend doing it only for OAuth based API.

Adding a Connect button (OAuth)

React
import * as React from "react";
import { Bearer, factory } from "@bearer/react";
const { Connect } = factory('github'); // Integration UUID
const MyConnectComponent = () => {
const onSuccess = ({ authId }) => {
// Use this authId later like bearer.auth(authId).get(..
console.log('AUTH_ID for this user', authId)
}
return (
// Initialize the Bearer provider with your client ID
<Bearer clientId=BEARER_CLIENT_ID>
<Connect
onSuccess={onSuccess}
render={({ connect }) => {
return (
<button onClick={connect}>
Connect to Github
</button>
);
}}
/>
</Bearer>
);
};
export default MyConnectComponent;

Replace the BEARER_CLIENT_ID with your Client ID that can be found on your Developer Keys page.

Adding a Setup component (user's credential)

By default, you can provide your API credentials (API Key, OAuth ClientID & Secret etc.) in the Settings page of the integration.

If you need to ask your users to provide their own, you can easily create a Setup Component on your app.

When users provide their credentials, Bearer will store them and provide in exchange a Setup Id that will then be needed to query the API.

Here is an example of a Setup Component for an API Key based integration:

React
import * as React from "react"
import { BearerContext } from "@bearer/react/lib/bearer-provider"
const MyComponent = () => {
const [setupId, setSetupId] = React.useState();
const context = useContext(BearerContext);
const handleClick = (e: any) => {
context.bearer
.invoke("INTEGRATION_UUID", "bearer-setup-save", {
setup:{
apiKey: "value",
type: "apikey"
}
})
.then(data => { setSetupId(data.setupId); })
.catch(console.error);
}
return (
<button type="button" onClick={this.handleClick}>Click Me</button>
)
}

Check out the source of the React client.