question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Add Auth to React context using Provider pattern

See original GitHub issue

Is 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:closed
  • Created 4 years ago
  • Reactions:22
  • Comments:15 (2 by maintainers)

github_iconTop GitHub Comments

5reactions
kjellskicommented, Sep 13, 2020

Did this ever really make it into the package? I can’t find it…

4reactions
akeithlycommented, Mar 11, 2021

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.

Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found