Optimizing Data Fetching with TanStack Store
Illustrate how to use TanStack Store for efficient data fetching and caching, using a posts store as an example. Show how to create a store that fetches post data from an API and caches it for future use.
import { createStore } from 'react-sweet-state';
// Action for fetching posts
cconst fetchPosts = async () => {
const response = await fetch('https://example.com/api/posts');
if (!response.ok) throw new Error('Failed to fetch');
const data = await response.json();
return data;
};
Defines an asynchronous action using 'fetchPosts' to retrieve posts from a sample API endpoint.
const initialState = {
posts: [],
loading: false,
error: null
};
Setup the initial state for the store, including an empty posts array, loading state, and an error field.
const actions = {
getPosts: () => async ({ setState, getState }) => {
try {
setState({ loading: true });
const posts = await fetchPosts();
setState({ posts, loading: false });
} catch (error) {
setState({ error, loading: false });
}
}
};
Defines the 'getPosts' action which fetches posts asynchronously, updates the state with the new data, handles loading state, and catches any errors.
const Store = createStore({
initialState,
actions,
name: 'postsStore'
});
Creates the 'postsStore' using Sweet State, with the provided initialState and actions.
export default Store;
Exports the configured store for use across the React application.