Blog>
Snippets

Managing Async Data Fetching

Demonstrate fetching data asynchronously with TanStack Store, handling loading states, and integrating fetched data into the application state.
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';

// Define an async function to fetch your data
const fetchData = async () => {
  const { data } = await axios.get('https://api.example.com/data');
  return data;
};
This piece of code imports `useQuery` from TanStack Query (previously React Query) and axios for making HTTP requests. It defines an asynchronous function `fetchData` that uses axios to fetch data from an example API and return it.
const YourComponent = () => {
  // Use the useQuery hook to fetch data
  const { isLoading, error, data } = useQuery(['key'], fetchData);

  // Handle loading state
  if (isLoading) return <div>Loading...</div>;

  // Handle error state
  if (error) return <div>An error occurred: {error.message}</div>;

  // Render fetched data
  return <div>{JSON.stringify(data)}</div>;
};
This piece of code shows a functional component using the `useQuery` hook to fetch data with `fetchData`. It handles loading and error states, displaying appropriate messages, and finally renders the fetched data by converting it to a JSON string.