Add Auth to React context using Provider pattern
See original GitHub issueIs your feature request related to a problem? Please describe. A pattern used for Authenticator (withAuthenticator) React component is hardly extensible. Prev feature request Describe the solution you’d like Use Provider pattern to track authentication state.
Describe alternatives you’ve considered Here is very basic implementation
import React, { useEffect, useState } from 'react'
import createReactContext from 'create-react-context'
import { Hub, Auth } from 'aws-amplify'
const { Consumer: AuthConsumer, Provider } = createReactContext()
const AUTHENTICATOR_AUTHSTATE = 'amplify-authenticator-authState'
const AuthProvider = props => {
const [auth, setAuth] = useState({})
useEffect(() => {
Auth.currentAuthenticatedUser()
.then(user => {
console.log('Current user: ', user)
localStorage.setItem(AUTHENTICATOR_AUTHSTATE, 'signedIn')
setAuth({ state: 'signIn', user })
})
.catch(err => localStorage.getItem(AUTHENTICATOR_AUTHSTATE))
.then(cachedAuthState => cachedAuthState === 'signedIn' && Auth.signOut())
}, [])
useEffect(() => {
Hub.listen('auth', ({ payload }) => {
const { event, data } = payload
if (event === 'signOut') {
setAuth({ state: event, user: null })
localStorage.deleteItem(AUTHENTICATOR_AUTHSTATE)
return
}
localStorage.setItem(AUTHENTICATOR_AUTHSTATE, 'signedIn')
setAuth({ state: event, user: data })
})
}, [])
return <Provider value={auth}>{props.children}</Provider>
}
export { AuthConsumer, AuthProvider }
Wrap app in AuthProvider
<AuthProvider>
<App />
</AuthProvider>
Use auth
context where you need it
<AuthConsumer>
{auth=>
auth.user
? (
<Button
onClick={_ => Auth.signOut()/*...*/}
children='Log Out'
/>
) : (
<Button
onClick={_ => Auth.signIn(/*...*/)/*...*/}
children='Log Out'
/>
)
}
</AuthConsumer>
Additional context Let me know you not mind to add this. I could implement it quite easily.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:22
- Comments:15 (2 by maintainers)
Top Results From Across the Web
Provider Pattern with React Context API - Flexiple
React's provider pattern is a powerful concept. React uses provider pattern in Context API to share data across the tree descendant nodes.
Read more >Predictable React authentication with the Context API
Now the first step is to communicate with your authentication backend. We are going to make simple HTTP calls with redaxios.
Read more >Context - React
Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes. The Provider component accepts a ......
Read more >Authentication With React Context | by Tameem Iftikhar
First of all, we will setup the react context. To keep our code clean, we will define a provider and consumer in the...
Read more >Building with React Context Provider Pattern - JavaScript Works
React uses the Context provider to share data across multiple children components in our React App without the need to pass data or...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Did this ever really make it into the package? I can’t find it…
This would be particularly handy for those of us not using the UI Components. They already have the
onAuthUIStateChange
to work with but many of need to build custom login components.