Request Status State
ReactJS
Hard
4 views
Problem Description
Build a card that loads data and shows idle/loading/success/error states.
Output Format
Render a React component.
Constraints
Store status and data separately and switch UI by status.
Official Solution
import React, { useEffect, useState } from 'react';
function fakeLoad() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const ok = Math.random() > 0.25;
if (ok) resolve({ user: 'Meetcode Learner', streak: 7 });
else reject(new Error('Server busy'));
}, 650);
});
}
export default function App() {
const [status, setStatus] = useState('idle');
const [data, setData] = useState(null);
const [error, setError] = useState('');
async function load() {
setStatus('loading');
setError('');
setData(null);
try {
const res = await fakeLoad();
setData(res);
setStatus('success');
} catch (e) {
setError(String(e.message || e));
setStatus('error');
}
}
useEffect(() => {
load();
}, []);
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode profile</h2>
<button type='button' onClick={load} disabled={status === 'loading'} style={{ padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Reload</button>
<div style={{ marginTop: 12, border: '1px solid #eee', borderRadius: 16, padding: 14 }}>
{status === 'idle' ? <div style={{ color: '#555' }}>Click reload.</div> : null}
{status === 'loading' ? <div>Loading...</div> : null}
{status === 'error' ? <div style={{ color: '#c1121f' }}>{error}</div> : null}
{status === 'success' ? (
<div>
<div><strong>{data.user}</strong></div>
<div style={{ color: '#555', marginTop: 6 }}>Streak: {data.streak} days</div>
</div>
) : null}
</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!