svelte-apollo icon indicating copy to clipboard operation
svelte-apollo copied to clipboard

how to Implement subscribeToMore

Open freeseamew opened this issue 3 years ago • 2 comments

Is there any way currently to implement subscribeToMore ?

For example, the code below is 'subscribeToMore' implemented as react

const TodoLists = ({todos, subscribeToMore}) => {

  useEffect(() => {
    subscribeToMore({
      document: SUBSCRIBE_TODOS,
      updateQuery: (prev, { subscriptionData }) => {
        if (!subscriptionData.data) return prev;

        return {
          todos: [
            ...prev.todos,
            subscriptionData.data.todoAdded,
          ],
        };
      },      
    })

  }, [])

  return (
    <ul>
      {todos.map(todo => (
        <li key={todo._id}>
          {/* {todo._id},  */}
          {todo.title},  
          {todo.memo}
        </li>
      ))}
    </ul>
  );

}

Please give me a simple hint on how to implement 'subscribeToMore({})' here in svelte-apollo.

freeseamew avatar Nov 26 '20 17:11 freeseamew

Umm I've solved it in the following way.

const links = query(GET_LINKS,{})

links.subscribeToMore(
  {
    document: SUBSCRIBE_LINK,
    updateQuery: (prev, { subscriptionData }) => {
      if (!subscriptionData.data) return prev;
      return {
        links: [
          ...prev.links,
          subscriptionData.data.linkAdded,
        ],
      }
    }     
  }
);

and I also found that there are ways to use 'refetch()' as follows:

const links = query(GET_LINKS,{})

links.subscribeToMore(
  {
    document: SUBSCRIBE_LINK,
    updateQuery: (prev, { subscriptionData }) => {
       links.refetch(); 
    }     
  }
);

Please check if there is any problem with using it like this.

freeseamew avatar Nov 27 '20 09:11 freeseamew

Awesome approach @freeseamew, did you know how to use unsubscribe from subscribeToMore? Or using an instance of the subscription itself?

Something like this would be ideal:

<script>
  import { subscribe } from "svelte-apollo";
  import { NEW_BOOKS } from "./queries";

  const newBooks = subscribe(NEW_BOOKS);
  let paused = false;

  $:
    if (paused) newBooks.unsubscribe();
    else newBooks.subscribe();
</script>


<button on:click={() => paused = !paused}></button>

{#if $newBooks.loading}
  Waiting for new books...
{:else if $newBooks.data}
  New Book: {$newBooks.data.book}
{/if}

JohnnySpain20 avatar Dec 03 '20 14:12 JohnnySpain20