Skip to content

Instantly share code, notes, and snippets.

@ilxanlar
Last active April 7, 2021 13:58
Show Gist options
  • Save ilxanlar/ea53e716ade2360d5d59a6adf0942f1d to your computer and use it in GitHub Desktop.
Save ilxanlar/ea53e716ade2360d5d59a6adf0942f1d to your computer and use it in GitHub Desktop.
import React from 'react'
const markAsDone = async (todoId) => {
// Send a request to mark a todo as done
}
export default function Todo({ todo }) {
const handleMarkAsDone = async (todo) => {
// Optimistically update local state to mark this task as done
setState(prevState => ({
...prevState,
todos: prevState.todos.map(item => {
if (item.id === todo.id) {
return {
...item,
done: true
}
}
return item
})
}))
try {
// Send the actual API request to the server
await markAsDone(todo.id)
} catch (error) {
// Rollback if the API request fails
setState(prevState => ({
...prevState,
todos: prevState.todos.map(item => {
if (item.id === todo.id) {
return {
...item,
done: false
}
}
return item
})
}))
}
}
return (
<li>
<p>{todo.title}</p>
{todo.done ? (
<strong>Done</strong>
) : (
<button onClick={() => handleMarkAsDone(todo)}>
Mark as Done
</button>
)}
</li>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment