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

A Complete Code Tutorial To Working With APIs In Flask

In this post, I want to show you how to quickly put together a complete REST API using Flask. As you might know, Flask is a perfect fit for the job! Our example creates a movies API but you can follow this for any API you want to create! Here's what we'll cover: An API needs a data source, a URL scheme, and request methods that clients use to access resources. To keep things simple and focused on the API, we skip setting up a database and use an in-memory array to hold our movies. This allows us to focus on the API request methods. We set up our API code in a new Python file called app.py . We import these Flask helpers : Our first API route handles listing all movies. Here is the code that does this. We use a @app.route decorator to set the request URL. Our response returns a JSON formatted collection with the movies from our data store. When using a database like MySQL or MongoDB, this is where you would integrate database calls to fetch movie data. Here is how you implement retrieving a single movie. In this method, we match the movie based on the id in the URL. If one is found, we send it back, using jsonify to format it as JSON. When creating a new movie, a REST client sends the new movie's attributes in a JSON payload. It might look as shown in the image. Here is the method in our app that takes this payload and creates new movies. In this method, we first check if the user supplied a title for the new movie . If not, we abort the request. Note the 400 error code. Otherwise, we create a new movie with the supplied title , plot , and other attributes. We save it in the movies data store and return a JSON result with the saved movie . Our method here is also the most complex in this example. That's because it has to handle multiple moving parts. Let's break it down. We match the movie to update based on the id in the URL. If no match is found, we abort the request. We do the same if the user has not supplied a title or plot , or if the user has not supplied any valid JSON . Otherwise, we update the movie with the attributes supplied in request.json . If an attribute is not supplied in the request , we recycle its old value and use that. We then save the updated movie in our data store. The API is almost complete! Here's the code that handles delete requests. We match the movie based on the id in the URL. If a match is not found, we abort the request. Else, we remove the movie from our data store. We then return a JSON with the result . That completes our movies API! For more on Flask, check out our course Fullstack Flask where we've focused on building a whole, master-level SaaS app end to end.

Thumbnail Image of Tutorial A Complete Code Tutorial To Working With APIs In Flask

Generate TypeScript Types from GraphQL

