Příprava ukládání bankovního účtu

This commit is contained in:
2023-06-07 21:08:50 +02:00
parent 8525bc5c12
commit e8ceb02194
5 changed files with 156 additions and 7 deletions

View File

@@ -0,0 +1,74 @@
import React, { ReactNode, useContext, useState } from "react"
import { useEffect } from "react"
const BANK_ACCOUNT_NUMBER_KEY = 'bank_account_number';
const BANK_ACCOUNT_HOLDER_KEY = 'bank_account_holder_name';
export type BankContextProps = {
bankAccount?: string,
holderName?: string,
setBankAccountNumber: (accountNumber?: string) => void,
setBankAccountHolderName: (holderName?: string) => void,
}
type ContextProps = {
children: ReactNode
}
const bankContext = React.createContext<BankContextProps | null>(null);
export function ProvideBank(props: ContextProps) {
const bank = useProvideBank();
return <bankContext.Provider value={bank}>{props.children}</bankContext.Provider>
}
export const useBank = () => {
return useContext(bankContext);
}
function useProvideBank(): BankContextProps {
const [bankAccount, setBankAccount] = useState<string | undefined>();
const [holderName, setHolderName] = useState<string | undefined>();
useEffect(() => {
const accountNumber = localStorage.getItem(BANK_ACCOUNT_NUMBER_KEY);
if (accountNumber) {
setBankAccount(accountNumber);
}
const holderName = localStorage.getItem(BANK_ACCOUNT_HOLDER_KEY);
if (holderName) {
setHolderName(holderName);
}
}, [])
useEffect(() => {
if (bankAccount) {
localStorage.setItem(BANK_ACCOUNT_NUMBER_KEY, bankAccount)
} else {
localStorage.removeItem(BANK_ACCOUNT_NUMBER_KEY);
}
}, [bankAccount]);
useEffect(() => {
if (holderName) {
localStorage.setItem(BANK_ACCOUNT_HOLDER_KEY, holderName);
} else {
localStorage.removeItem(BANK_ACCOUNT_HOLDER_KEY);
}
}, [holderName]);
function setBankAccountNumber(bankAccount?: string) {
setBankAccount(bankAccount);
}
function setBankAccountHolderName(holderName?: string) {
setHolderName(holderName);
}
return {
bankAccount,
holderName,
setBankAccountNumber,
setBankAccountHolderName,
}
}