ReactJS Program to Async Username Check with Explanation
ReactJS
Hard
Forms & Validation
19 views
1 min read
86 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around async, username, check. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Validate a username asynchronously and show loading/available states.
Input Format
No input.
Output Format
Render a React component.
Constraints
Trigger async check on blur and ignore outdated requests.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { useRef, useState } from 'react';
function fakeCheck(name) {
return new Promise((resolve) => {
setTimeout(() => {
const taken = ['admin', 'root', 'meetcode'];
resolve({ available: !taken.includes(name.toLowerCase()) });
}, 700);
});
}
export default function App() {
const [name, setName] = useState('');
const [status, setStatus] = useState('idle');
const [msg, setMsg] = useState('');
const requestId = useRef(0);
async function check() {
const v = name.trim();
if (!v) return;
setStatus('loading');
setMsg('Checking...');
const id = ++requestId.current;
const res = await fakeCheck(v);
if (id !== requestId.current) return;
if (res.available) {
setStatus('ok');
setMsg('Available');
} else {
setStatus('bad');
setMsg('Already taken');
}
}
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>Pick username</h2>
<label style={{ fontWeight: 700 }}>Username</label>
<input value={name} onChange={(e) => setName(e.target.value)} onBlur={check} placeholder='Type and leave the field' style={{ marginTop: 6, width: '100%', padding: '10px 12px', borderRadius: 12, border: '1px solid ' + (status === 'bad' ? '#c1121f' : '#bbb') }} />
<div style={{ marginTop: 10, color: status === 'bad' ? '#c1121f' : '#555' }}>{msg || 'Tip: try meetcode or admin'}</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).
Solution Guide
Problem
Validate a username asynchronously and show loading/available states.
Input / Output
Output
Render a React component.
Constraints
Trigger async check on blur and ignore outdated requests.
Details
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).
Official Solution
import React, { useRef, useState } from 'react';
function fakeCheck(name) {
return new Promise((resolve) => {
setTimeout(() => {
const taken = ['admin', 'root', 'meetcode'];
resolve({ available: !taken.includes(name.toLowerCase()) });
}, 700);
});
}
export default function App() {
const [name, setName] = useState('');
const [status, setStatus] = useState('idle');
const [msg, setMsg] = useState('');
const requestId = useRef(0);
async function check() {
const v = name.trim();
if (!v) return;
setStatus('loading');
setMsg('Checking...');
const id = ++requestId.current;
const res = await fakeCheck(v);
if (id !== requestId.current) return;
if (res.available) {
setStatus('ok');
setMsg('Available');
} else {
setStatus('bad');
setMsg('Already taken');
}
}
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>Pick username</h2>
<label style={{ fontWeight: 700 }}>Username</label>
<input value={name} onChange={(e) => setName(e.target.value)} onBlur={check} placeholder='Type and leave the field' style={{ marginTop: 6, width: '100%', padding: '10px 12px', borderRadius: 12, border: '1px solid ' + (status === 'bad' ? '#c1121f' : '#bbb') }} />
<div style={{ marginTop: 10, color: status === 'bad' ? '#c1121f' : '#555' }}>{msg || 'Tip: try meetcode or admin'}</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!