@nhost/react-apollo

Make it easy to use Apollo and React with your Nhost project.

@nhost/react-apollo exposes one component: NhostApolloProvider. Wrap your whole App around this component to make GraphQL requests anywhere from your app.

It's recommended to use @nhost/react-apollo with @nhost/react-auth and nhost-js-sdk for users to login and interact with the GraphQL API.

If you use @nhost/react-apollo and NhostApolloProvider without authentication (auth property) all GraphQL requests will be made with the public role.

#Install

npm install @nhost/react-apollo @nhost/react-auth nhost-js-sdk @apollo/client graphql graphql-tag

@apollo/client is required for @nhost/react-apollo to work and will be used to import useQuery, useMutation, and useSubscription.

#Create React App

See full Nhost Create React App with Apollo.

src/index.js
import React from "react";
import ReactDOM from "react-dom";
import { NhostAuthProvider } from '@nhost/react-auth";
import { NhostApolloProvider } from "@nhost/react-apollo";
import { auth } from "utils/nhost";
import App from "./App";

ReactDOM.render(
  <React.StrictMode>
    <NhostAuthProvider auth={auth}>
      <NhostApolloProvider
        auth={auth}
        gqlEndpoint={`https://hasura-REPLACE.nhost.app/v1/graphql`}
      >
        <App />
      </NhostApolloProvider>
    </NhostAuthProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

#Next.js

See full Nhost Next.js with Apollo.

pages/_app.js
import { NhostAuthProvider } from "@nhost/react-auth";
import { NhostApolloProvider } from "@nhost/react-apollo";

import { auth } from "utils/nhost";

function MyApp({ Component, pageProps }) {
  return (
    <NhostAuthProvider auth={auth}>
      <NhostApolloProvider
        auth={auth}
        gqlEndpoint={`https://hasura-REPLACE.nhost.app/v1/graphql`}
      >
        <Component {...pageProps} />
      </NhostApolloProvider>
    </NhostAuthProvider>
  );
}

export default MyApp;

Learn more about auth and storage in the nhost-js-sdk library.

src/utils/nhost.js
import nhost from "nhost-js-sdk";

const config = {
  base_url: "https://backend-REPLACE.nhost.app",
};

nhost.initializeApp(config);

const auth = nhost.auth();
const storage = nhost.storage();

export { auth, storage };

Usage

import React from "react";
import { useQuery } from "@apollo/client";
import gql from "graphql-tag";

const GET_TODOS = gql`
  query {
    todos {
      id
      created_at
      name
      completed
    }
  }
`;

export function function App() {
  const { loading, data } = useQuery(GET_TODOS);

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

  return (
    <div>
      <h1>in app</h1>
      {!data ? (
        "no data"
      ) : (
        <ul>
          {data.todos.map((todo) => {
            return <li key={todo.id}>{todo.name}</li>;
          })}
        </ul>
      )}
    </div>
  );
}