Created
October 6, 2024 11:56
-
-
Save paulweezydesign/906d7389f03980c1b8c7c67c9a786968 to your computer and use it in GitHub Desktop.
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 React, { createContext, useState, useEffect } from 'react'; | |
import { useRealmApp } from './realm'; | |
import { useNavigate } from 'react-router-dom'; | |
const AuthContext = createContext(); | |
const AuthProvider = ({ children }) => { | |
const app = useRealmApp(); | |
const navigate = useNavigate(); | |
const [user, setUser] = useState(app.currentUser); | |
const [loading, setLoading] = useState(true); | |
useEffect(() => { | |
if (app.currentUser) { | |
setUser(app.currentUser); | |
setLoading(false); | |
} else { | |
app.logIn({ provider: 'anon' }) | |
.then((user) => { | |
setUser(user); | |
setLoading(false); | |
}) | |
.catch((error) => { | |
console.error(error); | |
setLoading(false); | |
}); | |
} | |
}, [app]); | |
const login = async (email, password) => { | |
try { | |
const credentials = { | |
provider: 'local-userpass', | |
data: { email, password }, | |
}; | |
const user = await app.logIn(credentials); | |
setUser(user); | |
navigate('/protected'); | |
} catch (error) { | |
console.error(error); | |
} | |
}; | |
const signup = async (email, password) => { | |
try { | |
const credentials = { | |
provider: 'local-userpass', | |
data: { email, password }, | |
}; | |
const user = await app.emailPasswordAuth.registerUser(credentials); | |
setUser(user); | |
navigate('/protected'); | |
} catch (error) { | |
console.error(error); | |
} | |
}; | |
const logout = async () => { | |
try { | |
await app.currentUser.logOut(); | |
setUser(null); | |
navigate('/login'); | |
} catch (error) { | |
console.error(error); | |
} | |
}; | |
return ( | |
<AuthContext.Provider value={{ user, login, signup, logout, loading }}> | |
{children} | |
</AuthContext.Provider> | |
); | |
}; | |
export { AuthProvider, AuthContext }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment