grungnet/src/contexts/UserIdContext.tsx

37 lines
931 B
TypeScript
Raw Normal View History

import React, { useEffect, useState, useContext } from "react";
import { useDatabase } from "./DatabaseContext";
2021-07-09 02:22:35 -04:00
const UserIdContext = React.createContext<string | undefined>(undefined);
export function UserIdProvider({ children }: { children: React.ReactNode }) {
const { database, databaseStatus } = useDatabase();
const [userId, setUserId] = useState();
useEffect(() => {
if (!database || databaseStatus === "loading") {
return;
}
async function loadUserId() {
2021-07-09 02:22:35 -04:00
if (database) {
const storedUserId = await database.table("user").get("userId");
if (storedUserId) {
setUserId(storedUserId.value);
}
}
}
loadUserId();
}, [database, databaseStatus]);
return (
<UserIdContext.Provider value={userId}>{children}</UserIdContext.Provider>
);
}
export function useUserId() {
return useContext(UserIdContext);
}
export default UserIdContext;