54 lines
1.3 KiB
JavaScript
54 lines
1.3 KiB
JavaScript
import { useState, } from 'react';
|
|
import UserService from "../services/UserService";
|
|
import BasketService from "../services/BasketService";
|
|
|
|
export function useUser() {
|
|
const [user, setUser] = useState(null);
|
|
|
|
function signOut() {
|
|
setUser(null);
|
|
localStorage.removeItem("user");
|
|
}
|
|
|
|
function checkIsAuth() {
|
|
const uuser = localStorage.getItem('user');
|
|
if (user) {
|
|
return;
|
|
}
|
|
if (uuser) {
|
|
const t = JSON.parse(uuser);
|
|
setUser(t);
|
|
}
|
|
}
|
|
|
|
async function login(data) {
|
|
try {
|
|
const response = await UserService.login(data);
|
|
setUser(response);
|
|
localStorage.setItem("user", JSON.stringify(response));
|
|
} catch (error) {
|
|
throw new Error(error);
|
|
}
|
|
}
|
|
|
|
async function registration(data) {
|
|
try {
|
|
const response = await UserService.registration({...data, "role": "user"});
|
|
const basketResponse = await BasketService.createBasket(response.id);
|
|
setUser(response);
|
|
localStorage.setItem("user", JSON.stringify(response));
|
|
} catch (error) {
|
|
throw new Error(error);
|
|
}
|
|
}
|
|
|
|
return {
|
|
userId: user ? user.id : null,
|
|
userIsAdmin: user ? user.role === "admin" : false,
|
|
userIsAuth: user ? user.id : false,
|
|
login,
|
|
registration,
|
|
signOut,
|
|
checkIsAuth
|
|
};
|
|
} |