Fetch public todos - subscription

Now let's define the subscription query to get notified about new public todos

Create a new file with name src/components/Todo/NotifyNewPublicTodosSubscription.res and add the following query.

let make = %graphql(`
subscription {
where: { is_public: { _eq: true } }
limit: 1
order_by: [{ created_at: desc }]
) {
user {

Creating a new file for this query will help us reference this query module in other modules easily.

What does the Subscription do?

The query fetches todos with a simple condition; is_public must be true. We also limit the number of todos to 1, since we would just like to get notified whenever a new todo comes in. We sort the todos by its latest created_at time according to the schema. We specify which fields we need for the todos node.

Now let's create a React components that uses this subscription query.

Create a file with name src/components/Todo/TodoPublicListSubscription.res and add the following code.

let make = () => {
let newTodoSubscriptionResult = NotifyNewPublicTodosSubscription.use()
switch newTodoSubscriptionResult {
| {loading: true} => <div> {React.string("Loading...")} </div>
| {data: Some({todos})} =>
<TodoPublicList latestTodo={Js.Array.length(todos) > 0 ? Some(todos[0]) : None} />
| {error: Some(_error)} => <div> {React.string("Error!")} </div>
| {data: None, error: None, loading: false} => React.null

This component subscribes to the new public todos and passes latestTodo as prop to TodoPublicList

Now, we can render TodoPublicListSubscription instead of TodoPublicList in TodoPublicWrapper component.


Get Started with GraphQL Now

Hasura Cloud gives you a fully managed, production ready GraphQL API as a service to help you build modern apps faster.
Ready to get started?
Start for free on Hasura Cloud or you could contact our sales team for a detailed walk-through on how Hasura may benefit your business.
Stay in the know
Sign up for full access to our community highlights, new features, and occasional baby animal gifs! Oh, and we have a strict no-spam rule. โœŒ๏ธ