Thanks to visit codestin.com
Credit goes to www.apollographql.com

5. Execute your first query


To use the generated operations in RocketReserverAPI, first create an instance of ApolloClient. This instance uses your generated code to make network calls to your server. The recommended approach is to use a single instance of this object throughout your codebase.

Create an ApolloClient

  1. Create a new Swift file named ApolloClient+Setup.swift.

  2. Now add the following code into the file:

Swift
ApolloClient+Setup.swift
1import Apollo
2import Foundation
3
4extension ApolloClient {
5    static let shared: ApolloClient = {
6        return ApolloClient(url: URL(string: "https://apollo-fullstack-tutorial.herokuapp.com/graphql")!)
7    }()
8}

Implement the query

To verify that your ApolloClient instance is communicating correctly with the server, go to LaunchListViewModel and add an init() method with the following code:

Swift
LaunchListViewModel.swift
1import Apollo
2import RocketReserverAPI
3
4...
5
6init() {
7    Task {
8        do {
9            let response = try await ApolloClient.shared.fetch(query: LaunchListQuery())
10            if let errors = response.errors {
11                print("Error fetching launches: \(errors)")
12            }
13            
14            print("GraphQL Response - \(response)")
15        } catch {
16            print("Failure! Error - \(error)")
17        }
18    }
19}

Test your query

Build and run your application. The web host might take a few seconds to spin up your GraphQL server if nobody's been using it recently, but once it's up, you should see a response that resembles the following:

Query console log output, beginning with 'Success! Result: GraphQLResult...'

This means the request was correctly executed and you now have a list of launch sites 🚀🚀🚀.

Remove the init() method. The next section explains how to use the ApolloClient.

Next, let's connect this data to your UI

Feedback

Edit on GitHub

Ask Community