Skip to content

Instantly share code, notes, and snippets.

@gragland
Created February 28, 2019 20:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gragland/f2087c4d98b369cf4332db86db06971b to your computer and use it in GitHub Desktop.
Save gragland/f2087c4d98b369cf4332db86db06971b to your computer and use it in GitHub Desktop.
useFakeAuth React Hook
// 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