import { useState, useTransition } from "react"; import { useTranslation } from "react-i18next"; interface FollowState { following: boolean; pending: boolean; } interface Props { username: string; initialState: FollowState | null; } export function FollowButton({ username, initialState }: Props) { const { t } = useTranslation("journal"); const [state, setState] = useState( initialState ?? { following: false, pending: false }, ); const [isPending, startTransition] = useTransition(); const [error, setError] = useState(null); const onClick = () => { setError(null); startTransition(async () => { const path = state.following ? `/api/users/${username}/unfollow` : `/api/users/${username}/follow`; try { const res = await fetch(path, { method: "POST" }); if (!res.ok) { const body = await res.json().catch(() => ({})); setError(body.error ?? "Failed"); return; } const body = (await res.json()) as { following: boolean; pending: boolean }; setState({ following: body.following, pending: body.pending }); } catch (e) { setError((e as Error).message); } }); }; const label = state.following ? t("social.unfollow") : t("social.follow"); return (
{error &&

{error}

}
); }