You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
spa_instat_tv/src/features/CardsStore/hooks/index.tsx

61 lines
1.4 KiB

import {
useCallback,
useState,
useMemo,
} from 'react'
import find from 'lodash/find'
import type { Cards } from 'requests/getCardsList'
import { getCardsList } from 'requests/getCardsList'
import { addCard } from 'requests/addCard'
import { deleteCard } from 'requests/deleteCard'
import { setDefaultCard as setDefaultCardRequest } from 'requests/setDefaultCard'
import { useRequest, useToggle } from 'hooks'
export const useBankCards = () => {
const {
isOpen: infoModalOpen,
toggle: toggleInfoModal,
} = useToggle()
const [error, setError] = useState('')
const [cards, setCards] = useState<Cards | null>(null)
const defaultCard = useMemo(
() => find(cards, { default: true }),
[cards],
)
const fetchCards = useCallback(() => getCardsList().then(setCards), [])
const onAddCard = async (token: string) => (
addCard(token)
.catch(() => {
setError('error_can_not_add_card')
return Promise.reject()
})
.then(fetchCards)
)
const onDeleteCard = (cardId: string) => deleteCard(cardId).then(fetchCards)
const { isFetching, request: handleCardDelete } = useRequest(onDeleteCard)
const onSetDefaultCard = (cardId: string) => {
setDefaultCardRequest(cardId).then(fetchCards)
}
return {
cards,
defaultCard,
error,
fetchCards,
infoModalOpen,
isFetching,
onAddCard,
onDeleteCard: handleCardDelete,
onSetDefaultCard,
setError,
toggleInfoModal,
}
}