1

I'm writing a new app using react and aws-appsync and I can't make subscriptions work like I want.

I write a view, called by a router. It's a function tha uses states to store information. To fetch data from my apis, I wrote the code into fuctions, called by useEffect hooks, so that they are executed only one time. This part i ok.

I need to subscibe to appsync API, and I tried to do it in different ways with no success :

When I call it directly from the function, the code is called 10,000 times. So I tried with hooks :

   async function subscribe() {
  API.graphql(
      graphqlOperation(onAddRunLab, { client_id: userid, lab_id: labid })
  ).subscribe({
      next: ({ provider, value }) => updateInfo(value.data.onAddRunLab),
      error: error => console.warn(error)
  });
  
useEffect(() => {
  // Create an scoped async function in the hook
  async function anyNameFunction() {
    await subscribe();
  anyNameFunction();
}, []);

But, It does not work using hooks. I think the subscription is done but after that the link between rect and API is lost and the updateInfo function is never called.

Do you have any ideas ?

xadm
  • 8,219
  • 3
  • 14
  • 25
Jonathan
  • 111
  • 9

1 Answers1

2

You do not need to make the subscription an async function instead do the following and make sure that you unsubscribe from the subscription.

useEffect(() => {
  const subscription = API.graphql(
    graphqlOperation(onAddRunLab, { client_id: userid, lab_id: labid })
  ).subscribe({
    next: ({ provider, value }) => updateInfo(value.data.onAddRunLab),
    error: (error) => console.warn(error),
  });
  return () => subscription.unsubscribe();
}, []);
yudhiesh
  • 6,383
  • 3
  • 16
  • 49