Integrating TanStack Store with React Components
Provides a practical example of connecting TanStack Store's state to React components, using the store's hook to access and display state.
import { createQuery } from '@tanstack/react-query';
import { useState } from 'react';
Imports necessary functions from react-query and React.
const fetchUserData = async (userId) => {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) throw new Error('Network response was not ok.');
return response.json();
};
Defines an asynchronous function to fetch user data from an API.
function useUserData(userId) {
return createQuery(['userData', userId], () => fetchUserData(userId));
}
Creates a custom hook using createQuery hook from react-query, to fetch data for a specific user ID.
function UserProfile({ userId }) {
const { data: user, isLoading, error } = useUserData(userId);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error fetching user</div>;
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
);
}
Defines a React component to display user information using the custom hook to fetch and display data or an error/loading message.