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

3 Chrome Devtools Tips to Make Developing Vue Apps Easier

In this blog post, I want to share 3 Chrome DevTools tips I recently learned that will make your life easier when writing Vue apps. When we have objects with a lot of fields (and many rows) if you console.log it out, you have to dig deep within these objects to uncover the values you're looking for. However, Chrome provides a handy function console.table , which will nicely format our data into a pretty table! Did you know you can add color to your console.log ?? Try this out. Open up any website and open the dev tools. Then type: And you should see something that looks like this: ... cool, right!? How it works: You'll notice that the first argument to console.log is a string, as normal, but with a special %c , which is where the CSS will be placed. We pass the CSS as a string as the second argument. You can even load images this way -- if you use a background image. Try the following: ...and you should see something like this: How it works We're using a background url to within the CSS. Did you know that Chrome supports a top-level await keyword for async functions? It's super helpful. And here's what it looks like in our console: And if we wanted to inspect this product's ingredients? We can use console.table ! Hope this makes your day a little easier! And to learn more about developing Vue Apps, check out our book Fullstack Vue !

Thumbnail Image of Tutorial 3 Chrome Devtools Tips to Make Developing Vue Apps Easier

Using React Redux with TypeScript

In this article, we will learn how to use react-redux hooks with TypeScript to build a note taking app.Redux is an incredibly useful tool for centralised state management in React apps. However, introducing Redux into a React project can be a bit intimidating because it introduces a number of new concepts - state, actions, reducers, selectors, action creators etc., and adds a fair bit of boilerplate code. This has, however, changed for the better since the introduction of react-redux hooks such as useSelector and useDispatch . In this article, we will learn how to add Redux to a simple React TypeScript app, and how to use and manipulate application state. We will use create-react-app to generate a stock React app. We can generate a TypeScript-based app by specifying the template argument as below. We'll call our app react-redux-typescript . Once this is done, the next step is to add redux and react-redux to the project, like so: Since redux is written in TypeScript, we don't need to install any additional types for it. We do, however need to install the types for react-redux . We can then open the project in our code editor and start hacking! 🤓 We can remove the default layout generated by create-react-app in App.tsx and replace it with the following initial layout that includes an input for typing in a note. It will be useful to separate the note input into its own component for ease of use and modification later on. So we can create a new file NewNoteInput.tsx with the following layout. So our App.tsx will now look like this: Now, we'd like to know when the 'Add note' button is clicked, so that we can add a note. We can do so by defining a function prop for the NewNoteInput component, which gets called each time the 'Add note' button is clicked. The NewNoteInput component now takes an addNote function that takes a string input for a note. The component also maintains an internal state for the current note being typed. This value is updated on each change of the note input element. When the 'Add note' button is clicked, the onAddNoteClick function is invoked, which calls the addNote function passed in, and cleans up the internal state. It's important to note the types we've used here: We can then use the addNote prop in App.tsx to pass in a callback. For now we can use alert to make sure that it's working. eInput addNote={alert}/> We are now ready to introduce Redux into our app! The first step towards this is to create a reducer. Reducers are pure functions that are used to populate new values for any piece of state. A reducer takes two parameters - the previous state value, and an action that contains a payload that is used to a'er the state value. Let's create a notesReducer.ts file that contains this function. Here, we have defined an interface for NotesState which includes an array of notes that have been added. The initialState represents the state at the point when the app is loaded, where there are no notes saved yet. We have also defined a type for Action , which contains a type ADD_NOTE and a string payload which is the actual note to be added. We can now create a Redux store that manages the state of our application by using our notesReducer . We can create a store.ts file to hold this object. The final step to connect it all up, is to wrap our application in a react-redux Provider. In the app's index.tsx , we will import Provider from react-redux and wrap our app in it. The Provider takes a store prop to which we will pass the store we have created previously. Previously when building the layout in our App.tsx file, we used a placeholder to indicate the list of added notes. We'd now like to populate that list with real data, and for that we will need to access the state of our app. We can access this state using the useSelector hook from react-redux . A selector is a function that parses the state and gives back the required slice of it. In our case, we'd like the notes array from the state, so we can access it like so: The useSelector hook takes a function that receives the state as a parameter, and returns a specific part of it. It also accepts two type arguments: We then use the notes array to render a list of notes. We're now displaying live data from the state in our application. However, there is no data to display since we're not adding anything to the state store in the first place! We are still passing in alert as the addNote callback to NewNoteInput . Instead, we need to pass in a function that will dispatch an ADD_NOTE action which will trigger the notesReducer and add the note to the state. react-redux provides a useDispatch hook that gives us access to a function that can dispatch actions to our store. We can use it with our addNote callback to dispatch the ADD_NOTE action. In the onAddNote function, we have manually defined the ADD_NOTE action in the format expected by the notesReducer . This can, however, open up many possibilities for errors - we could make an unintentional typo, get one of the property names wrong, or assign the wrong values. react-redux offers a feature called Action Creators which helps avoid these errors. To make use of this feature, we can create a new file, say actions.ts , that will define our action creators. We can move the definition of the Action type into this file as well. This means that any component that calls the addNote function only needs to be concerned about the note itself, rather than all the other formatting around the actual action. We can now refactor App.tsx to use this action creator. And there we have it! We are now displaying the notes from our app state in the list, and adding to the list each time a new note is added. ✅ All the code from this article is at https://github.com/satansdeer/react-redux-typescript.

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

