Files
iistwin/client/src/hooks/usePersistentDraft.ts

33 lines
1.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useState, useEffect, useRef, useCallback } from 'react';
/**
* Черновик сообщения с персистентностью в localStorage.
*
* Текст неотправленного сообщения живёт только в памяти (useState) и пропадает
* при перезагрузке страницы (обновление Service Worker после деплоя, редирект
* авторизации, дискард вкладки). Хук сохраняет текст по ключу и восстанавливает
* при монтировании и при смене ключа (другой чат). Очистка — обычным setValue('').
*/
export function usePersistentDraft(storageKey: string): [string, (value: string) => void] {
const [value, setValue] = useState<string>(() => {
try { return localStorage.getItem(storageKey) ?? ''; } catch { return ''; }
});
const keyRef = useRef(storageKey);
keyRef.current = storageKey;
// Смена чата — восстанавливаем черновик этого чата
useEffect(() => {
try { setValue(localStorage.getItem(storageKey) ?? ''); } catch { setValue(''); }
}, [storageKey]);
const set = useCallback((next: string) => {
setValue(next);
try {
if (next) localStorage.setItem(keyRef.current, next);
else localStorage.removeItem(keyRef.current);
} catch { /* localStorage недоступен (приватный режим и т.п.) */ }
}, []);
return [value, set];
}