Blog>
Snippets

State Normalization with TanStack Store

Showcase a practical example of normalizing state within TanStack Store to manage complex data structures efficiently.
import { createStore } from '@tanstack/react-store';

// Initial state with nested structure
const initialState = {
    posts: {
        1: { id: 1, title: 'TanStack Store Introduction', comments: [101] },
        2: { id: 2, title: 'State Management', comments: [102, 103] }
    },
    comments: {
        101: { id: 101, content: 'Great article!' },
        102: { id: 102, content: 'Very informative.' },
        103: { id: 103, content: 'Looking forward to more!' }
    }
};
Defines the initial application state with nested data structures, specifically posts and comments.
const useStore = createStore({
    initialState,
    actions: {
        addComment(postId, newComment) {
            return (state) => {
                const commentId = Object.keys(state.comments).length + 1;
                const newCommentId = `10${commentId}`;
                // Adding the new comment to the comments object
                state.comments[newCommentId] = { id: newCommentId, content: newComment };
                // Associating new comment ID with the post
                state.posts[postId].comments.push(newCommentId);
            };
        }
    }
});
Creates a TanStack Store with actions to add comments, showcasing how mutating operations are conducted on a normalized state structure.
// Example usage
useStore.getState().addComment(1, 'Another insightful post!');
Demonstrates how to use the store's action to interact with the state, in this case adding a new comment to a post.