mirror of
https://github.com/mastodon/mastodon.git
synced 2025-05-07 20:26:15 +00:00
Streamline state/ref synchronization
This commit is contained in:
parent
83697d18e7
commit
10638e350f
|
@ -55,19 +55,8 @@ const InnerAccountNote: React.FC<Props> = ({ accountId }) => {
|
|||
const [value, setValue] = useState<string>(initialValue ?? '');
|
||||
const [saved, setSaved] = useState(false);
|
||||
|
||||
// We need to access the value on unmount
|
||||
const valueRef = useRef<string>(value);
|
||||
const dirtyRef = useRef(false);
|
||||
|
||||
// Keep the valueRef in sync with the state
|
||||
useEffect(() => {
|
||||
valueRef.current = value;
|
||||
}, [value]);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialValue !== valueRef.current) setValue(initialValue ?? '');
|
||||
}, [initialValue, setValue]);
|
||||
|
||||
useEffect(() => {
|
||||
dirtyRef.current = initialValue !== undefined && initialValue !== value;
|
||||
}, [initialValue, value]);
|
||||
|
@ -84,13 +73,6 @@ const InnerAccountNote: React.FC<Props> = ({ accountId }) => {
|
|||
[accountId, dispatch, setSaved],
|
||||
);
|
||||
|
||||
// Save changes on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (dirtyRef.current) onSave(valueRef.current);
|
||||
};
|
||||
}, [onSave]);
|
||||
|
||||
const handleChange = useCallback<ChangeEventHandler<HTMLTextAreaElement>>(
|
||||
(e) => {
|
||||
setValue(e.target.value);
|
||||
|
@ -120,6 +102,24 @@ const InnerAccountNote: React.FC<Props> = ({ accountId }) => {
|
|||
if (dirtyRef.current) onSave(value);
|
||||
}, [onSave, value]);
|
||||
|
||||
// To save the changes on unmount, we need to synchronize the state in a ref
|
||||
const valueRef = useRef<string>(value);
|
||||
|
||||
useEffect(() => {
|
||||
valueRef.current = value;
|
||||
}, [value]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (dirtyRef.current) onSave(valueRef.current);
|
||||
};
|
||||
}, [onSave]);
|
||||
|
||||
// Handle `initialValue` changes
|
||||
useEffect(() => {
|
||||
if (initialValue !== valueRef.current) setValue(initialValue ?? '');
|
||||
}, [initialValue, setValue]);
|
||||
|
||||
return (
|
||||
<div className='account__header__account-note'>
|
||||
<label htmlFor={`account-note-${accountId}`}>
|
||||
|
|
Loading…
Reference in New Issue
Block a user