Advanced React 08.1 · Ecosystem
Data that belongs together
A customer and their orders from different tables: joining on the server, a dependent query with enabled, parallel queries and labels as a tree.
Loading lesson…
Advanced React 08.1 · Ecosystem
A customer and their orders from different tables: joining on the server, a dependent query with enabled, parallel queries and labels as a tree.
Loading lesson…
This sub-lesson follows on from Advanced React 08 – it assumes you know useQuery, labels (queryKey) and invalidation. There every query downloaded one thing: a list of products, one user. A real app, though, nearly always needs data that belongs together and lives in different tables in the database.
Take an online shop. The database has a table of customers and a table of orders. An order doesn't remember the customer's whole name and address – only her id, in the userId column. Databases call that a foreign key: a number that points to a row in another table. Read the tables on the left and right as two sheets of paper; the arrow is what links them:
| users (customers) | orders |
|---|---|
| id 1 – Anna Smith, anna@example.com | id 101 – userId 1 → belongs to Anna |
| id 2 – Peter Brown, peter@example.com | id 102 – userId 1 → Anna’s too |
| id 3 – Eve Davis, eve@example.com | id 103 – userId 2 → belongs to Peter |
The "My account" page should show the customer's name and the list of her orders. That's two pieces of data from two tables. The straightforward attempt looks like this:
// ❌ not like this// fetchUserByEmail(email) and fetchOrders(userId) = made-up functions that download the customer and her ordersfunction MyAccount({ email }: { email: string }) {const { data: user } = useQuery({queryKey: ['users', 'by-email', email],queryFn: () => fetchUserByEmail(email),})const { data: orders } = useQuery({queryKey: ['users', user.id, 'orders'], // 💥 user is undefined at firstqueryFn: () => fetchOrders(user.id),})// …}
What happens: on the first render the customer hasn't arrived yet, user is undefined and user.id ends in the error "Cannot read properties of undefined". And even if it didn't crash, the second query would start at once – without the id we don't have yet. We're missing three things:
In the noticeboard picture from lesson 08: the customer and her orders are two different folders. The keeper doesn't know they belong together – to it they're just two labels. You create the link between them: with what you put in the label, and with when you let the second folder be fetched.
Related data can be loaded in four ways. The table shows the situation on the left, the way in the middle and the section of this sub-lesson on the right. Read it from the top: the first row is the simplest, and the next ones come in when the one before doesn't work.
| Situation | Way | Section |
|---|---|---|
| the server can return the customer together with her orders | one query – the server joins it | 1 |
| you know the id in advance (from the address, from props) | two queries side by side – they run in parallel | 2 |
| the second query needs something from the result of the first | a dependent query with enabled | 3 |
| a list and more data for each item | useQueries – or better, join it on the server | 4 |
A database can join tables by itself – the SQL language calls it a JOIN ("attach to each order the customer row with the same id"). That's why plenty of APIs offer an address that returns the customer together with her orders, say /users/1?include=orders. On the client you then have a single query:
// fetchUserWithOrders(id) = a made-up function: one request, the server returns { id, name, …, orders: [ … ] }function MyAccount({ userId }: { userId: number }) {const { data, isPending, isError, error } = useQuery({queryKey: ['users', userId, 'with-orders'],queryFn: () => fetchUserWithOrders(userId),})if (isPending) return <p>Loading…</p>if (isError) return <p>{error.message}</p>return (<><h2>{data.name}</h2><ul>{data.orders.map((o) => <li key={o.id}>Order #{o.id}</li>)}</ul></>)}
One request, one "Loading…", no query waiting for another. That's why it's the first choice whenever the API can do it. GraphQL (another way of asking a server) works like that too: in one query you ask for the customer together with her orders.
On the page /customers/1 you know the customer's id before you download anything – it's in the address (useParams from Advanced React 07). So the second query doesn't have to wait for the first. You simply write them one below the other:
// fetchUser(id) and fetchOrders(userId) = made-up functions, each downloads one tablefunction CustomerPage() {const userId = Number(useParams().userId) // from the address /customers/1 → 1const user = useQuery({queryKey: ['users', userId],queryFn: () => fetchUser(userId),})const orders = useQuery({queryKey: ['users', userId, 'orders'], // the id is known at once → the query starts at oncequeryFn: () => fetchOrders(userId),})if (user.isPending || orders.isPending) return <p>Loading…</p>if (user.isError) return <p>{user.error.message}</p>if (orders.isError) return <p>{orders.error.message}</p>return (<><h2>{user.data.name}</h2><ul>{orders.data.map((o) => <li key={o.id}>Order #{o.id}</li>)}</ul></>)}
useQuery but store all of it in user and orders. Both queries return the same names (data, isPending…), and this way they don't get mixed up: user.data is the customer, orders.data the orders.|| = "at least one is still waiting"). If you wanted to show the name sooner, you can handle each part separately.On the "My account" page, though, you don't know the id in advance – you only have the signed-in customer's e-mail. You learn her id only from the first query, and only with it can you download the orders. The second query depends on the first. For that, useQuery has the enabled option: while it's false, the query downloads nothing and waits. A template with blanks:
const { data: first } = useQuery({ … }) // the first query as usualconst { data: second } = useQuery({queryKey: [ ___ , first?.___ ], // the label contains what the second query needs from the firstqueryFn: () => fetch___(first!.___),enabled: ___, // the condition "first is here by now"})
You fill it in with the answers to three questions:
user?.id – while there's no customer, it's undefined and nothing crashes (?. from JavaScript 06).user !== undefined.// ✅ like thisfunction MyAccount({ email }: { email: string }) {// 1. the customer by e-mailconst { data: user } = useQuery({queryKey: ['users', 'by-email', email],queryFn: () => fetchUserByEmail(email),})// 2. her orders – once the id is knownconst { data: orders } = useQuery({queryKey: ['users', user?.id, 'orders'],queryFn: () => fetchOrders(user!.id), // ! = "user is here by now" – enabled guarantees itenabled: user !== undefined, // while there's no customer, the query waits})if (!user || !orders) return <p>Loading…</p>return (<><h2>{user.name}</h2><ul>{orders.map((o) => <li key={o.id}>Order #{o.id}</li>)}</ul></>)}
What happens when the page opens:
user is undefined, so enabled is false and the second query downloads nothing. The label ['users', undefined, 'orders'] doesn't matter – a query that isn't allowed to run fetches nothing.user.id is 1, enabled is true and the label changes to ['users', 1, 'orders']. Only now does the second query start.You know the exclamation mark in user!.id from TypeScript 02: it tells TypeScript "trust me, user isn't undefined here". It doesn't know by itself, because it doesn't see the connection with enabled. We do: queryFn is called only when enabled is true, that is, when user exists.
What you see: Two buttons that load the customer Anna and her orders – once with a dependent query (the id is looked up from the e-mail), once side by side (the id is known in advance). Every request takes 600 ms. Below the card you see how long it took.
Try it:
The takeaway: A dependent query is the right solution when you really don't know the id – but every wait adds up. When you know the id in advance, let the queries run side by side.
Loading the interactive part…
Queries that wait for each other are called a waterfall – the data comes down step by step like water down stairs. With two steps it doesn't matter. But if the orders waited for the customer and the order items in turn for the orders, the user would wait three times. So it pays to weigh every step: can't the id be found some other way (from the address, from the sign-in), or can't the whole thing be joined on the server (section 1)? More about waterfalls is in the "Waterfalls" tip in Advanced React 08.
A different case: you have a list of all customers' orders and want to show the customer's name with each one. So each order comes with one query for its customer – as many queries as orders. You mustn't call useQuery in a loop (the rules of hooks from React basics 03), so TanStack Query offers useQueries: it gets an array of queries and returns an array of results in the same order.
// orders = the already downloaded list of orders, each has a userId// Set removes repeated ids (JavaScript 05): Anna has two orders, she's downloaded only onceconst userIds = [...new Set(orders.map((o) => o.userId))]const userQueries = useQueries({queries: userIds.map((id) => ({queryKey: ['users', id], // the same label as on the customer pagequeryFn: () => fetchUser(id),})),})// userQueries[0] belongs to userIds[0], userQueries[1] to userIds[1]…// every item has the same names as the result of useQuery: data, isPending, isError…
['users', id] – the same one the customer page uses. When the user then clicks through, the data is already on the noticeboard.You know from lesson 08 that invalidateQueries compares labels by their start: ['posts'] also crosses out ['posts', { page: 2 }]. When you give related data labels that start the same way, they form a tree – and a whole branch can be crossed out at once:
['users'] // the list of customers['users', 1] // customer no. 1['users', 1, 'orders'] // her orders['users', 1, 'orders', 101] // one of her orders
The table shows what each call crosses out. On the left the label you pass to invalidateQueries({ queryKey: … }), on the right the folders that get downloaded again:
| queryKey in invalidateQueries | Crosses out |
|---|---|
['users', 1, 'orders'] | the orders of customer 1 (and the single orders below them) |
['users', 1] | customer 1 and everything below her – the orders too |
['users'] | absolutely everything about all customers |
If the customer adds a new order, crossing out ['users', 1, 'orders'] is enough – the name didn't change, so it doesn't need downloading. If she changes her name, you cross out ['users', 1]. That's why you build labels from the general to the specific: first "what it's about" ('users'), then "which one" (1), then "what part of it" ('orders').
When you need data that belongs together, go through these questions in this order:
enabled, and the value from the first query in the label.// LABELS AS A TREE – from the general to the specific['users', userId] // a customer['users', userId, 'orders'] // their orders// SIDE BY SIDE – the id known in advanceconst user = useQuery({ queryKey: ['users', userId], queryFn: () => fetchUser(userId) })const orders = useQuery({ queryKey: ['users', userId, 'orders'], queryFn: () => fetchOrders(userId) })// DEPENDENT – the id only from the first queryconst { data: me } = useQuery({ queryKey: ['users', 'by-email', email], queryFn: () => fetchUserByEmail(email) })const { data: myOrders } = useQuery({queryKey: ['users', me?.id, 'orders'],queryFn: () => fetchOrders(me!.id),enabled: me !== undefined,})// AFTER A CHANGE – cross out the branchqueryClient.invalidateQueries({ queryKey: ['users', userId, 'orders'] })
Recipes – on the left what you want, on the right what you write:
| I want… | I write |
|---|---|
| a customer with their orders in one request | one useQuery for an address that joins them (?include=orders) |
| two pieces of data whose id I know from the address | two useQuery one below the other |
| data that needs the result of another query | enabled: first !== undefined and first?.id in the label |
| one query for each item of a list | useQueries({ queries: array.map(…) }) |
| to refresh everything about a customer after a change | invalidateQueries({ queryKey: ['users', id] }) |
enabled and the value from the first query in its label.Fill in a dependent query: the orders for the right id, and only once the customer has arrived. The first query and the look are finished.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
Loading the interactive part…
?include=, GraphQL) – one request, no waiting.enabled, and a waterfall worth shortening.['users', id, 'orders']) – after a change you cross out a whole branch with one call.QueryClient, QueryClientProvider, useQuery, fetchOrders, fetchUserByEmail)QueryClient, QueryClientProvider, useQuery – from the library @tanstack/react-query: the data fetching and caching library (lesson Advanced React 08).fetchOrders, fetchUserByEmail – from the file src/course/fakeApi.en.ts. The course fake API: data and functions pretending to be a server (with a delay, sometimes even with an error). In a real app you would call fetch() here./** An order in a second "table" – userId points to the user it belongs to (Advanced React 08.1). */export interface Order {id: numberuserId: numberitems: number}/** The orders of one user (a fixed delay). */export async function fetchOrders(userId: number): Promise<Order[]> {await sleep(600)return orders.filter((o) => o.userId === userId)}export interface User {id: numbername: stringemail: stringcity: string}/** Finds a user by e-mail – a fixed delay, so the demo's timeline is easy to read. */export async function fetchUserByEmail(email: string): Promise<User> {await sleep(600)const user = users.find((u) => u.email === email)if (!user) throw new Error(`There is no user with the e-mail ${email}`)return user}
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).