Skip to content

Commit f23aea7

Browse files
committed
avatar on header
1 parent 35c5dae commit f23aea7

1 file changed

Lines changed: 31 additions & 2 deletions

File tree

src/layout/frame/Header.tsx

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
Link as MuLink,
1414
Divider,
1515
Tooltip,
16+
Avatar,
1617
} from "@material-ui/core";
1718
import { AccountCircle, GitHub, Search, QuestionAnswer } from "@material-ui/icons";
1819
import { Link, useLocation } from "react-router-dom";
@@ -23,6 +24,7 @@ import { logout, toAbsoluteUrl } from "utils";
2324
import { useAppDispatch, useAuth, useLoginBack } from "hooks";
2425
import { Notification, Adblock } from "features";
2526
import { setUsername } from "app/pages/login/userSlice";
27+
import axios from "axios";
2628

2729
const useStyles = makeStyles((theme: Theme) =>
2830
createStyles({
@@ -52,9 +54,36 @@ const useStyles = makeStyles((theme: Theme) =>
5254
danger: {
5355
color: theme.palette.error.main,
5456
},
55-
})
57+
}),
5658
);
5759

60+
const RenderAvatar = React.memo(({ username }: { username: string }) => {
61+
const [hasAvatar, setHasAvatar] = React.useState<boolean | null>(null);
62+
63+
React.useEffect(() => {
64+
let cancelled = false;
65+
66+
axios
67+
.head(`/api/user/avatar/${username}`)
68+
.then(() => {
69+
if (!cancelled) setHasAvatar(true);
70+
})
71+
.catch(() => {
72+
if (!cancelled) setHasAvatar(false);
73+
});
74+
75+
return () => {
76+
cancelled = true;
77+
};
78+
}, [username]);
79+
80+
if (hasAvatar === null) {
81+
return <AccountCircle />;
82+
}
83+
84+
return hasAvatar ? <Avatar src={`/api/user/avatar/${username}`} /> : <AccountCircle />;
85+
});
86+
5887
export function Header() {
5988
const location = useLocation();
6089
const { enqueueSnackbar } = useSnackbar();
@@ -133,7 +162,7 @@ export function Header() {
133162
<Notification />
134163

135164
<IconButton color="inherit" {...bindTrigger(loginPopupState)}>
136-
<AccountCircle />
165+
<RenderAvatar username={username} />
137166
</IconButton>
138167
<Menu
139168
{...bindMenu(loginPopupState)}

0 commit comments

Comments
 (0)