Async Username Check
ReactJS
Hard
5 views
Problem Description
Validate a username asynchronously and show loading/available states.
Output Format
Render a React component.
Constraints
Trigger async check on blur and ignore outdated requests.
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!
No comments yet. Start the discussion!