0
0
GraphQLquery~5 mins

Refetching and polling in GraphQL

Choose your learning style9 modes available
Introduction

Refetching and polling help keep your data fresh by asking the server for updates regularly or on demand.

You want to update a list of messages in a chat app automatically.
You need to refresh stock prices every few seconds.
You want to reload user profile data after a user makes changes.
You want to keep a dashboard showing live data up to date.
Syntax
GraphQL
query YourQueryName {
  yourData {
    field1
    field2
  }
}

// Refetching: Call the query again manually when needed.

// Polling example (in Apollo Client):
useQuery(YOUR_QUERY, { pollInterval: 5000 })

Refetching means running the query again to get fresh data.

Polling means running the query automatically at set time intervals.

Examples
This is a simple query to get user IDs and names.
GraphQL
query GetUsers {
  users {
    id
    name
  }
}
You can call refetch() to manually update the data.
GraphQL
// Refetch example in Apollo Client
const { data, refetch } = useQuery(GET_USERS);

// Call refetch() when you want fresh data
This query runs every 10 seconds to get updated user data automatically.
GraphQL
// Polling example in Apollo Client
const { data } = useQuery(GET_USERS, { pollInterval: 10000 });
Sample Program

This query fetches messages and automatically updates every 3 seconds.

GraphQL
query GetMessages {
  messages {
    id
    text
    sender
  }
}

// In Apollo Client React hook:
const { data, loading, error } = useQuery(GET_MESSAGES, { pollInterval: 3000 });
OutputSuccess
Important Notes

Polling can increase server load; use it only when needed.

Refetching is good for manual updates, like after a user action.

Always handle loading and error states when fetching data.

Summary

Refetching updates data on demand by running the query again.

Polling updates data automatically at regular intervals.

Use these to keep your app's data fresh and responsive.