T
TanStack5w ago
eastern-cyan

Preventing waterfalls for (mostly) static data?

Hey everyone, i'm currently making a duolingo clone as a practice project and have some issues with designing the initial fetch for the "paths" part and how to store data afterwards. The app is structured in a way that a course has multiple sections, a section has multiple units, and a unit has multiple lessons. The situation is, where when a user loads a section, it should ideally fetch all units and lessons for the section that was loaded. The units and lessons dont change often, but i am not 100% sure, My question is how to best do and then store this initial fetch on tanstack query? I checked the docs regarding waterfalls, but they mostly provided several options for how to handle the fetch, but im not so clear on how to store the data after. From what i understood from the docs, sending a big tree as something like this might be best?
SectionTree : {

SectionTreeNode:
SectionObject,
Units: [
UnitTreeNode: {
UnitObject,
Lessons: [LessonObject, LessonObject, LessonObject]
},
UnitTreeNode: {
UnitObject,
Lessons: [LessonObject, LessonObject, LessonObject]
}
]
}
SectionTree : {

SectionTreeNode:
SectionObject,
Units: [
UnitTreeNode: {
UnitObject,
Lessons: [LessonObject, LessonObject, LessonObject]
},
UnitTreeNode: {
UnitObject,
Lessons: [LessonObject, LessonObject, LessonObject]
}
]
}
However, once the frontend receives the tree, should i store each unit in a ["unit", unitId"] and each lesson in a ["lesson", lessonId], or should i have an array of units as a query and same for lessons? Should i have 2 query keys, one for the result of each section/ unit / lesson of the big tree, and another for an actual section/unit/lesson that might mutate? Thank you in advance guys!
1 Reply
correct-apricot
correct-apricot5w ago
Build your API in a way that it's reliable and fast, if everything you need to display can be retreived with one call, thats good. Let's say you only have the one Endpoint that retreives everything: I'd build hooks for each View…
useSection({ sectionId }) // returns Units
useUnit({ unitId }) // returns Lessons
useLesson({ lessonId }) // returns single Lesson
useSection({ sectionId }) // returns Units
useUnit({ unitId }) // returns Lessons
useLesson({ lessonId }) // returns single Lesson
…that are using select (https://tanstack.com/query/latest/docs/framework/react/guides/render-optimizations#select) to only get the part you are interested in (Lesson(s), Unit(s) or Section(s)) This way if you change the API you only need to change the implementation inside your useSection, useUnit, … hooks and everything else stays the same.

Did you find this page helpful?