aboutsummaryrefslogtreecommitdiffstats
path: root/src/hooks/useLoginState.js
blob: 94301efbdd6bb4ebefd13d3fba5555284b2c5146 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { useState } from "react";

export default function useLoginState() {
  const [userInfo, setUserInfoState] = useState(
    localStorage.userInfo ? JSON.parse(localStorage.userInfo) : {},
  );

  function setUserInfo(userInfo) {
    setUserInfoState(userInfo);
    localStorage.userInfo = JSON.stringify(userInfo || {});
  }

  async function login(username, password) {
    console.log(`logging in: ${username}, ${password}`);
    // const userInfo = await api.login()
    const userInfo = {
      username,
    };
    console.log("Login success");
    setUserInfo(userInfo);
    return userInfo;
  }

  function logout() {
    setUserInfo({});
  }

  const isLoggedIn = !!userInfo?.username;

  return { userInfo, isLoggedIn, login, logout };
}