State Normalization in TanStack Store
Showcases how to normalize state in TanStack Store for efficient data storage and retrieval, especially useful in cases of managing relational data.
import { defineStore } from 'tanstack-store-vue';
export const useArticlesStore = defineStore('articles', () => {
const articlesById = ref({});
const articleIds = ref([]);
function addArticles(articles) {
articles.forEach(article => {
// Add article ID to array for ordered references
if (!articleIds.value.includes(article.id)) {
articleIds.value.push(article.id);
}
// Normalize article data by ID for easy access and modification
articlesById.value[article.id] = article;
});
}
function getArticleById(id) {
return computed(() => articlesById.value[id]);
}
return { articlesById, articleIds, addArticles, getArticleById };
});
This example demonstrates state normalization within TanStack Store for efficient handling of relational data, such as articles. Articles are stored by their IDs in a dictionary for quick access and modification, while an array keeps track of their order. The `addArticles` function normalizes incoming articles by adding their IDs to the array if not already present, and setting them in the dictionary. The `getArticleById` function provides a reactive way to access an article by its ID.