Handling Side Effects in TanStack Store
Explain how to handle side effects within a reactive application using TanStack Store, focusing on integrating API calls and synchronizing with the global state.
import { store } from 'tanstack-store-react';
// Define a global store
const globalStore = store({
data: null,
async fetchData() {
try {
const response = await fetch('https://api.example.com/data');
this.data = await response.json();
} catch (error) {
console.error('Failed to fetch data:', error);
}
}
});
This code snippet defines a global data store using TanStack Store. It initializes the store with a `data` state set to null and a method `fetchData` to asynchronously fetch data from an API and update the `data` state.
import { useEffect } from 'react';
import { useStore } from 'tanstack-store-react';
function App() {
const { data, fetchData } = useStore(globalStore);
useEffect(() => {
fetchData();
}, [fetchData]);
return (
<div>
{data ? <p>Data loaded successfully!</p> : <p>Loading data...</p>}
</div>
);
}
This code snippet demonstrates how to use the defined global store in a React component. It uses `useStore` to access the `data` state and the `fetchData` method from the global store. A `useEffect` hook is used to call `fetchData` when the component mounts, triggering the data fetching process. The component then renders a message based on whether `data` has been successfully loaded.