Auto Save With Cleanup
ReactJS
Hard
6 views
Problem Description
Auto-save text after user stops typing and cancel the pending save on change.
Output Format
Render a React component.
Constraints
Use setTimeout in effect and clear it in cleanup.
Official Solution
import React, { useEffect, useState } from 'react';
export default function App() {
const [text, setText] = useState('');
const [saved, setSaved] = useState('');
const [status, setStatus] = useState('idle');
useEffect(() => {
if (!text) return;
setStatus('waiting');
const id = setTimeout(() => {
setSaved(text);
setStatus('saved');
}, 700);
return () => clearTimeout(id);
}, [text]);
return (
<div style={{ padding: 16, width: 560 }}>
<h2 style={{ marginTop: 0 }}>meetcode autosave</h2>
<textarea value={text} onChange={(e) => setText(e.target.value)} rows={4} style={{ width: '100%', padding: 12, borderRadius: 12, border: '1px solid #bbb' }} />
<div style={{ marginTop: 8, color: '#555' }}>Status: {status}</div>
<div style={{ marginTop: 8, color: '#555' }}>Saved: {saved || 'Nothing yet'}</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!