DEV Community

Johannes Konings
Johannes Konings

Posted on

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";

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

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

  const onPageRendered = async () => {
    readGameDays();
    subscribeGameDay();
    readPlayers();
    subscribeGame();
  };

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
          ]
        ]);
      }
    });
  };

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()
          ]
        ]);
      }
    });
  };

That's all 🎉

Oldest comments (0)