React

Installation and Integration Guide for EarthoOne SDK

1. Install the SDK

Using npm:

npm install @eartho/one-client-react

Using yarn:

yarn add @eartho/one-client-react

2. Retrieve Eartho Client ID

Go to Eartho Creator and copy your Eartho client ID from the "Developers Integration" section.

3. Configure the SDK

Wrap your application with EarthoOneProvider in your custom _app.js file:

import React from 'react';
import App from 'next/app';
import Router from 'next/router';
import { EarthoOneProvider } from '@eartho/one-client-react';
import { Nav } from '../components/Nav';
import '../components/App.css';

const onRedirectCallback = (appState) => {
  Router.replace(appState?.returnTo || '/');
};

const protectedPaths = [
  { path: '^/dashboard', accessIds: ['userAccessId', 'adminAccessId'], redirectPath: '/no-access' },
  { path: '^/users', accessIds: ['userAccessId'], redirectPath: '/no-access' }
];

class MyApp extends App {
  render() {
    const { Component, pageProps } = this.props;
    return (
      <EarthoOneProvider
        clientId={process.env.NEXT_PUBLIC_CLIENT_ID}
        onRedirectCallback={onRedirectCallback}
        authorizationParams={{
          redirect_uri: typeof window !== 'undefined' && window.location.origin,
        }}
        protectedPaths={protectedPaths}
        defaultLoginPath="/"
        loadingComponent={<div>Loading...</div>}
      >
        <Nav />
        <Component {...pageProps} />
      </EarthoOneProvider>
    );
  }
}

export default MyApp;

4. Integrate Eartho Authentication in Your Components

Use the useEarthoOne hook in your components to access the authentication state and methods:

// src/pages/login.js
import React from 'react';
import { useEarthoOne } from '@eartho/one-client-react';

function LoginPage() {
  const {
    isLoading,
    isConnected,
    error,
    user,
    connectWithPopup,
    logout,
  } = useEarthoOne();

  if (isLoading) {
    return <div>Loading...</div>;
  }
  if (error) {
    return <div>Oops... {error.message}</div>;
  }

  if (isConnected) {
    return (
      <div>
        Hello {user.displayName}{' '}
        <button onClick={() => logout({ returnTo: window.location.origin })}>
          Log out
        </button>
      </div>
    );
  } else {
    return (
      <button
        className="btn btn-outline-success"
        id="login"
        onClick={() => connectWithPopup({ accessId: "YOUR_EARTHO_ACCESS_ID" })}
      >
        Log in
      </button>
    );
  }
}

export default LoginPage;

For an example project, visit Eartho React Example.

Last updated