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 🎉

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay