• Custom React hook to manage and fetch user reward data, as well as update the user's reward state.

    This hook retrieves user reward data, allows the state of the user reward to be updated, and provides methods for refreshing the data and handling errors.

    Parameters

    • Optional id: string

      The optional user ID to fetch the associated reward data. If no ID is provided, the reward cannot be fetched.

    Returns UseUserRewardReturn

    The returning object contains:

    • refresh: fetchUserRewardMethod - Function to refresh or re-fetch the user reward data.
    • updateUserRewardState updateUserRewardStateMethod - Function to update the state of the user reward.
    • userReward: The current user reward data. Can be null if no reward is available.
    • fetched: Boolean indicating whether the user reward data has been successfully fetched.

    Implementation Details

    • Caching: API responses are cached for 120 seconds to reduce redundant network calls.
    • Effect Trigger: Data fetch is triggered by changes to the id via useEffect.
    • Error Handling: Errors are logged and re-thrown with context for better debugging.
    • Refreshing Data: The refresh method forces a refetch of the data, optionally suppressing UI updates.
    • State Management: userReward holds the fetched data, and fetched indicates the loading status.

    Example

    import { useUserReward } from 'react-playmakers';

    const UserRewardComponent: React.FC = () => {
    const { userReward, fetched, refresh, updateUserRewardState } = useUserReward("URXXXXXXX");

    useEffect(() => {
    if (!fetched) {
    console.log("Fetching user reward...");
    }
    }, [fetched]);

    const handleUpdateRewardState = async () => {
    try {
    const updatedReward = await updateUserRewardState('newState');
    console.log('Updated user reward:', updatedReward);
    } catch (err) {
    console.error('Error updating user reward state:', err);
    }
    };

    return (
    <div>
    {fetched ? (
    <div>
    <h2>User Reward</h2>
    <p>{userReward ? `Reward State: ${userReward.state}` : "No reward available"}</p>
    <button onClick={handleUpdateRewardState}>Update Reward State</button>
    </div>
    ) : (
    <p>Loading...</p>
    )}
    <button onClick={() => refresh()}>Refresh Reward</button>
    </div>
    );
    };

Generated using TypeDoc