Skip to content

Instantly share code, notes, and snippets.

@jacob-ebey
Forked from AndrewIngram/toggle.jsx
Created October 27, 2023 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacob-ebey/9b0a1e8450ec595f17070525f8604d4e to your computer and use it in GitHub Desktop.
Save jacob-ebey/9b0a1e8450ec595f17070525f8604d4e to your computer and use it in GitHub Desktop.
Naive sketch of mutation API
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