Spaces:
Running
Running
| import Cookies from "js-cookie"; | |
| import { useQuery } from "react-query"; | |
| import { useCookie } from "react-use"; | |
| import { API, api, MY_TOKEN_KEY } from "utils/api"; | |
| export const login = async () => { | |
| const res: any = await fetch("/api/auth", { | |
| method: "GET", | |
| headers: { "Content-Type": "application/json" }, | |
| }); | |
| if (!res.ok) return; | |
| const url = await res.json(); | |
| window.location.href = url; | |
| }; | |
| export const setToken = (token: string) => { | |
| // localStorage.setItem(MY_TOKEN_KEY, token); | |
| // set cookie | |
| Cookies.set(MY_TOKEN_KEY, token); | |
| // set api sauce header authorization globally | |
| api.setHeader("Authorization", `Bearer ${token}`); | |
| }; | |
| export const useUser = () => { | |
| const [value, updateCookie, remove] = useCookie(MY_TOKEN_KEY); | |
| const { | |
| data, | |
| status, | |
| refetch, | |
| remove: clear, | |
| }: any = useQuery(["user.me"], async () => { | |
| const response: any = await API.me(); | |
| if (response.status === 401) { | |
| localStorage.set("token", null); | |
| } | |
| if (!response.ok) return null; | |
| return { | |
| ...response.data, | |
| }; | |
| }); | |
| return { | |
| user: data, | |
| loading: status === "loading", | |
| refetch, | |
| logout: () => { | |
| remove(); | |
| clear(); | |
| api.deleteHeader("Authorization"); | |
| window.location.reload(); | |
| }, | |
| }; | |
| }; | |