Optimistic Like Button
ReactJS
Hard
4 views
Problem Description
Create a like button that updates UI immediately and then confirms.
Output Format
Render a React component.
Constraints
Update state first, then simulate server with a delay.
Official Solution
import React, { useState } from 'react';
function wait(ms) {
return new Promise((r) => setTimeout(r, ms));
}
export default function App() {
const [likes, setLikes] = useState(10);
const [status, setStatus] = useState('');
async function like() {
setLikes((n) => n + 1);
setStatus('Saving...');
await wait(600);
setStatus('Saved on meetcode.');
await wait(700);
setStatus('');
}
return (
<div style={{ padding: 16 }}>
<h2 style={{ marginTop: 0 }}>meetcode post</h2>
<div style={{ color: '#555' }}>Likes: {likes}</div>
<button type='button' onClick={like} style={{ marginTop: 12, padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Like</button>
{status ? <div style={{ marginTop: 10, color: '#555' }}>{status}</div> : null}
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!