Prvotní nástřel fungující aplikace
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
import React, { ReactNode, useContext, useState } from "react"
|
||||
import { useEffect } from "react"
|
||||
|
||||
const LOGIN_KEY = 'login';
|
||||
|
||||
export type AuthContextProps = {
|
||||
login?: string,
|
||||
setLogin: (name: string) => void,
|
||||
clearLogin: () => void,
|
||||
}
|
||||
|
||||
type ContextProps = {
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
const authContext = React.createContext<AuthContextProps | null>(null);
|
||||
|
||||
export function ProvideAuth(props: ContextProps) {
|
||||
const auth = useProvideAuth();
|
||||
return <authContext.Provider value={auth}>{props.children}</authContext.Provider>
|
||||
}
|
||||
|
||||
export const useAuth = () => {
|
||||
return useContext(authContext);
|
||||
}
|
||||
|
||||
function useProvideAuth(): AuthContextProps {
|
||||
const [loginName, setLoginName] = useState<string | undefined>();
|
||||
|
||||
useEffect(() => {
|
||||
const login = localStorage.getItem(LOGIN_KEY);
|
||||
if (login) {
|
||||
setLogin(login);
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (loginName) {
|
||||
localStorage.setItem(LOGIN_KEY, loginName)
|
||||
} else {
|
||||
localStorage.removeItem(LOGIN_KEY);
|
||||
}
|
||||
}, [loginName]);
|
||||
|
||||
function setLogin(login: string) {
|
||||
setLoginName(login);
|
||||
}
|
||||
|
||||
function clearLogin() {
|
||||
setLoginName(undefined);
|
||||
}
|
||||
|
||||
return {
|
||||
login: loginName,
|
||||
setLogin,
|
||||
clearLogin
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user