@buddies/hooks
v1.0.0
Published
Buddies Hooks ===
Downloads
5
Readme
Buddies Hooks
Authentication
Setup
The very root of your app must have this.
import { AuthContext } from '@buddies/hooks'
const AppRoot = () => {
const handleLoginRequest = async (client, user, accessToken) => {
console.log(`Welcome ${user.nickname}!`)
// Save the access token where you want (cookie, local storage etc)
}
const handleLogoutRequest = async () => {
// Delete the access token from where it is saved
}
const handleAccessTokenRequest = async () => {
// Return the access token value from where it is saved
// If no access tokens exists, returns undefined
return undefined
}
return (
<AuthContext
onLoginRequest={handleLoginRequest}
onLogoutRequest={handleLogoutRequest}
onAccessTokenRequest={handleAccessTokenRequest}
>
<App />
</AuthContext>
)
}
Get the current user
import { useAuth } from '@buddies/hooks'
const Example = () => {
const { loading, user } = useAuth()
if (loading)
return <span>Loading...</span>
if (user === undefined)
return <span>You are not connected</span>
return <span>Hello {user.nickname}!</span>
}
Login with local credentials
import { useEffect } from 'react'
import { useAuth } from '@buddies/hooks'
const Example = () => {
const { user, loginWithLocalCredentials } = useAuth()
useEffect(() => {
loginWithLocalCredentials('Your app name')
.on('succeed', (client, user, accessToken) => {
console.log(`Welcome ${user.nickname}`)
})
.on('error', (error) => console.err(error))
.login('[email protected]', 'password')
}, [])
if (user === undefined)
return <span>You are not connected</span>
return <span>Hello {user.nickname}!</span>
}
Signup with local credentials
import { useEffect } from 'react'
import { useAuth } from '@buddies/hooks'
const Example = () => {
const { user, signupWithLocalCredentials } = useAuth()
useEffect(() => {
signupWithLocalCredentials('Your app name')
.on('succeed', (client, user, accessToken) => {
console.log(`Welcome ${user.nickname}`)
})
.on('error', (error) => console.err(error))
.signup('[email protected]', 'password', 'nickname', 'username', 'biography')
}, [])
if (user === undefined)
return <span>You are not connected</span>
return <span>Hello {user.nickname}!</span>
}