add recoil store

This commit is contained in:
Sam 2022-05-05 16:33:44 +02:00
parent 580449440a
commit 2e4b8b9823
10 changed files with 225 additions and 68 deletions

23
frontend/src/lib/store.ts Normal file
View file

@ -0,0 +1,23 @@
import axios from "axios";
import { atom } from "recoil";
import type { APIError, MeUser } from "./types";
export const userState = atom<MeUser | null>({
key: "userState",
default: getCurrentUser(),
});
async function getCurrentUser(): Promise<MeUser | null> {
const token = localStorage.getItem("pronouns-token");
if (!token) return null;
try {
const resp = await axios.get<MeUser | APIError>("/api/v1/users/@me");
if ("id" in resp.data) return resp.data as MeUser;
return null;
} catch (e) {
console.log("Error fetching /users/@me:", e);
}
return null;
}

27
frontend/src/lib/types.ts Normal file
View file

@ -0,0 +1,27 @@
export interface MeUser {
id: string;
username: string;
display_name: string | null;
bio: string | null;
avatar_source: string | null;
avatar_url: string | null;
links: string[] | null;
discord: string | null;
discord_username: string | null;
}
export interface APIError {
code: ErrorCode;
message?: string;
}
export enum ErrorCode {
BadRequest = 400,
Forbidden = 403,
InternalServerError = 500,
InvalidState = 1001,
InvalidOAuthCode = 1002,
UserNotFound = 2001,
}