Skip to content

Instantly share code, notes, and snippets.

View App.js
useEffect(() => {
API
.graphql(graphqlOperation(messagesByChannelId, {
channelID: '1',
sortDirection: 'ASC'
}))
.then((response) => {
const items = response?.data?.messagesByChannelID?.items;
if (items) {
View schema.graphql
type Message
@model
@key(name: "byChannelID", fields: ["channelID", "createdAt"], queryField: "messagesByChannelID") {
id: ID!
channelID: ID!
author: String!
body: String!
createdAt: AWSDateTime
updatedAt: AWSDateTime
}
View schema.graphql
type Message @model {
id: ID!
author: String!
body: String!
createdAt: AWSDateTime
updatedAt: AWSDateTime
}
View App.js
import React, { useEffect, useState } from 'react';
import Amplify from '@aws-amplify/core';
import API, { graphqlOperation } from '@aws-amplify/api';
import '@aws-amplify/pubsub';
import { createMessage } from './graphql/mutations';
import { onCreateMessage } from './graphql/subscriptions';
import { messagesByChannelId } from './graphql/queries';
View App.js
const [messageBody, setMessageBody] = useState('');
// useEffect(...) for loading initial messages
// useEffect(...) for subscriptions
const handleChange = (event) => {
setMessageBody(event.target.value);
};
View event shape
{
provider: { ... }, // this contains AppSync subscription metadata
value: {
data: {
onCreateMessage: {
id: "374fdfe6-71e4-4e02-b41f-d9d78037c916",
channelID: "1",
author: "Dave",
body: "This should be the new message",
createdAt: "2020-08-01T04:43:58.335Z",
View subscribe options
{
next: (event) => {
// do something with event
},
error: (error) => {
// raise or handle error
}
}
View App.js
// useEffect(..., []);
useEffect(() => {
const subscription = API
.graphql(graphqlOperation(onCreateMessage))
.subscribe({
next: (event) => {
setMessages([...messages, event.value.data.onCreateMessage]);
}
});
View App.js
import '@aws-amplify/pubsub';
import { onCreateMessage } from '../graphql/subscriptions';
View subscriptions.js
export const onCreateMessage = /* GraphQL */ `
subscription OnCreateMessage {
onCreateMessage {
id
channelID
author
body
createdAt
updatedAt
}
You can’t perform that action at this time.