Blog>
Snippets

Fetching Data with useQuery and Handling Offline State

Show how to fetch data using the useQuery hook and display different UI based on the online/offline state of the application, including loading, error, and success states.
import { useQuery } from '@tanstack/react-query';
import React, { useState, useEffect } from 'react';
import { View, Text, Button } from 'react-native';
import { onlineManager } from '@tanstack/react-query';
Imports necessary libraries and modules including useQuery from React Query, React hooks, and UI components from React Native. It also imports onlineManager to handle online/offline status.
const fetchData = async () => {
  const response = await fetch('https://myapi/data');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};
Defines an asynchronous function fetchData to fetch data from a hypothetical API endpoint and parse it as JSON.
const MyComponent = () => {
  const [isOnline, setIsOnline] = useState(onlineManager.isOnline());

  useEffect(() => {
    const unsubscribe = onlineManager.subscribe(setIsOnline);
    return () => unsubscribe();
  }, []);

  const { data, error, isLoading } = useQuery(['myData'], fetchData, {
    enabled: isOnline,
  });

  if (isLoading) return <Text>Loading...</Text>;
  if (error) return <Text>An error occurred: {error.message}</Text>;

  return (
    <View>
      {isOnline ? (
        <Text>Data: {JSON.stringify(data)}</Text>
      ) : (
        <Text>Offline mode: Data might be outdated.</Text>
      )}
    </View>
  );
};
MyComponent uses the useState and useEffect hooks to dynamically manage online/offline state changes with onlineManager. It fetches data using the useQuery hook with 'myData' as the query key and fetchData as the query function. It conditionally renders UI based on loading, error, or success states and communicates offline status to the user.
export default MyComponent;
Exports MyComponent as the default export of the module, making it available for use in other parts of the application.