Skip to content

03: Fetch data

Let's fetch some real data for our shop.

Add GraphQL API route

SOFA uses GraphQL for data fetching which greatly simplifies frontend work – the React code sends a single query and gets a JSON back, without having to worry about dozens of REST API endpoints and combining their results into the structure that the frontend needs. All that is catered for by the GraphQL layer.

As the first step, add pages/api/graphql.ts with this code in it:

// TODO

Next, add a GraphQL schema and a set of resolvers to your project:

[TODO how do we do this?]

At this point, you can visit http://localhost:3000/api/graphql in your browser and see the GraphQL playground:

🖼 TODO

Try issuing this simple query:

# TODO

You should get a JSON back:

🖼 TODO

Fetch products

Let's fetch top-selling products for the homepage. Update your index.js component like this:

// TODO code with plain `fetch`

You should see this:

🖼 TODO

Add Apollo Client

Though plain fetch works, Apollo Client is an advanced GraphQL client that we recommend in real-world SOFA projects.

First, install Apollo Client:

# TODO

Then add it to the Next.js app:

[TODO withApollo.tsx, apolloClient.ts etc.]

Now you can upgrade your code from plain fetch like this:

// TODO index.js to use Apollo Client instead of fetch

Bonus: strongly-typed queries

One of the beautiful things about the GraphQL + TypeScript combo is that the IDE knows, at compile time, which fields the responses contain and their types. Let's demonstrate such setup:

TODO:

  1. Create queries.ts
  2. Add graphql-code-generator & scripts to generate TS interfaces
  3. Use strongly-typed queries in index.tsx (we'll switch to TS now)