Implement a blog feed with fetching and state
CoinbaseSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to handle asynchronous data fetching, state synchronization, and UI interactions in React, specifically managing a list of blog posts with optimistic updates and sorting.
Blog Feed Manager
You are building a blog feed component in React. Implement a BlogFeed component that fetches data from an API, displays a list of posts, and handles user interactions.
Requirements
- Data Fetching: On mount, fetch data from an async
fetchPosts()function. Display a loading state while fetching and handle potential error states. - Sorting: Provide a toggle to sort the posts by
createdAt(newest first) or bytitle(alphabetical). - Optimistic Deletion: When a user clicks 'Delete' on a post:
- Remove the post from the UI immediately (before the API call completes).
- Call an async
deletePost(postId)function. - If the API call fails, revert the state to show the deleted post again and display an error message.
- Data Structure: Each post has an
id(string),title(string), andcreatedAt(ISO string).
API Interfaces
// Provided functions
async function fetchPosts() { ... }
async function deletePost(postId) { ... }
Example Flow
- Initial State: Empty list, show 'Loading...'.
- Loaded: API returns
[{id: '1', title: 'B', createdAt: '2023-01-01'}, {id: '2', title: 'A', createdAt: '2023-02-01'}]. - Sorting: Toggle 'Alphabetical' -> List reorders to 'A', then 'B'.
- Deletion: Click delete on 'A'. 'A' disappears instantly from UI. API call triggers. If
deletePost('2')resolves, 'A' remains gone. If it rejects, 'A' reappears.
Constraints
- Use
useStateanduseEffecthooks. - Ensure the list remains deterministic even when an optimistic update is pending.
Hints
Hint 1
Use a local state to keep a 'source of truth' list and a derived state (or separate state) for the currently displayed list based on the sort criteria.
Hint 2
For optimistic updates, maintain a backup of the current list before modifying it so you can revert the state if the API call fails.
Hint 3
Use the `id` of the post to filter the list effectively during the deletion process.
Follow-up questions
- How would you optimize performance if the blog feed contained thousands of posts?
- How would you handle race conditions if the user triggers a 'Delete' action multiple times in quick succession?
- If you were to use a library like React Query (TanStack Query), how would your implementation change regarding optimistic updates?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.