MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

ReactJS Program to Request Status State with Explanation

ReactJS Hard State Management 26 views
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around status, state, data. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Build a card that loads data and shows idle/loading/success/error states.

Input Format

No input.

Output Format

Render a React component.

Constraints

Store status and data separately and switch UI by status.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
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> ); }

Output Example

No sample I/O is provided for this question.

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next