Last active
April 7, 2021 13:58
-
-
Save ilxanlar/ea53e716ade2360d5d59a6adf0942f1d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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