Blog>
Snippets

Replacing Redux Thunks with TanStack Store Queries

Show how to convert a Redux thunk function into a TanStack Store query for fetching data, including how to handle loading states and errors.
// Redux thunk example for fetching data
const fetchDataThunk = () => async (dispatch) => {
  dispatch({ type: 'FETCH_DATA_START' });
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    dispatch({ type: 'FETCH_DATA_SUCCESS', payload: data });
  } catch (error) {
    dispatch({ type: 'FETCH_DATA_FAILURE', payload: error });
  }
};
This is a Redux thunk function for fetching data from an API. It dispatches actions to update the store depending on whether the fetch operation succeeds or fails.
// Converting to TanStack Store query
import { createQuery } from '@tanstack/react-store';

const useFetchData = createQuery(async ({ queryKey }) => {
  const response = await fetch(queryKey[0]);
  if (!response.ok) throw new Error('Network response was not ok.');
  return response.json();
}, {
  // Define key for the query to use for caching and refetching
  queryKey: () => ['https://api.example.com/data']
});
This code snippet converts the Redux thunk function into a TanStack Store query for fetching data. It uses createQuery to define an async function that fetches data. Errors are handled by throwing exceptions, and the queryKey is used to uniquely identify and cache this query.
// Using the TanStack Store query in a component
function MyComponent() {
  const { data, error, isLoading } = useFetchData();

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

  return (
    <div>
      {/* Display fetched data here */}
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}
This is how you can use the TanStack Store query in a component. It destructures the data, error, and isLoading properties from the useFetchData hook to handle loading states and errors in the UI.