Abort Fetch On Unmount
ReactJS
Hard
7 views
Problem Description
Fetch data and cancel the request using AbortController on cleanup.
Output Format
Render a React component.
Constraints
Create AbortController and call abort in cleanup.
Official Solution
import React, { useEffect, useState } from 'react';
export default function App() {
const [status, setStatus] = useState('idle');
const [items, setItems] = useState([]);
useEffect(() => {
const controller = new AbortController();
async function load() {
setStatus('loading');
try {
const res = await fetch('https://jsonplaceholder.typicode.com/users?_limit=5', { signal: controller.signal });
const json = await res.json();
setItems(json);
setStatus('success');
} catch (e) {
if (String(e && e.name) === 'AbortError') return;
setStatus('error');
}
}
load();
return () => controller.abort();
}, []);
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode users</h2>
{status === 'loading' ? <div>Loading...</div> : null}
{status === 'error' ? <div style={{ color: '#c1121f' }}>Request failed</div> : null}
{status === 'success' ? (
<ul style={{ paddingLeft: 18 }}>
{items.map((u) => <li key={u.id}>{u.name}</li>)}
</ul>
) : null}
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!