In this post, I want to explain something that tripped me up for a long time: how to generate TypeScript types from a GraphQL server. They are! In fact, you even have types for your queries , which is extra confusing. Let me try to clarify. So, in your GraphQL server you might expose a User object. User has fields like id , email , username , profileImageUrl etc. When your client consumes this API it is over HTTP -- but if we're using TypeScript, it would be nice to have TypeScript types that match the GraphQL types. So again, *and they both have their own, separate, types . This post shows you how to generate TypeScript types from your GraphQL server. And it's super handy because not only is your code type-checked, but your editor will also help you autocomplete. At first, you might try writing these types by hand, but this will just drive you crazy to maintain by hand as your app grows. However, in a large scale production application, there could be hundreds of GraphQL endpoints & types. Take a look at GitHub's v4 GraphQL API , no joke, there are almost 1,000 endpoints & types. Creating TypeScript definitions for those (by hand) would be a nightmare! Not only that, a change in the server means you will have to find and update your TypeScript definitions over and over again. Ew. Of course every GraphQL API already has types defined in the schema. Wouldn't be great if there is something that can translate GraphQL types into TypeScript automatically? As you've probably predicted, there is. Ladies & gentleman, let me introduce to you, Apollo CLI . The Apollo CLI is a robust command line interface that allows for a variety of different things such as schema validation, generate static types, and etc. And we'll use this tool to auto-generate TypeScript definitions from our GraphQL API. Here's how: To use the Apollo CLI, we can install it globally with the following command: There are two commands we are especially interested in: We'll set up both of these steps as two separate script commands in our application's package.json file. We'll label these scripts codegen:schema and codegen:generate . To download the schema, we'll need to run the apollo client:download-schema command and specify the options we would want. In our case, we'll specify the single minimum option we need - the endpoint and pass in the value of our local GraphQL endpoint ( http://localhost:9000/api ). We'll run the newly created codegen:schema script in our command line. After a brief period, we'll notice success messages that state Loading Apollo Project and Saving schema to schema.json . If we look at the root of our client/ directory, we'll notice a schema.json file be generated that represents our entire GraphQL schema! With the GraphQL schema available in our app, we can now look to generate the static types for the listings query and deleteListing mutation in our GraphQL API. This can be done with the Apollo CLI client:codegen command. We'll specify a few options as we set up the script. The first option we'll add is the --localSchemaFile option, which is used to specify the path to the schema file in our client/ directory. Since the schema.json file is in the root of our project, the value for the --localSchemaFile option will be schema.json . The second option we'll specify is the --includes option which is used to state the files that contain the GraphQL operations we'll want to generate static types for. In my case, all of my GraphQL requests live in TypeScript files within my src/ folder. There fore, I'll specify a value of src/**/*.tsx which entails looking through our entire src/ folder and for any files that have the .tsx file extension. The final option we'll specify is the —-target option, which is required and allows us to specify which code generator we'd like to use. swift , flow , scala are all different options but in our case we're interested in the typescript option. We'll have the above apollo command as part of the codegen:generate script command in our application. We can now run the newly created codegen:generate command in our terminal. Upon success, we'll see the Loading Apollo Project message followed by Generating query files with 'typescript' target - wrote 3 files . By default, the Apollo code generator creates static typings for the GraphQL documents it finds in __generated__/ folders. For example: If we take a look at one of these auto generated files, we can see TypeScript interfaces for the return data and input variables! In Tinyhouse, you'll get up to speed with this whole stack really quickly. We've organized the course so that you can skip around if you just want to learn a specific part, but we also build the whole production-ready app if you want to walk through step-by-step. Check out Tinyhouse: a Fullstack React Masterclass

Thumbnail Image of Tutorial Generate TypeScript Types from GraphQL

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

3D React: Create Minecraft (with physics!) in React

In this post, I'm going to show you how to build Minecraft in React . What? A 3D Game, in React?? Yes. It's been said that React is more of a mindset than a DOM library and I'm going to show you an example that is both surprising and beautiful: a voxel Minecraft clone - with 3D rendering - in React. Below I'm going to walk you through how to recreate the smash hit game Minecraft , but if you prefer to watch a video, Maksim - Fullstack React with TypeScript author -- gives a walkthrough tutorial here on Youtube . Here is the code repository . Clone it, run it, and play around to see how the code really works. Then go ahead and make your own React game! Minecraft is an open-ended game that allows the player to explore a procedurally-generated game world. The game allows the player to build structures from materials such as wood, stone, dirt, and ores. The player's character has to occasionally eat food to replenish their health bar. For the demo, these are the main features: This game uses React for rendering UI and controlling events. For graphics, it uses these libraries: The basic world in the game has a Three.js Scene with a mesh which has grass material. The grass is provided through a grass.jpg image file. Here is the code that creates the ground, contained in Ground/js . In this code, we create a Ground function component that renders a Three.js mesh with a grass texture. This creates a green view in our scene . The grass texture is repeated 240 times in each direction. The Player is defined in a function component in Player.js . Here's what it looks like: First, we import some libraries we'll use to implement the player: use-cannon for physics, react-three-fiber gives us the 3D rendering, and then a few of our own modules. Continuing on, here's the Player : There's a lot here! But the short version is that this code creates a ref to the player representation. It uses a custom usePlayerControls hook to allow the player to move (described below), and we update the camera to reflect the current view. Here's what it looks like: Amazing! The code that implements Player movement is contained in usePlayerControls.js . What's super-cool is that we can use keyup and keydown listeners in a custom hook. I don't have room to paste the whole thing, but it looks like this: You can find the full source file here . This code uses Hooks like useState to provide functionality for handling user key presses as well as making the Player move. We use common game control keys for movement as follows: For more on modern React patterns like custom Hooks, Testing, GraphQL and Redux, check out Fullstack React with TypeScript .

Thumbnail Image of Tutorial 3D React: Create Minecraft (with physics!) in React

What is Svelte.js and Why Should You Care? Svelte vs React vs Vue

Before React.js and Vue.js came along, building large, maintainable web applications was still pretty hard. JavaScript files were hard to organize and deploy to production, and manipulating the DOM was painful. React and Vue turned front end developers into productive rock-stars, but utilizing a Virtual DOM in the browser incurs performance penalties. What if we could know how things would change in an app at build time, rather than waiting until run time to do the work? Enter Svelte.js. Svelte.js has many similarities to React and Vue but offers benefits that improve performance while being easy to learn and truly reactive. So what is Svelte.js, how does it work, and how does it compare overall to React and Vue? Just like React and Vue, Svelte is a JavaScript framework offering a productive approach for making frontend interfaces easy to build. The biggest technical advantage of Svelte is that it does the bulk of its work during a compile step, which means high performance, browser-friendly JavaScript with small bundle sizes. While Svelte's build process is the framework's biggest innovation, it is also very easy to learn, has fantastic documentation, and a great developer experience. The cornerstone of both React and Vue is that they process page updates with a Virtual DOM, reducing computationally heavy operations on the real DOM. However, this has a downside - virtual DOM operations need to be made in addition to operations that will be made on the real DOM eventually, which means performance penalties and potentially unnecessary work. Svelte's compile step results in the browser doing less work, pre-converting your app into vanilla JavaScript with no Svelte shipping runtime, framework, or library and no layers of abstraction between the app and the browser. Svelte is known as the vanishing framework because it is not present after the build process. If you think about it, it makes a lot of sense for a JavaScript framework to optimize the build step. After all, it is a one time process that can run on a developer workstation or a Continuous Integration (CI) machine and optimize the code before the first user ever interacts with it. Other frameworks utilize additional libraries and complex third-party solutions to manage state. Despite the number of solutions, as applications grow larger, it becomes harder to keep track of what was stored where. Props are supported, however Svelte also offers an easy approach to manage state within the framework, using the context API and Svelte Stores to accomplish application-wide state management. Svelte.js is easy to learn and use, and is similar to frameworks like React and Vue in that it uses a component-based architecture. Svelte's syntax is very easy to learn, particularly if you are already proficient with HTML, JavaScript, or another framework. Users estimate that you can pick up Svelte basics in one day. Svelte is most similar to Vue in terms of syntax because it uses templates and single file components whereas React uses JSX, however, you can typically achieve the same results with fewer lines of code than a Vue file because Svelte requires very little boilerplate. In a Svelte project, .svelte files are used to define single-file components. Keeping components in single files (organized in directories) with all the logic in one place helps keep even big projects maintainable. A .svelte file consists of a <script> section and any HTML markup you wish to use. You may notice the lack of boiler-plate, which makes the code very readable even for someone who has never used the framework. Here's a sample .svelte file. Any variable declared is automatically reactive and can be used in the markup with single curly braces {varName} . Because Svelte compiles into optimized JS files instead of JS, HTML, and CSS, it's lightning-fast compared to other frameworks. User tests show Svelte is around 30% faster than other common frameworks. Similarly, Svelte compiles code into small, optimized bundles of JavaScript, so it takes up less memory than other frameworks. Because of the compile step, Svelte can pick only the required pieces of code to update the DOM, resulting in an output that's up to 10X smaller than other frameworks, and faster loading times. Svelte has all the features you need to build rich, interactive web apps. Here's a quick rundown of key features. With its outstanding performance, easy syntax, and innovative compiler system, Svelte is rapidly gaining popularity and is set to be in the top 3 frameworks in the future. To learn more about what Svelte is and its many advantages, you can read the Svelte introductory blog post from the framework's author Rich Harris. This article is just the tip of the iceberg when it comes to Svelte. You can learn more with lots of interactive examples at the official Svelte.js tutorial . If you want to go even further with Svelte, you can learn how to build a full-stack web application with Svelte, Express, and PostgreSQL in our new Fullstack Svelte Course!

Thumbnail Image of Tutorial What is Svelte.js and Why Should You Care? Svelte vs React vs Vue

Comparing Lifecycle Methods - React.js and Svelte

Modern applications involve many DOM manipulations. Components (and elements) are constantly being removed, added, updated, etc. to deliver incredible user experiences and/or to optimize performance. Sometimes, you may need to execute code when a component is added (such as automatically focusing an input field when a form is loaded like the G-Mail login page) or when a component is removed (such as removing all event listeners associated with that element to prevent memory leaks). Frameworks/libraries such as React.js and Svelte provide component lifecycle methods that allow developers to predictably execute code at these very moments/situations. Having such access into each stage a component undergoes provides more control over how and when the component should be rendered. Commonly, functions can be scheduled to be invoked when these events occur in the lifecycle of a component instance: Svelte offers four lifecycle methods: This is the order of phases for a cycle involving beforeUpdate and afterUpdate : Additionally, only one lifecycle method is ran during server-side rendering: Coincidentally, the lifecycle methods of Svelte and React.js are quite similar: Notice that all of these methods happen as soon as the component's data is updated (either new props are received or state has changed) and before any rendering occurs. As previously mentioned, beforeUpdate is also called after the props or state has been modified and before the DOM is updated. Essentially, beforeUpdate can be customized to perform the same duties as any of these three lifecycle methods. To explore these similarities in-depth and understand why lifecycle methods are important in the development of components, let's walkthrough two versions of a simple application (one version using React.js and another using Svelte) and observe these lifecycle methods. Open both demos side-by-side, and open the developer console for both. React Demo Svelte Demo The application is a simple form that asks the user if they have any allergies. If they do, then an input field asking the user to mention their allergies appears beneath the radio button group. The lifecycle methods are located in the <FormInput /> component, and each method will log a message to the console when it is executed. Note : In the React demo, you will notice two different versions of the <FormInput /> component: src/FormInput_Class.js and src/FormInput_Hooks.js . In this post, we will be using the src/FormInput_Class.js version of the component since the useEffect hook only encompasses the lifecycle methods componentDidMount , componentDidUpdate and componentWillUnmount . Feel free to use this version of the component. Answer "Yes" to the question by clicking the "Yes" option in the radio button group. The input field should appear beneath the radio button group, like so: Check the developer consoles. When a component is mounted in Svelte, it will call beforeUpdate before the initial onMount . Then, once the component has rendered, onMount is called, followed by afterUpdate . The additional beforeUpdate call is caused by the readonly this binding ( bind:this ) that references the input field ( inputElement ). When a component is mounted in React, it will call getDerivedStateFromProps before the initial mount (before the render method is called). Then, once the component has rendered, componentDidMount (the React equivalent of Svelte's onMount ) is called. Type the letter "a" into the input field. Check the developer consoles. When a component's state is changed in Svelte, it will call beforeUpdate , followed by afterUpdate . Notice that the "X" button that appears when the input contains text is not yet rendered into the DOM when beforeUpdate is called. Once beforeUpdate finishes, the DOM is updated with the new state, and then afterUpdate is executed and has access to this newly rendered "X" button. When a component's state is changed in React, it will call getDerivedStateFromProps (always called before the render method), followed by shouldComponentUpdate and getSnapshotBeforeUpdate . Notice that the "X" button is not yet rendered into the DOM when any of these methods are called (like beforeUpdate ). Once these methods finish, the render method is called, the DOM is updated with the new state, and then componentDidUpdate (the React equivalent of Svelte's afterUpdate ) is executed and has access to this newly rendered "X" button. Inside of the input field, clear it by pressing the "X" button on the right. Check the developer consoles. Basically, the same methods are called in the exact same order. The only difference here is that the "X" button has not yet been removed from the DOM when beforeUpdate (also getDerivedStateFromProps , shouldComponentUpdate and getSnapshotBeforeUpdate ) are called. Once the component re-renders and the "X" button is removed, afterUpdate (also componentDidUpdate ) recognize that this button is removed. Answer "No" to the question by clicking the "No" option in the radio button group. Check the developer consoles. When a component is unmounted ("destroyed") in Svelte, it will call onDestroy , followed by the unmount method returned from onMount . Since both methods are called just before the component is unmounted, the component (and its constituent elements) are still in the DOM when these methods are called. Once these methods finish, the component will no longer exist in the DOM. Essentially, both of these methods perform the same function, but onDestroy can run inside a server-side component unlike the unmount method returned from onMount . When a component is unmounted in React, it will call componentWillUnmount . This method, like onDestroy , is called just before the component is unmounted, so the component (and its constituent elements) are still in the DOM when it is called. Once this method finishes, the component will no longer exist in the DOM. Experiment! Apply these lifecycle methods in your Svelte applications! Build custom Svelte lifecycle methods using beforeUpdate , afterUpdate , onMount and onDestroy .

Thumbnail Image of Tutorial Comparing Lifecycle Methods - React.js and Svelte