blockstack-react-auth-provider
Impliment blockstack.js' authentication using React patterns you know and love.
Installation
$ yarn add blockstack-react-auth-provider
Usage
react-app-rewire-blockstack and blockstack-react-scripts.
1) Make sure that your dev server and build processes are configured to work with blockstack.js. I encourage you to check out2) Import and wrap your root component with an instance of AuthProvider:
{ return <AuthProvider> <Router /> </AuthProvider> }
3) Import and wrap child components (on any level) with an instance of Auth Consumer. Use its data as you see fit:
Notice how we use loggedIn
(a boolean) to decide whether to display the 'account' page link, or a 'log in' button.
<AuthConsumer> <div> <NavLink exact to='/' children='feed' /> <NavLink to='/some-other-page' children='some-other-page' /> loggedIn ? <NavLink to='/account' children='account' /> : <button onClick= logIn children='log in' className='active' /> </div> </AuthConsumer>
In our router, we might want to disable routes based on authentication state. We can do this by conditionally (based on the value of loggedIn
) rendering a redirect. We also (usually) will want to prevent rendering the main router before authentication state has loaded (aka. isLoading
).
{ return <AuthConsumer> isLoading ? <Loading /> : <BrowserRouter> <Switch> <Route exact path='/' component= Feed /> <Route path='/some-other-page' component= SomeOtherPage /> <Route path='/account' component= loggedIn ? Account : <Redirect to='/' /> /> <Route component= FourOFour /> </Switch> </BrowserRouter> </AuthConsumer> }