Latest Tutorials

Learn about the latest technologies from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

    Error Handling in GraphQL

    GraphQL servers are able to handle errors by default, both for syntax and validations errors. You've probably already seen this when using GraphiQL or any other playground to explore GraphQL APIs. But often the default way is not sufficient for more complex situations or to sophistically handle the errors from a frontend application. So let's dive into how to improve this. Error handling is described in the GraphQL specification and is part of the default structure of any GraphQL response. This response consists of 3 fields: The simplest type of error that you can get is when you in example try to use an operation that's not present in the schema of your GraphQL API. Suppose we have an API that serves as the backend for a music application. Using queries and mutations, you will be able to view tracks, add playlists, and save tracks to playlists that you've created. One of the operations for that API is a mutation to add a track to a playlists, which is called saveTrackToPlaylist . But suppose we make a mistake when spelling the mutation in the GraphQL playground. What would happen? The server will throw a default GraphQL error, as the misspelled mutation is not present in the schema: The response object has the previously mentioned error field and a message stating the error: Cannot query field \"saveTrrackToPlaylist\" on type \"Mutation\". Did you mean \"saveTrackToPlaylist\"? . As you can see GraphQL graciously prevents you in sending non-existing operations to the server. Similar errors are thrown when your operation variables or requested fields are incorrect. When you have an error that's not related to the GraphQL schema, you would have to throw an error from the resolvers of your GraphQL server. This can simpy be done by throwing an error from the resolver. This would looks something like this for the music application server: In the resolver an error is thrown when the playlist or track that you define for the saveTrackToPlaylist mutation are not present in the database. The error message will again be added to the errors field of the GraphQL response object. The snippet above has been truncated but the actual response in the GraphQL playground is a huge chunk of JSON, which makes it hard to get the important information from that response. Fortunately, the GraphQL specification allows you to add a field called extensions to the error object. To extend the error object, you can either throw a custom Error object or use predefined error methods available in Apollo Server. Apollo Server provides several predefined errors, such as AuthenticationError , ForbiddenError , and UserInputError , as well as the general ApolloError . These errors make it easier for you to debug and read errors from the GraphQL server. Handling errors this way works especially well when you're using Apollo to create your GraphQL server, but there are more declarative ways of returning errors to the client. One way of doing so is by adding errors as data. This approach has several advantages: To add errors to your data, you need to use the Union type (a.k.a. Result ) in your GraphQL schema. Also, the logic in the resolver is rewritten so that next to the result or error for the operation you also need to return a type for it. This allows you to send the previous mutation in the following way, which has different payload types based on the return of the resolver. The mutation saveTrackToPlaylist now has three different payloads depending on the result of the resolver. The payload SaveTrackSuccess returns the playlist and tracks details when the operation is successful, while the SaveTrackPlaylistError and SaveTrackError are retuned when an error occurs. More implementations for error handling in GraphQL and the full source code are available it the book Fullstack GraphQL .

    Thumbnail Image of Tutorial Error Handling in GraphQL

    Using GraphQL Code Generator For Type-Safe GraphQL Clients

    Using GraphQL together with TypeScript can have huge advantages, as you can use your GraphQL schema to create TypeScript type definitions and even code that fetches data from the GraphQL server. This is incredibly powerful. Why is that? Basically it means we can have TypeScript types that match our GraphQL types and operations. An important nuance is that TypeScript has a set of types and GraphQL has a set of types . It might take a minute to understand, but these are different things, as GraphQL and TypeScript have a similar type system with slightly different nuances. What exactly is what we will discover in this article! To generate TypeScript type definitions and code from GraphQL, we first need to have a schema. For this you'll use the Rick and Morty API that is publicly available, and based on the popular television show. When you open the GraphQL Playground for the Rick and Morty API you can use multiple operations like queries and mutations. Let's try this out, by pasting the query below in the Explorer: This will result in a JSON response that consists of all the characters in the show and their name and gender . Great! Using the Rick and Morty API as starting point we can now use this with TypeScript and autogenerate some code. To get this data from the GraphQL API into your application you need to fetch the data using the query. For this you could use a regular HTTP-request or any of the popular GraphQL clients. For this example we're using the library graphql-request that's very lightweight and requires just a few lines of code. After installing it from NPM, you can fetch data from the Rick and Mory API like this: But the data that you receive from the API doesn't have any type definitions that you can use in TypeScript. Instead of adding them manually, the library GraphQL Code Generator can be used. Generating the TypeScript type definitions and code can be done with GraphQL Code Generator is a CLI tool that generates TypeScript typings out of any GraphQL schema. Let's create an application to fetch the Github info using TypeScript code generated from the GraphQL schema. Installing GraphQL Code Generator can be done with npm or Yarn, but first you need to add graphql as a dependency. And @graphql-codegen/cli and related plugins as a dev dependency: You've now installed everything you need to generate the type definitions from the GraphQL API. But to use GraphQL Code Generator you need to add a configuration file called codegen.yaml that specifies the url to the GraphQL API and the plugins that must be used: After adding the configuration file you can run the command graphql-codegen from the command line, in the same directory as the configuration file was added. This will now create a new types.ts file containing all the TypeScript type definitions based on the schema of the Rick and Morty API. This means that you can use this to have a type for the data returned by graphql-request . In your query you requested the characters that are represented as a type called Characters : Pretty straightforward! Of course, there are many more features GraphQL Code Generator that you could use. In the book Fullstack GraphQL you can find more working examples, including a guide to generate GraphQL client code from your GraphQL schema.

    Thumbnail Image of Tutorial Using GraphQL Code Generator For Type-Safe GraphQL Clients

    I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

    This has been a really good investment!

    Advance your career with newline Pro.

    Only $30 per month for unlimited access to over 60+ books, guides and courses!

    Learn More

    How to Define Props in React + TypeScript App

    Props in React are like function arguments. They are passed in a component so it knows the data to work with. To define props create a new type where declare every prop that should be defined: The name for this type consists of 2 parts: It is now a good convention to name props types like this. To use a props type pass it as a type for components props: You also can use FunctionComponent and FC generic types for it: To define a props type with complex structures inside, it is better to decompose those structures in multiple different types. For example: You can use these types in component declaration as usual. You can declare optional props using ? : You can use an interface as well as a type for declaring props types: The difference between a type and an interface is in their extension. Let's say you want to extend ComponentProps with another field baz . In a case of a type you would write: In a case of an interface: On the contrary, an interface cannot extend a union type:

    Thumbnail Image of Tutorial How to Define Props in React + TypeScript App

    How to create a functional component using TypeScript

    Create a new file with a component name, for example, Message.tsx . It is important to use the .tsx extension for the component to work properly. Inside, create a functional component as you would in plain React: Then, create a MessageProps type to define props that this component will accept. Use it to type passed props inside of a component: The MessageProps type is used to declare what type the properties of this component support. This is similar to declaring types with prop-types but without any additional packages and the result of type checking is available at design time. You won't need to run the project to figure out that some types are not correctly passed. Also, you can use React's FunctionComponent generic type to avoid typing props themselves and shorten the declaration a bit: This generic type will help TypeScript to derive props types. Similar, you can use FC generic, which is the same as FunctionComponent but shorter: Those generics support children prop. So, you don't have to manually define it in your component props if you need it.

    How to Define Props with Children in React + TypeScript App

    There are multiple ways to define props with children. You can declare children prop on your props type and assign the ReactNode type to it: If children should be optional, you can mark it with the ? : However, this is not very convenient to declare this field by hand every time. The PropsWithChildren type encapsulates children declaration in itself : You can use this type as a generic : The FunctionComponent generic interface includes children declaration. It uses PropsWithChildren under the hood. You can pass your props as a type parameter into this generic when declaring props: Another type you can use is React.FC . This is a type-alias for FunctionComponent , so it is the same as the previous one just shorter. When you declare a class component you can extend React.Component type: Like FC , the Component type automatically includes the children prop as well.