aboutsummaryrefslogtreecommitdiffstats
path: root/src/hooks/useLoginState.js
blob: b7c72216de19a9ced7fd56ba390ffce7361d08c8 (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
32
33
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};
}