44 lines
1.2 KiB
TypeScript
44 lines
1.2 KiB
TypeScript
import { useCallback, useEffect, useState } from 'react'
|
|
|
|
function useSendButtonCaption(
|
|
initial: string,
|
|
loading: boolean,
|
|
error: string | null,
|
|
result = initial,
|
|
singular = true
|
|
) {
|
|
const [caption, setCaption] = useState(initial)
|
|
const [disabled, setDisabled] = useState(false)
|
|
const [title, setTitle] = useState(initial)
|
|
|
|
const update = useCallback(<T extends NonNullable<unknown>>(data: T | undefined) => {
|
|
if (data !== undefined) {
|
|
setCaption(result)
|
|
setTitle('Отправить ещё раз')
|
|
|
|
if (singular) {
|
|
setDisabled(true)
|
|
setTitle('')
|
|
}
|
|
}
|
|
|
|
}, [result, singular])
|
|
|
|
useEffect(() => {
|
|
if (loading) {
|
|
setCaption('Загрузка...')
|
|
setTitle('Отменить и отправить ещё раз')
|
|
}
|
|
}, [loading])
|
|
|
|
useEffect(() => {
|
|
if (!loading && error !== null) {
|
|
setCaption(error + ', нажмите, чтобы попробовать ещё раз')
|
|
setTitle('')
|
|
}
|
|
}, [error, loading])
|
|
|
|
return { update, children: caption, disabled, title }
|
|
}
|
|
|
|
export default useSendButtonCaption |