/
lizardking
/
react_project
Обзор
Документация
Войти
/
lizardking
/
react_project
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/features/react19/FormWithAsyncSave/model/useFormWithAsyncSave.ts
62 строки
2 KB
LizardKing
Task 9 - React 19
14 ноя 2025, 20:35
14 ноя 2025, 20:35
86e4531
Код
Авторство
О чём код?
import { useActionState, useEffect, useRef, useState } from 'react' import { simulateDelay } from '../../lib/simulateDelay' import { initialFormWithAsyncSaveState, type FormWithAsyncSaveState } from './formState' export function useFormWithAsyncSave() { const [buttonLabel, setButtonLabel] = useState('Сохранить') const wasPendingRef = useRef(false) const [formState, formAction, isPending] = useActionState<FormWithAsyncSaveState, FormData>( async (_previousState, formData) => { const rawValue = formData.get('value') const value = typeof rawValue === 'string' ? rawValue.trim() : '' if (!value) { return { errorMessage: 'Поле не должно быть пустым', } } await simulateDelay(1000) return initialFormWithAsyncSaveState }, initialFormWithAsyncSaveState, ) useEffect(() => { if (isPending) { wasPendingRef.current = true setButtonLabel('Сохранение...') return } if (!isPending && wasPendingRef.current) { wasPendingRef.current = false if (!formState.errorMessage) { setButtonLabel('Сохранено!') const timeoutId = window.setTimeout(() => { setButtonLabel('Сохранить') }, 1000) return () => { window.clearTimeout(timeoutId) } } setButtonLabel('Сохранить') } return }, [isPending, formState.errorMessage]) return { formState, isPending, buttonLabel, formAction, } }