Fetching data and formatting it #107
-
Hi, I'm looking at using domain functions for a number of remix projects, I am attempting to create a simple Todo list example, the user can have multiple lists, archive the list, add tasks to a list tick them off etc. I essentially wanted to understand what the best approach is for the situations I describe below: I have a function fetchLists:
This works great, but I'm looking to format the list (when retrieving tasks with them) so that there are two arrays one with completed tasks and one with active Tasks:
I created another domain function for this, which operates on a single list (this kinda follows a similar thing in the examples with the user domains)
My question is how best to handle the array of lists coming from the fetchLists function, am I approaching this correctly by separating the formatting into a DF or should this just be a utility? should I create a dedicated DF that fetches the list and formats them? Or is there a 'better' way to use the other DF functions like map & pipe to do this more in line with DF? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Do you always use |
Beta Was this translation helpful? Give feedback.
-
Hi @deanfields , thanks for reaching out! Glad to know you've been using DFs and Remix 🔥 I don't know if there's a best way but here is how I'd model it: import { makeDomainFunction as mdf, map } from "domain-functions"
const fetchLists = mdf(z.object({ withTasks: z.boolean().optional() }), UserSchema)(
async ({ withTasks = false }, { sessionId }) => {
// I'd put the body of fetchListsByUserId function here instead of creating another abstraction
// IMO the DF is the place to put the core of the business logic
// Excuse me for the pseudo code below
const response = await fetch(`${API}/lists/${sessionId}?withTasks=${withTasks}`)
const json = await response.json()
return z.array(listSchema).parse(json)
}
)
// typeof fetchLists === DomainFunction<List[]>
// I use map whenever I want to change the result of another DF:
const categorizedFetchLists = map(fetchLists, lists => lists.map(
(list) => ({ ...list, ...separateTasksByStatus(list.tasks) })
))
// typeof categorizedFetchLists === DomainFunction<List & { completedTasks: Task[]. activeTasks: Task[] }[]> That is just one way of doing it... I hope it helps! |
Beta Was this translation helpful? Give feedback.
Hi @deanfields , thanks for reaching out! Glad to know you've been using DFs and Remix 🔥
I don't know if there's a best way but here is how I'd model it: