Blog>
Snippets

Fetching and Caching Data with TanStack Ranger

Demonstrate how to fetch data from an API, cache it using TanStack Ranger, and display it in a React component, highlighting the library's caching mechanism.
import { useQuery } from '@tanstack/react-query';
import React from 'react';
Importing useQuery hook from TanStack Query (previously known as React Query) and React for building the component.
const fetchData = async () => {
  const response = await fetch('https://api.example.com/data');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};
Defines an asynchronous function to fetch data from an API.
function DataComponent() {
  const { data, error, isLoading } = useQuery(['dataKey'], fetchData);

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

  return (
    <div>
      <h1>Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}
React component utilizing the useQuery hook to fetch and cache the data. It handles loading states, error handling, and displays the fetched data.