Multiple subscriptions in AWS Amplify react Connec

2020-07-24 04:21发布

问题:

I have a list of todo items and I would like to receive notifications when items are added or deleted from the list.

So far I have implemented item addition notification:

<Connect
        query={graphqlOperation(listTodos)}
        subscription={graphqlOperation(onCreateTodo)}
        onSubscriptionMsg={(prev, { onCreateTodo }) => {
            return addItem(prev, onCreateTodo)
        }}
    >
        {({ data: { listTodos }, loading, error }) => {
            if (loading) return "Loading"
            if (error) return "Error"

            return listTodos.items
                .map(({ id, name }) => <div key={id}>{name}</div>)
        }}
</Connect>

Now I am wondering, how can I add item deletion notification to this component? Does subscription attribute accept an array of graphql operations?

Thanks!

回答1:

You can use multiple Connect components in your component.

<Connect query={graphqlOperation(listTodos)}>
  {({ data: { listTodos }, loading, error }) => {
    if (loading) return "Loading"
    if (error) return "Error"

    return listTodos.items.map(({ id, name }) => <div key={id}>{name}</div>)
  }}
</Connect>

<Connect
  subscription={graphqlOperation(subscriptions.onCreateTodo)}
  onSubscriptionMsg={(prev, { onCreateTodo }) => {
    // Do something
    return prev;
  }}
>
  {() => {}}
</Connect>

<Connect
  subscription={graphqlOperation(subscriptions.onUpdateTodo)}
  onSubscriptionMsg={(prev, { onUpdateTodo }) => {
    // Do something
    return prev;
  }}
>
  {() => {}}
</Connect>


回答2:

Looks like the current solution is to create your own implementation of the Connect component as described in this github issue: https://github.com/aws-amplify/amplify-js/issues/4813#issuecomment-582106596