Summary

GraphQL shines over REST because it allows us to efficiently get the data we need in the shape we need with far less effort. The GitHub GraphQL Explorer is a great tool for getting comfortable with the syntax. There are two main types of requests we can make to a GraphQL server:

  • We can execute a query to read data
  • We can execute a mutation to write data

Queries allow us to specify the objects and fields we want in the response. We can rename them by using aliases. We can parameterize a query by defining variables. We can give variables types and specify whether each one is required or not with ! at the end. There are query features that we didn't cover in this chapter, such as conditionally including fields and the powerful paging capability. In summary, it's an extremely powerful query language!

Mutations share some of the same features as queries, such as being able to pass parameters into them. It's great how we get to control what data is included in the response as well.

GraphQL operates over HTTP with HTTP POST requests to a single URL. The HTTP body contains the query or mutation information. We can use an HTTP client to interact with a GraphQL server, but we'll probably be more productive with a library like Apollo that is built specifically to interact with GraphQL servers.

React Apollo is a set of React bits and pieces that work with the core Apollo library. It gives us nice Query and Mutation React components for including queries and mutations right in our JSX, making our code arguably easier to read. Before we can use these components, we need to set up our ApolloClient object with the URL to the GraphQL server and any credentials. We also need to include an ApolloProvider component high in our component tree, above all the components that need GraphQL data.

Caching is switched on out-of-the-box when we scaffold our project with apollo-boost. The Mutation component gives us update and refetchQueries props to manage cache updates.

All in all, GraphQL is a very productive way to interact with backends, and it works really nicely with React and TypeScript apps.

So, we've learned many different aspects of React and TypeScript in this book so far. One big topic that we haven't covered yet is how we can robustly test the apps we build. We'll cover this in the next chapter. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.148.187