Problem: How to implement unique username feature in gun js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import {useContext, useEffect,useState,createContext} from 'react' | |
| import GUN from 'gun' | |
| import 'gun/sea' | |
| import 'gun/axe' | |
| const AuthContext = createContext() | |
| export function useAuth() { | |
| return useContext(AuthContext) | |
| } | |
| export function AuthProvider({children}) { | |
| const [username, setUsername] = useState('') | |
| // DATABASE | |
| const gun = GUN(); | |
| // GUN USER | |
| const user = gun.user().recall({sessionStorage:true}) | |
| // current user username | |
| user.get('alias').on(v => setUsername(v)) | |
| gun.on('auth',async(event) => { | |
| const alias = await user.get('alias'); //username string | |
| setUsername(alias); | |
| console.log(`signed in as ${alias}`) | |
| }) | |
| function login(username,password) { | |
| const promise = new Promise((resolve,reject)=>{ | |
| user.auth(username,password,({err}) =>{ | |
| if(err){ | |
| // alert(err) | |
| reject() | |
| } | |
| else{ | |
| resolve() | |
| } | |
| }) | |
| }) | |
| return promise | |
| } | |
| function signup(username,password) { | |
| const promise = new Promise((resolve,reject)=>{ | |
| user.create(username,password,({err}) => { | |
| if(err) { | |
| alert(err); | |
| } | |
| else { | |
| user.auth(username,password,({err}) => err && alert(err)) | |
| resolve() | |
| } | |
| }) | |
| }) | |
| return promise | |
| } | |
| function logout() { | |
| user.leave(); | |
| setUsername(''); | |
| } | |
| function deleteAccount(setUsername){ | |
| user.delete('alias') | |
| setUsername(''); | |
| } | |
| const value = { | |
| username, | |
| setUsername, | |
| user, | |
| login, | |
| signup, | |
| logout, | |
| deleteAccount | |
| } | |
| return( | |
| <AuthContext.Provider value={value}> | |
| {children} | |
| </AuthContext.Provider> | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment