Function useVote

  • Custom React hook for managing votes on a submission.

    Parameters

    • Optional submissionId: string

      The ID of the submission for which votes are managed.

    Returns UseVoteReturn

    The object containing:

    • cancelVote: Cancels the current vote for a given submission.
    • downVote: Registers a downvote for a given submission.
    • upVote: Registers an upvote for a given submission.
    • fetched: A boolean flag indicating whether the vote status has been fetched.
    • myVote: Represents the current user's vote value.
    • voteBalance: Represents the total vote balance (sum of all votes) for the submission.

    Implementation Details

    • Real-Time Vote Balance Updates: The hook optimistically updates the vote balance when a vote action is performed, providing immediate visual feedback without waiting for API responses.
    • Caching: Fetches vote data and balance from the cache with expiration times (e.g., 120,000 ms for vote status and 60,000 ms for balance).
    • Error Handling: In case of an error during a vote action or data fetching, the hook reverts to the previous state (initial vote and balance), ensuring the UI remains consistent.
    • User Context: The hook leverages the useAuth hook to access the authenticated user's data to determine the current vote status.

    Example

    import { useVote } from 'react-playmakers';

    function SubmissionVoting('SXXXXXXXX') {
    const {
    upVote,
    downVote,
    cancelVote,
    fetched,
    myVote,
    voteBalance
    } = useVote(submissionId);

    if (!fetched) {
    return <div>Loading vote data...</div>;
    }

    return (
    <div>
    <p>Vote Balance: {voteBalance}</p>
    <p>My Vote: {myVote === 1 ? 'Up' : myVote === -1 ? 'Down' : 'None'}</p>
    <button
    onClick={() => upVote()}
    disabled={myVote === 1}
    >
    Upvote
    </button>
    <button
    onClick={() => downVote()}
    disabled={myVote === -1}
    >
    Downvote
    </button>
    <button
    onClick={() => cancelVote()}
    disabled={myVote === 0}
    >
    Cancel Vote
    </button>
    </div>
    );
    }

Generated using TypeDoc