Abortable Fetch Effect
ReactJS
Hard
6 views
Problem Description
Fetch data in an effect and cancel when the component unmounts.
Output Format
Render a React component.
Constraints
Use AbortController and ignore results when aborted.
Official Solution
import React, { useEffect, useState } from 'react';
export default function App() {
const [status, setStatus] = useState('idle');
const [data, setData] = useState(null);
const [error, setError] = useState('');
useEffect(() => {
const ac = new AbortController();
async function run() {
setStatus('loading');
setError('');
setData(null);
try {
const res = await fetch('https://jsonplaceholder.typicode.com/todos/2', { signal: ac.signal });
const json = await res.json();
setData(json);
setStatus('success');
} catch (e) {
if (ac.signal.aborted) return;
setError(String(e.message || e));
setStatus('error');
}
}
run();
return () => ac.abort();
}, []);
return (
<div style={{ padding: 16, width: 560 }}>
<h2 style={{ marginTop: 0 }}>meetcode abortable fetch</h2>
{status === 'loading' ? <div>Loading...</div> : null}
{status === 'error' ? <div style={{ color: '#c1121f' }}>{error}</div> : null}
{status === 'success' ? <pre style={{ background: '#f6f8fa', padding: 12, borderRadius: 14 }}>{JSON.stringify(data, null, 2)}</pre> : null}
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!