Created
February 28, 2019 20:12
-
-
Save gragland/f2087c4d98b369cf4332db86db06971b to your computer and use it in GitHub Desktop.
useFakeAuth React Hook
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
// Current auth status | |
let currentAuth = false; | |
// Holds setAuth for every instance of hook | |
const authSetters = new Set(); | |
function useFakeAuth() { | |
// Auth state and setter | |
const [auth, setAuth] = useState(currentAuth); | |
// Add setAuth to authSetters | |
useEffect( | |
() => { | |
authSetters.add(setAuth); | |
return () => authSetters.delete(setAuth); | |
}, | |
[setAuth] | |
); | |
// Fake async API call to auth or de-auth | |
// In real life you'd probably pass in an email/pass | |
// And have onSuccess and onError instead of a callback arg | |
const setAuthApi = (newAuth, cb) => { | |
setTimeout(() => { | |
// Update current auth status | |
currentAuth = newAuth; | |
// Call setAuth for every instance of hook | |
authSetters.forEach(setter => setter(newAuth)); | |
cb && cb(); | |
}, 100); | |
}; | |
const signin = cb => setAuthApi(true, cb); | |
const signout = cb => setAuthApi(false, cb); | |
return [auth, signin, signout]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment