Skip to content

Async Reward Example

An example that calls an async API on scratch completion to display win/loss results in the .reward area.

In this example, reward results are asynchronously displayed on completion. However, there are also cases where results are asynchronously fetched when Scratcher is created. In such cases, you can implement it in a similar way to this example.

Playground

Below is a playground example you can try directly.

Async API Function Example

Below is a temporary async API example that randomly returns win/loss results.

tsx
import React, { useRef, useState } from 'react';
import Scratcher from '@scratcher.js/react';

function getAsyncRewardAPI() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(Math.random() > 0.5 ? 'Win!' : 'Loss');
    }, 1000);
  });
}

export default function AsyncRewardExample() {
  const [reward, setReward] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const handleComplete = async () => {
    setLoading(true);
    const result = await getAsyncRewardAPI();
    setReward(result as string);
    setLoading(false);
  };

  return (
    <Scratcher width={320} height={180} onComplete={handleComplete}>
      <div className="reward">{loading ? 'Checking result...' : reward || 'Scratch to check!'}</div>
    </Scratcher>
  );
}