Handling File Fields using React Hook Form

In this article, we will learn how to handle file uploads using react-hook-form.react-hook-form is a great library that provides an easy way to build forms with React. It provides a number of hooks that simplify the process of defining and validating various types of form fields. In the following sections, we will learn how to define a file input, and use it to upload files to firebase. We will use create-react-app to generate a stock React app. We'll call our app react-hook-form-file-input . Once the app is ready, we can navigate into the folder and install react-hook-form . Let us define our form in the app.js file. We can remove all the default markup added by create-react-app , and add a form element which contains a file input and a submit button like so: We can now connect our form element to react-hook-form using the useForm hook. useForm returns an object containing a register function which, as the name suggests, connects a given element with react-hook-form . We need to pass the register function as a ref into each element we want to connect. Now that our file input has been registered, we can handle submissions by adding an onSubmit handler to the form. The useForm hook also returns a handleSubmit function with which we will wrap our onSubmit handler. The data parameter that is passed to onSubmit is an object whose keys are the names of the fields, and values are the values of the respective fields. In our case, data will have just one key - picture , whose value will be a FileList . When we fire up the app using yarn start , we will see this on screen. On choosing a file and clicking 'Submit', details about the uploaded file will be logged to the console. Now that we have learnt how to work with file inputs using react-hook-form , let us look at a slightly more advanced use case for uploading files to Firebase . You can find the code for the Firebase file upload example here . Clone the repo and run yarn to install the dependencies. You can set up your Firebase configuration in the .firebaserc and firebase.json files at the root of the project, and log into Firebase using the CLI . As we've seen earlier, we can install react-hook-form via yarn using: The App.js file contains a file input which uploads a file to Firebase. We can now switch it over to use react-hook-form like so: We have wrapped the input element with a form , given it a name and registered it with react-hook-form . We have also moved all the logic in the onChange event handler into our onSubmit handler which receives the data from react-hook-form . We can run the app using the yarn start command and it will look the same as earlier. Choosing a file and clicking 'Submit' will upload it to Firebase. We have now learnt how to work with file inputs using react-hook-form . ✅ The code used in this article is available at https://github.com/satansdeer/react-hook-form-file-input and https://github.com/satansdeer/firebase-file-upload .

Thumbnail Image of Tutorial Handling File Fields using React Hook Form

Getting Started with Jamstack

"Jamstack" is an architecture for web apps that promises to be faster and easier to create than the traditional client/server architecture. In this article, we'll take a dive into the Jamstack architecture to better understand how it works and the advantages it offers. We'll also build and deploy a very simple Jamstack app using Eleventy and deploy it to Netlify . You should be familiar with: For the practical part of this article, you'll need to have Node & NPM installed on your computer. The examples included assume a Linux-based system. Rather than serving pages from a web server, Jamstack sites are static pages served directly from a CDN which allows for greater speed and security. Interactivity and personalization can be provided by JavaScript, which can be used for HTTP connections to API services like cloud databases, payment gateways, content management, etc. Rather than having a backend web app serving dynamic pages by generating HTML on the fly, Jamstack apps consist of pre-rendered static pages. Since most developers wouldn't want to write their app in HTML, a static-site generator is usually employed. Since Jamstack sites consist only of static assets, this means the site can be served by a distributed file-serving network aka a Content Delivery Network (CDN). Without any web server to provide functionality, how can a Jamstack site be as dynamic as a traditional web app? For example, how can you personalize your site without a database with customer data to populate authenticated pages? Most dynamic functionality in a Jamstack app will be provided by JavaScript running in the user's browser. With the emergence of the single-page application app architecture provided by JavaScript frameworks like React, Angular, and Vue, frontend apps can simulate multi-page sites without the need for a web server. Recently, there here have sprung up many companies providing API-based services including cloud databases (e.g. Hasura , Fauna ), cloud computation (e.g. AWS Lambda ), identity management (e.g. Auth0 ), eCommerce (e.g. Snipcart ), payment processing (e.g. Stripe ) and so on. These API services can all be connected to static apps using AJAX requests during the app lifecycle, thereby greatly enhancing the possible feature set for a Jamstack app. While the idea of Jamstack apps has existed in one form or another for quite a while, Jamstack has only recently become a viable and attractive architecture as the evolution of the ecosystem permitted it. For example, without modern JavaScript frameworks and the emergence of API services, Jamstack apps would be severely lacking in functionality when compared to traditional apps. Let's look at some of the advantages Jamstack provides that make it an attractive option. Since a Jamstack app does not have a backend server, it can be quite cheap to host. This is because backend apps usually require a web server to be listening all the time for requests, whereas CDN file serving is done with a centralized web server that you won't have to pay as much for. Jamstack apps will often be faster, since CDN content is served at the network edge. This means that your static files may be served from data centers around the world that are physically closer to your users, reducing latency of requests. While a web server can also be distributed it will still likely be slower than an optimized CDN. Even more importantly, static files are computationally much easier to serve than rendering HTML on the fly, and therefore can be served significantly faster. Since there is no backend server, Jamstack apps can be more secure than traditional apps since there are much fewer exploitable public interfaces. This means that you, as the developer, don't need to be concerned about server security, authentication management, database exploits etc, which are all sources of vulnerability. Also, CDNs can provide DDoS mitigation since the content is distributed across a network, providing another way in which Jamstack can be more secure. It should be noted that Jamstack apps still have security vulnerabilities - just less than traditional apps. For example, your serverless functions and API calls to cloud services can still introduce security holes. Of course, Jamstack is not a silver bullet and it may not always be the superior solution. Getting rid of the web server definitely provides advantages, but there are downsides too. It might be argued that it's harder to develop Jamstack apps, especially for developers who are traditionally backend developers. Also, Jamstack can't take advantage of the enormous ecosystem of backend software that makes web development easier, including frameworks like WordPress, or Laravel. It's also worth noting that most of the advantages of Jamstack are accrued for apps with many users. If you're building an internal tool, like an admin dashboard, you won't get near as many advantages of Jamstack, and it may be wise to stick with a traditional web server solution. Now we're clear on what Jamstack apps are and why you might create one. The question now, is, how do you make them? The center-piece of a Jamstack app is usually the static-site generator. This is a framework that will turn your content into static files ready to be deployed. These can range from simply (e.g. Eleventy) to more complex (e.g. Next.js). On the simple end, the generator might be little more than a CLI tool that turns markdown into HTML. On the complex end, the generator may allow you to create a feature-rich single-page app to present your static content. Examples of static-site generators include Next.js, Gatsby, Nuxt.js, Eleventy, and Jekyll. As discussed, static sites are usually hosted on a CDN. While you could use a CDN service directly, like Cloudflare , or AWS S3, it's easier to use a static hosting provider like Netlify or Vercel . The advantage these services offer is that they're geared for Jamstack sites (indeed, the term "Jamstack" was coined by Mattias Billman, CEO of Netlify) and include many useful features that will help in deploying static sites. For example, both Netlify and Vercel provide a Git server that you can push to to trigger a build of your site, environment variable management, serverless functions, CI, and more. Let's see how to build a simple Jamstack site - a blog. To do this, we'll use the Eleventy static-site generator and deploy it to Netlify. To begin with, let's create a folder for our project and change into it. Let's now create a markdown file which will be used for the home page content: We'll then add some content to the file: One of the advantages of Eleventy is that it is very simple to use. In fact, with just one file we can create a build! We'll use npx (a CLI tool packaged with NPM that allows you to run a package without installing it) and call the Eleventy binary which will create a build: Eleventy will generate a file _site/index.html that looks like this: Of course, this is not a valid HTML page since it's missing document tags. So let's create a layout that Eleventy will use to render our markdown file with. The liquid templating language is one that Eleventy can read and provides a very simple way to provide layouts. Here's the content you should add to your layout file: Let's add some frontmatter to the top of the file to allow for some configuration. We'll add a layout property which tells Eleventy the layout template to use, as well as a title property. Run Eleventy again, and here's the updated content you'll see for _site/index.html: While very simple, this is a perfectly valid static site! Let's use Netlify to deploy this site. First, register for a free Netlify account at https://netlify.com . Then, go to https://app.netlify.com , and drag the _site folder generated by Eleventy into the browser window. Netlify will automatically create a new app and deploy the static files. You can then view your site at https://[your-site].netlify.app! In this article, you've learned about the Jamstack architecture and should now have an understanding of how it works and the advantages it offers. You've also built and deployed a very simple static blog using Eleventy and Netlify. If we connected an API service to this app, we'd have a bonafide Jamstack app. To continue your discovery of Jamstack, I recommend the following next steps:

Angular Universal is Server-Side-Rendered Angular

Did you know you can greatly improve the performance of your Angular apps with Angular Universal? It's pretty amazing in that you can boost the performance of an Angular app from a Lighthouse score from 66 to 95+ points -- with the right techniques. But what is this magic Angular Universal and how do we use it in our apps? Well it helps to look at the problem first. Single-page-apps (SPAs) have at least one big pitfall: they are rendered in the browser rather than on the server. When we render a "normal" Angular app - we first have to download the code and then run the app. To understand the problem in more detail, consider the browser's simplified workflow. The browser: As you can see, the moment when your Angular application is bootstrapped is at the very end of the workflow . That's why it takes so long to render the first contentful paint . SPAs have one more pitfall. Because content is rendered in the browser, the index.html file shipped to the end user has no content. What if your end-user is a web crawler? If you try to curl a basic Angular app, you'll notice that you don't get the full HTML of the first view of your app, but instead get the tiny HTML file that loads the code. This is less-than-ideal for many situations. This changes with Angular Universal. With Angular Universal you're able to render your Angular app on the server (!) . This means that the HTML that is shipped to your end-user is your rendered app - from the first request sent over. And what's great is, you can even make database calls or serve authenticated content with the right configuration. I'll teach you how. The basic idea is this: you use @angular/platform-server with @nguniversal/express-engine to render your Angular app in Node.js . Starting your adventure with Angular Universal is as simple as applying a single command using the Angular CLI. Navigate to your project root directory and type the following in the terminal: Angular CLI will install all the necessary dependencies for you and apply schematics (a set of instructions on how to adjust the project). After applying the schematics, you should see the summary output of what has been changed, added, or deleted in your project: The backbone of your project is the package.json file. Angular CLI has installed new dependencies there that are necessary to run Angular in the Node.js runtime environment: Another change is in the scripts section, where Angular has added dev:ssr , build:ssr , serve:ssr , and prerender . We'll talk more about these later. So if you peek inside the server.ts file that gets generated, it looks like this: Starting off, we import a few things, the important part being @nguniversal/express-engine which is, as you might guess, an engine for Express to render Angular apps. We also import AppServerModule which comes from our app . Continuing on, here's the meat of our server. I'll explain a few bits below: The key part above is that ngExpressEngine bootstraps the Angular framework using the AppServerModule object imported from src/main.server.ts . That's the entry point of the application and what's responsible for the bulk of the smarts. server.get('*.*') , is responsible for hosting all other assets that the browser will request (e.g. images). Finally we run the server like we would with a "normal" express application: With the code above, we're on our way to rendering a high-performance server-side Angular app. Amazing! If you're interested in learning more check out the course Mastering Angular Universal: Build Blazing-fast Server-Side-Rendered Angular App

Thumbnail Image of Tutorial Angular Universal is Server-Side-Rendered Angular