Commit 32312625 authored by David Haynes's avatar David Haynes 🙆

Dynamic homepage based on auth status

- holy crap custom hooks are a game changer
parent 35ecedad
Pipeline #3876 passed with stage
in 1 minute and 11 seconds
import React from "react";
import { PageTemplate } from "Components";
import useAuthCheck from "../../Utils/useAuthCheck";
const HomePage = () => (
<PageTemplate>
<p>Hello World!</p>
</PageTemplate>
);
const HomePage = () => {
const { isLoggedIn, loaded } = useAuthCheck();
return (
<div>
{loaded ? (
<div>
{isLoggedIn ? (
<PageTemplate>
<p>
You're logged in and looking at the homepage which means you
passed the auth check and we are now rendering the new homepage
for logged in users but we haven't written it so you're looking
at this sentence yeah.
</p>
</PageTemplate>
) : (
<PageTemplate>
<p>
You're not logged in and looking at the homepage which means you
failed the auth check and we are now rendering the homepage for
non logged in users but we haven't written it so you're looking
at this sentence yeah.
</p>
</PageTemplate>
)}
</div>
) : (
<div />
)}
</div>
);
};
export default HomePage;
import React from "react";
import { Container } from "reactstrap";
import useAuthCheck from "../../Utils/useAuthCheck";
class AuthedPageTemplate extends React.Component {
constructor(props) {
super(props);
this.state = { isLoggedIn: null, loaded: false };
}
const AuthedPageTemplate = props => {
const { isLoggedIn, loaded } = useAuthCheck();
componentDidMount() {
fetch("/auth/status/", {
headers: {
"Content-Type": "application/json"
}
})
.then(r => r.json())
.then(res =>
this.setState({
isLoggedIn: res.is_authenticated,
loaded: true
})
);
}
render() {
const { isLoggedIn, loaded } = this.state;
return (
<div>
{loaded ? (
<div>
{isLoggedIn ? (
<Container>{this.props.children}</Container>
) : (
<h1>You're not authed!</h1>
)}
</div>
) : (
<div />
)}
</div>
);
}
}
return (
<div>
{loaded ? (
<div>
{isLoggedIn ? (
<Container>{props.children}</Container>
) : (
<h1>You're not authed!</h1>
)}
</div>
) : (
<div />
)}
</div>
);
};
export default AuthedPageTemplate;
import React, { useState, useEffect } from "react";
const useAuthCheck = () => {
const [isLoggedIn, setIsLoggedIn] = useState(null);
const [loaded, setLoaded] = useState(false);
const getAuthStatus = async () => {
let response = await fetch("/auth/status/", {
headers: {
"Content-Type": "application/json"
}
});
let data = await response.json();
setIsLoggedIn(data.is_authenticated);
setLoaded(true);
};
useEffect(() => {
getAuthStatus();
}, []);
return { isLoggedIn, loaded };
};
export default useAuthCheck;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment