Skip to content

Instantly share code, notes, and snippets.

@gragland
Created February 28, 2019 20:12
Show Gist options
  • Select an option

  • Save gragland/f2087c4d98b369cf4332db86db06971b to your computer and use it in GitHub Desktop.

Select an option

Save gragland/f2087c4d98b369cf4332db86db06971b to your computer and use it in GitHub Desktop.

Revisions

  1. gragland created this gist Feb 28, 2019.
    37 changes: 37 additions & 0 deletions use-fake-auth-hook.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    // 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];
    }