WhoBuilt

Fetching Data

Jul 3, 2020· 47 min· 33K views·Watch on YouTube

Lee Robinson, developer and creator of Learn Next.js at leerob, explains data fetching in Next.js, from API routes and client-side libraries to GraphQL, Hasura, and Apollo Client.

Why to avoid a custom server

A custom server can help when an app needs custom request handling or authentication, and a standalone server may cost less for some workloads. But it gives up serverless API routes and automatic static optimization. Robinson estimates that about 95 percent of Next.js use cases can avoid a custom server.

Build API routes and fetch data with SWR

API routes are files under `pages` that handle requests and responses, with helpers for reading cookies, query parameters, and request bodies and returning JSON. Dynamic routes such as `/api/users/[id]` can return a specific user or query a database. For client-side data that can load after the page, SWR fetches and revalidates responses, helping keep pages statically served.

GraphQL and Hasura on Postgres

GraphQL lets clients request specific fields, including nested data, with queries for reading and mutations for changing data. Hasura builds a GraphQL API over Postgres and generates CRUD mutations from table models. Robinson demonstrates creating tables, querying and filtering rows, and joining related deals and locations in the Day Drink app.

Use Apollo Client in the Day Drink app

The Day Drink app uses Apollo Client to query deals by day and retrieve related users, active days, and locations. Apollo also supports mutations and a cache; after adding a deal, the app updates cached query results directly so the new deal appears without another database request. Robinson also shows fetching location and city data for display and possible map use.

Takeaways

  • Keep a custom server only when the app needs its request handling or has a clear cost reason; API routes preserve serverless deployment and static optimization.
  • Use client-side fetching for noncritical data when serving a static page matters; SWR can refresh data as it becomes stale.
  • GraphQL queries can limit responses to needed fields and retrieve related data together.
  • Hasura can generate CRUD mutations from Postgres models, reducing the work of building a GraphQL API.
  • Apollo’s cache can be updated after a mutation to show new data without refetching the same query.

Mentioned in this talk

Search inside this talk

What was claimed 7

Related talks