Last active
October 27, 2023 16:05
-
-
Save AndrewIngram/4d4aa2e441ffeb74a05de020d04125c9 to your computer and use it in GitHub Desktop.
Naive sketch of mutation API
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
function getIsLiked(viewerId, entityId) { | |
// hit a database or something | |
} | |
function toggleLikeStatus(viewerId, entityId) { | |
// hit a database or something | |
return !currentStatus; | |
} | |
function LikeButton({viewerId, entityId}) { | |
const isLiked = getIsLiked(viewerId, entityId); | |
// Somehow toggleHandle points to a generated endpoint that runs this handler | |
// toggleHandleState is a serialized representation of the dependency array | |
// updatedIsLiked points to the optimistic value, or new value | |
const [toggleHandle, toggleHandleState, updatedIsLiked] = useServerMutationHandle( | |
(viewerId, entityId) => toggleLikeStatus(viewerId, entityId), // returns new value | |
() => !isLiked, // optional optimistic update | |
[viewerId, entityId] | |
); | |
return ( | |
<form action="" method="POST"> | |
<input type="hidden" name="handler" value={toggleHandle} /> | |
<input type="hidden" name="state" value={toggleHandleState} /> | |
<button type="submit">{updatedIsLiked ?? isLiked ? 'Unlike' : 'Like'}</button> | |
</form> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment