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

How to Use useCallback Hook with TypeScript

The useCallback hook returns a memoized callback that only changes if one of the dependencies has changed. This helps us to avoid unwanted and unnecessary components re-renders. The basic syntax for the useCallback hook is: You don't need any additional typings since TypeScript knows that useCallback accepts a function and an array of dependencies. It is preferable to use eslint-plugin-react-hooks though, to ensure you don't miss any argument in the dependencies array but that's optional. Let's assume we have a login form component: And then we have 2 input components: The problem is that when we change an email React will re-render both inputs instead of only EmailInput . This is happening because handler functions are being created on every re-render of the LoginForm component. So, on each render there are new handler functions for the InputEmail and PasswordEmail component, that's why they re-render each time. Let's fix that! Now, when we change an email or a password only the corresponding input component re-renders.

How to Use fetch with TypeScript

The main problem with fetch function is that it isn't a generic function . This makes it harder to type response data without writing additional wrappers. We can create a wrapper-module to avoid this problem. Let's create a function request that will handle network requests: Now we can call this function as we would call fetch : Or, since it is an async function we can use await : Right now the request function doesn't handle errors. To solve that we have 2 options: There are no obligatory rules for this but Single Responsibility Principle tells us not to mix those concerns in a single function. However, we will take a look at both ways. The first one is to handle errors inside of the request function: We can use catch to handle unresolved promises. There is a catch though (no pun intended). The first issue we can solve making the function async and using try-catch : However, this doesn't solve the second issue with not knowing how to handle the error. We can handle some basic network errors (Page Not Found, Bad Request) but we cannot handle any business-logic errors. With async/await approach, we can handle errors outside of the request function: We can also pre-define some basic request-methods, like get and post : We will use them like this:

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 use urql authExchange to implement authentication in Next.js

In this article, we will learn how to use the urql authExchange to add authentication with a GraphQL API in a Next.js app.In the last article , we have learnt how to use urql to execute queries and mutations in a Next.js Server-Side Rendered app. In the following sections, we will recap those learnings and build on them to implement authentication using urql exchanges. urql is a lightweight, versatile and extensible GraphQL client for modern frontend apps, with support for React, Svelte, Vue and plain JavaScript. It was introduced as an alternative to existing GraphQL clients like Relay and Apollo . Every query or mutation in urql is modeled as an 'operation', and the system at any moment has a stream of operations issued by various parts of the app. Exchanges are pieces of middleware that transform the stream of operations into a stream of results. This is explained in more detail in the architecture documentation . Some of urql 's core features such as fetching data and caching are also handled via exchanges implemented by the urql team and provided by default. You can also create your own exchanges by implementing functions that conform to the rules defined here . Next.js requires Node to be pre-installed on your system. You can then scaffold a Next.js TypeScript app using the following command in your terminal/command prompt. Once you have a skeleton app set up, you can install the dependencies required for urql . graphql is a peer dependency of urql and provides the underlying GraphQL implementation. No additional type definitions are required since urql is written in TypeScript. next-urql provides the Next.js bindings for urql . react-is is a peer dependency of next-urql , required for react-ssr-prepass to walk the component tree and pre-fetch any data required for rendering. @urql/exchange-auth provides the authExchange that we will implement our API authentication with. Finally, jwt-decode will be used to read the token and determine expiration time. We will also use Material UI to quickly scaffold out a login/register component and one that renders user info. Let us install the required dependencies for Material UI. Let us use the withUrqlClient HOC to wrap our entire app in the urql context. This makes the urql client and hooks usable in the rest of our app. The first parameter to withUrqlClient is a function that returns a ClientOptions object. This can be used to pass configuration into the urql client instance, such as the API URL, custom fetch function, request policy and any additional middleware in the exchanges property. For this tutorial, we will use the Web Collections Demo API from Formidable. In this tutorial, we will build a simple app with two screens - a login/register screen where users will authenticate or sign up to the app, and a user info screen that displays information about the logged in user. We will use the following operations from the Web Collections Demo API: We will use the browser's local storage to persist tokens across page reloads. The authExchange is a piece of middleware for the urql client, which intends to facilitate the typical JSON Web Token (JWT) based authentication flow with a simple and flexible API. It is provided in the @urql/exchange-auth package. We can add the authExchange to the exchanges property when configuring our urql client. The authExchange itself takes four pieces of configuration: The signin , register and refreshCredentials mutations from our API return an object that has the following shape. Let us implement a small helper function that stores the auth state in the browser's local storage. We've added a check for window since we only want this code to run in the browser. When the user logs out, we'd like to clear the auth state from storage. We can now add a couple of convenience functions to fetch the token and refresh token. Let us start implementing the authExchange functions, beginning with getAuth - this function needs to handle a couple of different scenarios: The addAuthToOperation function receives two parameters - the first is the current authState , and the second is the operation that will be executed next. The second parameter is of type Operation and is urql's way of representing an item in the stream of GraphQL requests. Operations have a context that contains the fetch options, either as an object or as an initializer function. We will retrieve the options for the current operation like so. We'll then create a new operation which is basically a clone of the input operation, along with our required override - the addition of our access token to the Authorization header. So the entire implementation of the addAuthToOperation function will look like this: Our API uses the GraphQL error code extension to communicate errors. For the purposes of this tutorial, we will only consider UNAUTHORIZED errors. Token expiry is one of the scenarios when we know the API will error. We are able to determine this by decoding the JWT and reading the exp field which specifies the expiration time. Our API's access token specifies the expiration time as seconds since the Unix epoch. Let us add a buffer of 5 seconds to determine that the token is about to expire. Now, this would work if all of our queries and mutations required the access token to be provided. However, we have mutations such as login and register which do not require the token passed in. We will need to adapt our logic to account for these mutations, and this can be done using the passed in Operation object. The full implementation of the willAuthError function will be as follows. Now that we have implemented all the required functions, the final step is to configure the urql client with the authExchange . Let us create a factory function that receives the ssrExchange and returns a client configuration object. We'll use this on our app's homepage in the next section. Our home page will render the login form when unauthenticated, and a user profile when the user is logged in. We'll use our clientOptions factory function here to provide the urql client to our app. We'll use two mutations login and register from the API in this component. urql 's useMutation hook can be used to consume these mutations within a React component. The useMutation hook returns a tuple containing the current state of the operation, and a function that triggers it. We'll trigger our mutations on submission of the respective form. Here is the full implementation of the page. We'll use the me query from the API to retrieve the user's ID, name and creation time. We can then use urql 's useQuery hook to execute the query. Let us create a simple layout with material-ui components to display the profile data. This will also include a loading indicator and an alert to show any error messages. In this article, we have learnt how to implement JWT authentication with a GraphQL API using urql and @urql/exhange-auth with a Next.js app. We have understood how to apply authentication to queries and mutations, and built a simple app that allows login and registration. All the code used in this article is available on my GitHub .

Thumbnail Image of Tutorial How to use urql authExchange to implement authentication in Next.js

How to Consume a GraphQL API in Next.js with urql and next-urql

In this article, we will learn how to use urql to consume a GraphQL API in a Next.js SSR app.urql is a lightweight, versatile and extensible GraphQL client for modern frontend apps, with support for React, Svelte, Vue and plain JavaScript. It was introduced as an alternative to existing GraphQL clients like Relay and Apollo . These GraphQL clients are largely similar when it comes to setup and use. In the next section, we will see how they compare with each other on various parameters. All three GraphQL clients provide standard features such as queries, mutations, caching and subscriptions, while only differing slightly in implementation. urql 's defaults for configuration are slightly better than those for Apollo, and it has a lower entry barrier thanks to its thorough documentation and native support for features otherwise only available via third-party plugins. Additionally, urql has a powerful caching mechanism offers both normalized and document caching via the @urql/exchange-graphcache package. urql is built on the principle of having a lightweight core, extensible via middleware called exchanges. This makes it the smallest in bundle size as compared to the other options. A full, detailed comparison of the clients by different categories of features can be found on the urql website . Next.js is one of the most popular React-based frameworks, and urql has first class native support for it via the next-urql package. Apollo and Relay do not have official plugins with support for Next.js which means the implementation might change between releases of the framework, and any app that uses it will have to be constantly maintained to keep up. With next-urql , most of the boilerplate involved in setting up urql for Server-Side Rendering (SSR) with Next.js is already done for you. It provides convenience functions such as the withUrqlClient HOC which enables your SSR pages to pre-fetch data via GraphQL queries. Next.js requires Node to be pre-installed on your system. You can then scaffold a Next.js TypeScript app using the following command in your terminal/command prompt. Once you have a skeleton app set up, you can install the dependencies required for urql . graphql is a peer dependency of urql and provides the underlying GraphQL implementation. No additional type definitions are required since urql is written in TypeScript. next-urql provides the Next.js bindings for urql . react-is is a peer dependency of next-urql , required for react-ssr-prepass to walk the component tree and pre-fetch any data required for rendering. We can use the withUrqlClient HOC to wrap our entire app in the urql context. This makes the urql client and hooks usable in the rest of our app. The first parameter to withUrqlClient is a function that returns a ClientOptions object. This can be used to pass configuration into the urql client instance, such as the API URL, custom fetch function, request policy and any additional middleware in the exchanges property. For this tutorial, we will use the GitHub GraphQL API. This API requires you to authenticate using a personal access token. You can follow the steps described here to create one after logging in with your GitHub account. We can then configure our urql client to pass the token as part of the authorization header on each request to the API. Now that we have our urql client set up, let us look at how we can use it to connect to the GitHub API and fetch some data. We will build a simple component that will display a list of repositories, with each item showing a link to the repo, its name, star count and commit count. The component will look somewhat like this. To start, let us look at the GraphQL query that should be used. This query fetches the first 10 repositories for the current user (determined from the personal access token). For each repository, it includes the name, ID, URL, stargazer count and the number of commits to the main branch. There are various other fields that can be added to the query, as documented in the API reference . We can execute this query using the useQuery hook from urql . Since we're using TypeScript, let us model the API response with the correct expected types and use them as type parameters to useQuery . The response object returned by useQuery returns a number of useful items, out of which we will currently use the fetching flag which tells us whether or not the operation is still in progress, and the data property which contains the fetched data when available. Let us now add some simple UI to render the returned data. This Repositories component now fetches and renders a list of repositories with star and commit counts. So far, we've seen how to set up urql in a Next.js app and use it to query the GitHub GraphQL API. Let's now take it a step further and learn how to create mutations - these are API operations that can cause the data to change in the backend. For the purposes of this tutorial, we will implement the creation of an issue within a given GitHub repository. The GraphQL mutation to create an issue looks like this: This mutation takes three variables - the repository ID to create the issue in, the title and the body of the issue. On success, it returns an Issue object that can contain the number, title and body. So let us model the request variables and response, and create the mutation. The useMutation hook returns a tuple with two items - an object that exposes the current state of the mutation request, and a function that can be invoked with input variables to execute the actual mutation. Let us adapt our Repositories component to be able to call this mutation. We'll refactor and extract some of the code into an individual Repository component along the way. This is what the refactored Repositories component will look like. All the GraphQL types have been moved to a separate types module. And the individual Repository component now renders the list item, along with a button that invokes the createIssue mutation when clicked. Clicking the button creates an issue with a sample fixed title and body in the corresponding repo. Every query or mutation in urql is modeled as an 'operation', and the system at any moment has a stream of operations issued by various parts of the app. Exchanges are pieces of middleware that transform the stream of operations into a stream of results. This is explained in more detail in the architecture documentation . Some of urql 's core features such as fetching data and caching are also handled via exchanges implemented by the urql team and provided by default. You can also create your own exchanges by implementing functions that conform to the rules defined here . Server-Side Rendered apps need to be set up to fetch data on the server-side and send it down to the client for hydration.  urql  supports this via the ssrExchange . The SSR exchange has two functions - it gathers all the data as it is being fetched server-side, and using the serialized data on the client side to rehydrate the app without a refetch. When using next-urql , most of the boilerplate involved in instantiating the ssrExchange is already done for you. So if your client does not use any other exchanges, you do not explicitly need to instantiate the ssrExchange when creating the client. To enable SSR, you simply need to set the ssr flag in the second argument to the client configuration function. If you do want to add other exchanges to your client, they can be specified in an exchanges property returned by the configuration function. This function also gets the instance of the ssrExchange passed into it when called. Enabling SSR when wrapping the top level App component in withUrqlClient disables Next's ' Automatic Static Optimization ' which allows for hybrid apps with both server-side rendered and statically generated pages. If this is required in your app, you can wrap individual page components with withUrqlClient as required. When applying withUrqlClient to specific pages, we can also use getStaticProps or getServerSideProps to pre-fetch the data and populate the urql cache. This will render the page as a static page, further optimizing performance and allowing us to perform other operations in these functions. Let us adapt our app to use server-side rendering with getServerSideProps for our repositories component. We will add getServerSideProps to our Home page component, as this function can only be exported from page components. The getServerSideProps function gets called when the page is being rendered server-side. It will populate the cache so that the subsequent render of the Repositories component will hydrate it from cache when useQuery is called. In this article, we have learnt how to set up urql with a Next.js app and perform queries and mutations against the GitHub GraphQL API. Further, we have also learnt about the architecture of urql and how Exchanges work. We have used next-urql to implement server side rendering with pre-fetching of queries using the urql client and cache. In a subsequent tutorial, we will learn how to use urql exchanges for authentication and caching. All the code used in this article is available on my GitHub .

Thumbnail Image of Tutorial How to Consume a GraphQL API in Next.js with urql and next-urql

Release Management with ASP.Net Core and GitHub Actions

In this article, we will learn how to set up automated release creation for an ASP.Net Core project with GitHub ActionsRelease management can be a complicated beast at the best of times, and is notoriously hard to get right. Previously, shell scripts and batch files used to be the most common tools used for automation, and countless hours were spent trying to get them working as expected. This has changed in recent times, with platforms such as GitHub Actions providing a much simpler way of automating tasks and managing releases. In the last article , we have seen how GitHub Actions can be used to set up a pipeline for Continuous Integration (CI). In the following sections, we will build on that, and add a workflow that publishes release artifacts when new code is merged to the main branch. For the purposes of this tutorial, we will use a simple .NET Core console application. This can be created via the following command using the .NET CLI which is installed along with the SDK. We will use the GitHub repository that we created in the previous article, which already contains a GitHub Actions CI workflow that builds and runs unit tests on pushes to main and pull request branches. A tag is a label that can be applied to any commit in your repository for later identification. Tags are typically used to mark commits for releases. You can create a tag using the following commands in your terminal/command line. Tag names can be any arbitrary string, but are usually version numbers like v1.0.0 or v.1.1.2-beta5. When a tag has been published, it will appear in the 'Tags' section in your repository. You can then use the created tag to create a GitHub release - each release has a title, short description and attachments such as release notes, source code and built artifacts. In the next step, we will learn how to build our project and associate the built app code artifacts with the just-created release. Let us now create a release.yml file in the .github/workflows directory alongside the ci.yml workflow we have defined previously. We will use the release published event to trigger our workflow. This means our workflow will get triggered when a new release is published using the mechanism from the previous step. Let us now understand what this workflow does: We can now create a release using the steps described earlier. Let us first tag the last commit in our repo. I'll call the tag v1.0 . The tag will now appear in the 'Tags' section, and we can create a release from it. The release notes can be automatically populated based on the commits since the last tag. Once we hit publish, a release gets created on the 'Releases' page. Note that this only has the source code, and not the built artifacts from the tagged commit. Publishing the release also triggers our new workflow. When the workflow has finished, the built ZIP file and tarball are added to the release assets, and we have successfully released v1.0 of our app! 🎉 In this tutorial, we have learnt how to create and automate tasks around releases for an ASP.Net Core project using GitHub Actions. We built on concepts we learnt in the previous tutorial on CI with GitHub Actions . If you find yourself stuck at any point during the tutorial, you can view all the source code on my GitHub here . More detail on all the events that can be used to trigger GitHub Actions workflows can be found in the GitHub docs .

Thumbnail Image of Tutorial Release Management with ASP.Net Core and GitHub Actions