Fetch Data With Loading And Error
ReactJS
Hard
6 views
Problem Description
Fetch a fake list and show loading/error/success UI.
Output Format
Render a React component.
Constraints
Use fetch inside useEffect and handle states.
Official Solution
import React, { useEffect, useState } from 'react';
export default function App() {
const [state, setState] = useState({ status: 'idle', data: [], error: '' });
useEffect(() => {
let cancelled = false;
async function load() {
setState({ status: 'loading', data: [], error: '' });
try {
const res = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=5');
if (!res.ok) throw new Error('Request failed');
const json = await res.json();
if (!cancelled) setState({ status: 'success', data: json, error: '' });
} catch (e) {
if (!cancelled) setState({ status: 'error', data: [], error: String(e.message || e) });
}
}
load();
return () => { cancelled = true; };
}, []);
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode feed</h2>
{state.status === 'loading' ? <div>Loading...</div> : null}
{state.status === 'error' ? <div style={{ color: '#c1121f' }}>Error: {state.error}</div> : null}
{state.status === 'success' ? (
<ul style={{ paddingLeft: 18 }}>
{state.data.map((p) => (
<li key={p.id}>{p.title}</li>
))}
</ul>
) : null}
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!