Spaces:
Running
Running
File size: 1,296 Bytes
9cd6ddb |
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
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();
},
};
};
|