Skip to content
This repository has been archived by the owner on Nov 12, 2020. It is now read-only.

Commit

Permalink
how to initiate in React App
Browse files Browse the repository at this point in the history
  • Loading branch information
elitan committed Jul 11, 2020
1 parent 3523cb2 commit e2ec7d8
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 12 deletions.
63 changes: 52 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,43 @@
Make it easy to use Nhost with React.

- `NhostAuthProvider` - AuthProvider to simply check logged in state.
- `NhostApolloProvider` - ApolloProvider preconfigured with authentication that works for mutation, queries and subscriptions.

## Initiate

### Create React App

`index.js`

```jsx
import React from "react";
import ReactDOM from "react-dom";
import { NhostAuthProvider, NhostApolloProvider } from "react-nhost";
import { auth } from "[..]path_to//nhost";
import App from "./App";

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

### NextJS

_(coming soon)_

---

## Protected Route

### React Router
Expand All @@ -12,15 +49,21 @@ Make it easy to use Nhost with React.

```jsx
import React from "react";
import { useAuth } from "react-nhost";
import { Route, Redirect } from "react-router-dom";
import { auth } from "path_to_nhost_auth";

function PrivateRoute({ children, ...rest }) {
export function PrivateRoute({ children, ...rest }) {
const { signedIn } = useAuth();

if (signedIn === null) {
return <div>Loading...</div>;
}

return (
<Route
{...rest}
render={({ location }) =>
auth.isAuthenticated() ? (
signedIn ? (
children
) : (
<Redirect
Expand Down Expand Up @@ -51,14 +94,12 @@ import PrivateRoute from "[..]path_to/PrivateRoute.jsx";
<Login />
</Route>
/* Protected routes */
<PrivateRoute>
<Route exact path="/dashboard">
<Dashboard />
</Route>
<Route exact path="/settings">
<Settings />
</Route>
</PrivateRoute>
<PrivateRoute exact path="/">
<Dashboard />
</Route>
<PrivateRoute exact path="/settings">
<Settings />
</Route>
</Switch>
</Router>;
```
Expand Down
2 changes: 1 addition & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ export class NhostAuthProvider extends React.Component {
signedIn: props.auth.isAuthenticated(),
};

auth.onAuthStateChanged((data) => {
props.auth.onAuthStateChanged((data) => {
this.setState({ signedIn: data });
});
}
Expand Down

0 comments on commit e2ec7d8

Please sign in to comment.