Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/next/lib/hooks/profile.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2022 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45// Hook that uses API to get a given user's profile.6//7// If account_id is explicitly given, returns the *public* profile for that users.8//9// If account_id is NOT given, returns the *private* profile for the signed in user, or10// empty object if user not signed in.1112import LRU from "lru-cache";13import { useEffect, useState } from "react";1415import { Profile } from "@cocalc/server/accounts/profile/types";16import { len } from "@cocalc/util/misc";17import apiPost from "lib/api/post";18import useIsMounted from "./mounted";1920// How often to check for new profile.21const DEFAULT_CACHE_S = 10;2223// This cache is to avoid flicker when navigating around, since24// we want to show the last known avatar for a given user before25// checking if there is a new one.26const cache = new LRU<string, Profile>({ max: 300 });2728interface Options {29noCache?: boolean;30account_id?: string;31}3233export default function useProfile(opts: Options = {}): Profile | undefined {34const { profile } = useProfileWithReload(opts);35return profile;36}3738export function useProfileWithReload(opts: Options = {}): {39profile: Profile | undefined;40reload: () => void;41} {42const { account_id, noCache } = opts;43const isMounted = useIsMounted();44const [profile, setProfile] = useState<Profile | undefined>(45noCache ? undefined : cache.get(account_id ?? "")46);4748async function getProfile(): Promise<void> {49try {50const { profile } = await apiPost(51"/accounts/profile",52{ account_id, noCache },53DEFAULT_CACHE_S54);55if (!isMounted.current) return;56setProfile(profile);57if (!noCache && len(profile) > 0) {58// only cache if got actual information.59cache.set(account_id ?? "", profile);60}61} catch (err) {62console.warn("Unable to fetch a profile -- ", err);63}64}6566useEffect(() => {67getProfile();68}, [account_id, noCache]);6970return { profile, reload: getProfile };71}727374