Auto Save With Cleanup

Auto Save With Cleanup

Hard ReactJS Hooks & Effects 25 views
Explanation Complexity

Problem Statement

Auto-save text after user stops typing and cancel the pending save on change.

Input Format

No input.

Output Format

Render a React component.

Constraints

Use setTimeout in effect and clear it in cleanup.

Input / Output Format

Input Format
No input.
Output Format
Render a React component.
Constraints
Use setTimeout in effect and clear it in cleanup.

Examples

Input:
Output:
(React code)

Example Solution (Public)

ReactJS
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>
  );
}

Official Solution Code

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>
  );
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.