T
TanStack3w ago
flat-fuchsia

Is a single item collection a valid pattern?

Hi! I really love the benefits that DB brings on top of Query. Especially the optimistic updates! However, I’ve been struggling to understand the mental model around single item collections, like user data. Should I create a users collection with a single item, and wrap the returned data from queryFn into an array to conform to an array? Having to specify the user id every time I want to get or update the user seems very boilerplaty too. On the other hand, I love optimistic updates in DB so much that I’d be fine treating the usersCollection as a table and cope with it. I found this issue from Kyle that seems to relate to this, but it appeared to focus more on helping with client state than server state.
GitHub
RFC: Simplified Single-Value State Management API for TanStack DB ...
Summary Introduce a slimmed-down API built on top of TanStack DB's collection system that can replace useState, Redux, Zustand, and other state management solutions. Each "item" would...
5 Replies
sensitive-blue
sensitive-blue3w ago
perhaps this is what you want? https://github.com/TanStack/db/issues/182
GitHub
add a .findOne() to query build to return the first item · Issue...
e.g. instead of: const { data: users } = useLiveQuery( (q) => q .from({ usersCollection }) .where(@usersCollection.id, =, userId), [userId] ) const user = users[0] We could write: const { da...
correct-apricot
correct-apricot3w ago
until findOne is shipped, what I do is pretty much what you said too const results = useLiveQuery(..) const thing = results.data.at(0) it's not as convenient but works like a charm
flat-fuchsia
flat-fuchsiaOP3w ago
oh ok👌 Could we expect single item collections to be a thing in near future? I guess it’s one of those little niceties that would make it easier to adopt DB, though I understand resources are finite and there’s probably still plenty on the roadmap! it would help, but storing the server’s user data in an array still feels like trying to fit a square peg into a round hole
sensitive-blue
sensitive-blue3w ago
you can also wrap this into a custom hook e.g. useUserData() to make it neater
flat-fuchsia
flat-fuchsiaOP3w ago
that's what I ended up doing, which was easier than I thought!

Did you find this page helpful?