DEV Community

Johannes Konings
Johannes Konings

Posted on

5 3

AWS Amplify API: GraphQL subscription

Usage in React

In order for the display to be updated immediately after a gameday or game has been created, a GraphQL subscription must be set up.

For this we need an import.


import { onCreateGameday, onCreateGame } from "./../../graphql/subscriptions";
Enter fullscreen mode Exit fullscreen mode

The subscription will be registerd with the start of the webapp.

  useEffect(() => {
    onPageRendered();
  }, []);

  const onPageRendered = async () => {
    readGameDays();
    subscribeGameDay();
    readPlayers();
    subscribeGame();
  };
Enter fullscreen mode Exit fullscreen mode

In the function for the subscription it is the API call and the update of the state

  const subscribeGameDay = async () => {
    await API.graphql(graphqlOperation(onCreateGameday)).subscribe({
      next: subonCreateGameday => {
        const variant = "success";
        enqueueSnackbar(
          "Gamday created: " + subonCreateGameday.value.data.onCreateGameday.id,
          { variant }
        );

        setGameDayItems(gameDayItems => [
          ...gameDayItems,
          [
            subonCreateGameday.value.data.onCreateGameday.id,
            subonCreateGameday.value.data.onCreateGameday.date
          ]
        ]);
      }
    });
  };
Enter fullscreen mode Exit fullscreen mode

This will look like this.

gameday creation

(recorded with https://www.cockos.com/licecap/)

The same with the games.

const subscribeGame = async () => {
    await API.graphql(graphqlOperation(onCreateGame)).subscribe({
      next: subonCreateGame => {
        const variant = "success";
        enqueueSnackbar(
          "Game created: " + subonCreateGame.value.data.onCreateGame.id,
          { variant }
        );

        setGameItems(gameItems => [
          ...gameItems,
          [
            subonCreateGame.value.data.onCreateGame.id,
            subonCreateGame.value.data.onCreateGame.player1.name,
            subonCreateGame.value.data.onCreateGame.player2.name,
            subonCreateGame.value.data.onCreateGame.resultPlayer1.toString(),
            subonCreateGame.value.data.onCreateGame.resultPlayer2.toString()
          ]
        ]);
      }
    });
  };
Enter fullscreen mode Exit fullscreen mode

That's all 🎉

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more