Last active
December 17, 2021 10:42
-
-
Save Narottam04/f55e0f0c2a8273b9f8bd9b9969d96d93 to your computer and use it in GitHub Desktop.
Problem: How to implement unique username feature in gun js
This file contains hidden or 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