Skip to content

Instantly share code, notes, and snippets.

@pom421
Created May 22, 2020 10:32
Show Gist options
  • Save pom421/c96b804ecd6ee3e01218f76dbab30ffe to your computer and use it in GitHub Desktop.
Save pom421/c96b804ecd6ee3e01218f76dbab30ffe to your computer and use it in GitHub Desktop.
Hook for replacement of HOC for authentication
//https://codesandbox.io/s/quirky-hermann-1xzju?file=/src/App.js
import React, { useState, useEffect } from "react";
import "./styles.css";
const useAuth = Component => {
const [isAuthed, setAuth] = useState(false);
useEffect(() => {
setTimeout(() => {
setAuth(true);
}, 1500);
}, []);
const view = isAuthed ? (
<Component>as hook</Component>
) : (
<div>not authed</div>
);
return [isAuthed, view];
};
const AuthView = ({ children }) => {
useEffect(() => {
console.log("rendered AuthView");
}, []);
return <div>authenticated view: {children}</div>;
};
const AuthComponent = ({ isAuthed, children }) => {
if (!isAuthed) {
return <div>not authed</div>;
}
return children;
};
export default function App() {
const [isAuthed, view] = useAuth(AuthView);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>authenticated: {isAuthed.toString()}</h2>
{view}
{isAuthed && <AuthView>as conditional</AuthView>}
<AuthComponent isAuthed={isAuthed}>
<AuthView>as child</AuthView>
</AuthComponent>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment