import React from "react";

export interface UserContextData {
  username?: string;
}

const UserContext = React.createContext<UserContextData>({});

export const useUserContext = (): UserContextData => {
  return React.useContext(UserContext);
};

export const UserContextProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const [username, setUsername] = React.useState();

  React.useEffect(() => {
    fetch(`/api/me`)
      .then((response) => response.json())
      .then(({ username }) => {
        setUsername(username);
      });
  }, []);

  return (
    <UserContext.Provider
      value={{
        username,
      }}
    >
      {children}
    </UserContext.Provider>
  );
};
