<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Isaac Okoro on Medium]]></title>
        <description><![CDATA[Stories by Isaac Okoro on Medium]]></description>
        <link>https://medium.com/@officialisaacjunior?source=rss-537a53a5b2d4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4oiep0sImCuL9bd0</url>
            <title>Stories by Isaac Okoro on Medium</title>
            <link>https://medium.com/@officialisaacjunior?source=rss-537a53a5b2d4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 06:07:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@officialisaacjunior/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Improving code quality in Typescript with compiler options — Part 2]]></title>
            <link>https://medium.com/stackanatomy/improving-code-quality-in-typescript-with-compiler-options-part-2-5cc7cb258015?source=rss-537a53a5b2d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cc7cb258015</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Isaac Okoro]]></dc:creator>
            <pubDate>Wed, 03 Aug 2022 22:38:12 GMT</pubDate>
            <atom:updated>2022-08-03T22:38:12.681Z</atom:updated>
            <content:encoded><![CDATA[<h3>Improving code quality in Typescript with compiler options — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/0*T_BCuXha1MxbWThj.png" /></figure><p>Switching from JavaScript to Typescript is a huge improvement in any codebase. The switch can be made even better and improved by going beyond the default typescript features, making our codebase far more secure. To accomplish this, we will need to include some Typescript compiler options. Compiler options are properties in the tsconfig.json file that can be enabled and disabled to improve our Typescript experience. It is important to note that as Typescript evolves, new flags will be created; therefore, it is recommended that you review the <a href="https://www.typescriptlang.org/tsconfig">typescript documentation</a> and see if any new flags may be of interest to you at the time of reading this.</p><p>This article is part 2 of <a href="https://blog.openreplay.com/improving-code-quality-in-typescript-with-compiler-options">Improving Typescript code quality with compiler options</a>. Here we will cover more options in the tsconfig.json file and how to improve code quality with the strictPropertyInitialization, useUnknownInCatchVariables, strictFunctionTypes, allowUnusedLabels, allowUnreachableCode, noPropertyAccessFromIndexSignature, exactOptionalPropertyType, and forceConsistentCasingInFileNames options.</p><h3>The tsconfig.json file</h3><p>All compiler options are saved in the tsconfig.json file, generated by running tsc --init in our project root terminal. In this post, we will add more commonly used compiler options to the tsconfig.json file and demonstrate the new functionality they introduce to our code. We will add the following compiler options to improve code quality:</p><pre>&quot;compilerOptions&quot;: {<br>    &quot;module&quot;: &quot;system&quot;,<br>    &quot;strictPropertyInitialization&quot;: true,<br>    &quot;useUnknownInCatchVariables&quot;: true,<br>    &quot;strictFunctionTypes&quot;: true,<br>    &quot;allowUnusedLabels&quot;: false,<br>    &quot;allowUnreachableCode&quot;: false,<br>    &quot;noPropertyAccessFromIndexSignature&quot;: true,<br>    &quot;exactOptionalPropertyType&quot;: true,<br>    &quot;forceConsistentCasingInFileNames&quot;: true,<br>    &quot;target&quot;: &quot;es5&quot;,<br>    &quot;module&quot;: &quot;commonjs&quot;,<br>    &quot;rootDir&quot;: &quot;.&quot;,<br>    &quot;outDir&quot;: &quot;../dist/&quot;,<br>    &quot;sourceMap&quot;: true<br>}</pre><h3>strictPropertyInitialization</h3><p>When set to true, this compiler option ensures we initialize all class properties inside a constructor.</p><pre>class User{<br>    name: string;<br>    age: number;<br>    occupation: string | undefined;<br>    <br>    constructor(name: string) {<br>        this.name = name;<br>    }<br>}</pre><p>We have a User class in the code block above, and the constructor() method is where we initialize the properties of its instance. JavaScript automatically calls the constructor() method when we instantiate a class object. Typescript requires us to either initialize the properties we defined or specify a type of undefined. Hence when we compile the above code, we get the error shown below:</p><pre>error TS2564: Property &#39;age&#39; has no initializer and is not definitely assigned in the constructor.</pre><p>Undefined variables in our code cannot be ignored with this option.</p><h3>useUnknownInCatchVariables</h3><p>In Javascript, we can throw an error and catch it in a catch clause. Often, this will be an instance of error and is set to any by default. When the useUnknownInCatchVariable compiler option is set to true, it implicitly sets any variable in a catch clause to unknown instead of any. Consider the example below:</p><pre>try {<br>    // random code...<br>     throw &#39;myException&#39;; <br>}<br>catch (err) {<br>    console.error(err.message); <br>}</pre><p>When we compile the above code, with useUnknownInCatchVariables set to true, it changes our error to an unknown type. Hence we get the error below from the terminal.</p><pre>error TS2571: Object is of type &#39;unknown&#39;.</pre><p>This error is produced because the error was set to unknown by Typescript. To fix this error, we can:</p><ul><li>Narrow the error from unknown to an instance of Error.</li></ul><pre>try {<br>  // random code...<br>   throw &#39;myException&#39;; <br>}<br>catch (err) { // err: unknown<br>  if (err instanceof Error) {<br>    console.error(err.message);<br> }<br>}</pre><ul><li>Use a <a href="https://www.typescriptlang.org/docs/handbook/2/narrowing.html">type guard</a></li></ul><pre>try {<br>  // random code...<br>  throw &quot;myException&quot;;<br>} catch (err) {<br>  // Use the type guard<br>  // error is now narrowed to definitely be a string<br>  if (typeof err === &quot;string&quot;) {<br>    console.error(err);<br>  }<br>}</pre><p>With the help of our if check, Typescript recognizes that typeof err === &quot;string&quot; is a special form of code where we explicitly state and describe types. This is referred to as <a href="https://www.typescriptlang.org/docs/handbook/2/narrowing.html">type guard</a>.</p><h3>strictFunctionTypes</h3><p>When strictFunctionTypes is true, function parameters are checked more thoroughly. Typescript parameters are bivariant by default, implying that they can be both covariant and contravariant. Variance is a way to gain insight into subtyping relationships. When the parameter is covariance, we can assign a specific type to a broader type (e.g., assign a subtype to a supertype). Contravariance is the inverse; here, we can assign a broader type to a specific type (e.g., assigning a supertype to a subtype). We have covariance and contravariance in bivariance. To learn more about variance, click <a href="https://www.stephanboyer.com/post/132/what-are-covariance-and-contravariance">here</a>.</p><pre>//strictFunctionTypes: false</pre><pre>interface Animal {<br>  name: string;<br>}</pre><pre>interface Dog extends Animal {<br>  breeds: Array&lt;string&gt;;<br>}</pre><pre>let getDogName = (dog: Dog) =&gt; dog.name;<br>let getAnimalName = (animal: Animal) =&gt; animal.name;</pre><pre>getDogName = getAnimalName;  // Okay<br>getAnimalName = getDogName;  // Okay</pre><p>The above code runs without error, and parameters are compared bivariantly by default. The method of the supertype getAnimalName and subtype getDogName can be assigned to each other. Typescript’s parameters are compared contravariantly if strictFunctionTypes is set to true</p><pre>//strictFunctionTypes : true</pre><pre>interface Animal {<br>  name: string;<br>}</pre><pre>interface Dog extends Animal {<br>  breeds: Array&lt;string&gt;;<br>}</pre><pre>let getDogName = (dog: Dog) =&gt; dog.name;<br>let getAnimalName = (animal: Animal) =&gt; animal.name;</pre><pre>getDogName = getAnimalName; // Okay<br>getAnimalName = getDogName; // Error</pre><p>When the code block above is run, we get an error:</p><pre>Type &#39;(dog: Dog) =&gt; string&#39; is not assignable to type &#39;(animal: Animal) =&gt; string&#39;.<br>Types of parameters &#39;dog&#39; and &#39;animal&#39; are incompatible.<br>Property &#39;breeds&#39; is missing in type &#39;Animal&#39; but required in type &#39;Dog&#39;.</pre><p>Here, getAnimalName is a broader function than getDogName. As a result, the supertype cannot be assigned to the subtype in this case. However, a subtype can be assigned to a supertype. Most of the time, function parameters should be contravariant, not bivariant. If we enable this typescript option, Typescript will not treat function parameters as bivariant.</p><h3>Open Source Session Replay</h3><p><a href="https://github.com/openreplay/openreplay"><em>OpenReplay</em></a><em> is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*h-iUrU2tvjbK_6kb.png" /></figure><p><em>Start enjoying your debugging experience — </em><a href="https://github.com/openreplay/openreplay"><em>start using OpenReplay for free</em></a><em>.</em></p><h3>allowUnusedLabels</h3><p>A <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label">label statement</a> in JavaScript is used to prefix a label as an identifier. Label statements in JavaScript are similar to checkpoints in our code. Because the label keyword is not a reserved keyword in JavaScript, we can represent it with any string that is not a reserved word and is followed by a colon :. The syntax for declaring a label is similar to the syntax for declaring an object in JavaScript. Most developers make the error of declaring labels instead of objects. To avoid this, Typescript provides us with the allowUnusedLabels option, which, when set to false, causes Typescript to throw an error highlighting any unused labels in our code.</p><pre>const isUserAgeValid = (age: number) =&gt; {<br>  if (age &gt; 18) {<br>    curfew: true; //-- COMPILER ERROR - Unused label<br>  }<br>};</pre><p>In the code above, curfew is a label. The following error will be raised when the code block is compiled:</p><pre>error TS7028: Unused label</pre><h3>allowUnreachableCode</h3><p>UnReachable code will never be executed, such as a code that follows a return statement. When this compiler option is set to true, unreachable codes are ignored. In contrast, TypeScript verifies our code paths when allowUnreachableCode is set to false, ensuring that all codes can be accessed and used. When set to true, an error is thrown if any unreachable code is detected.</p><pre>const randomNum = (n: number): boolean =&gt; {<br>  if (n &gt; 5) {<br>    return true;<br>  } else {<br>    return false;<br>  }</pre><pre>return true;<br>};</pre><p>If a code is proven to be unreachable, Typescript will display this warning:</p><pre>error TS7027: Unreachable code detected.</pre><h3>noPropertyAccessFromIndexSignature</h3><p>When this compiler option is set to true, it requires us to access unknown properties using [] bracket notation and .dot notation to access defined properties. This promotes consistency because property accessed with dot notation always indicates existing property. (obj.key) syntax While we use the [] bracket notation if the property does not exist. obj[&quot;key&quot;].</p><pre>interface HorseRace {<br> // defined properties<br> breed: &quot;Shetland&quot; | &quot;Hackney&quot; | &quot;Standardbred&quot;;<br> speed: &quot;fast&quot; | &quot;slow&quot;;</pre><pre>//index signature for properties yet to be defined<br> [key: string]: string;<br>}</pre><pre>declare const pick: HorseRace;</pre><pre>pick.breed;<br>pick.speed;<br>pick.ownerName;</pre><p>In the above example, we defined an interface HorseRace and gave it some properties such as breed, speed, and an index signature (for unknown properties). We get this error when we compile the code above.</p><pre>error TS4111: Property &#39;ownerName&#39; comes from an index signature, so it must be accessed with [&#39;ownerName&#39;].</pre><p>To correct this error, use bracket notation when calling the property ownerName.</p><pre>pick.breed;<br>pick.speed;<br>pick[&quot;ownerName&quot;]</pre><h3>exactOptionalPropertyType</h3><p>By default, Typescript ignores whether a property is set to “undefined” because it wasn’t defined or because we set it that way.</p><pre>//exactOptionalPropertyTypes = false</pre><pre>interface Test {<br>  property?: string;<br>}</pre><pre>const test1: Test = {};<br>console.log(&quot;property&quot; in test1); //=&gt; false</pre><pre>const test2: Test = { property: undefined };<br>console.log(&quot;property&quot; in test2);</pre><p>The above code block would execute without error, logging false and true values. In test1, we’re checking to see if property was defined; if it wasn’t, it logs a false. In test2, the value true is logged because we defined property and set property to undefined. Next, let’s set the exactOptionalPropertyTypes option to true.</p><pre>//exactOptionalPropertyTypes = true</pre><pre>interface Test {<br>  property?: string;<br>}</pre><pre>const test1: Test = {};<br>console.log(&quot;property&quot; in test1); // false</pre><pre>const test2: Test = { property: undefined };<br>console.log(&quot;property&quot; in test2);  // true</pre><p>When the above code block is compiled, the following error will be logged:</p><pre>error TS2375: Type &#39;{ property: undefined; }&#39; is not assignable to type &#39;Test&#39; with &#39;exactOptionalPropertyTypes: true&#39;. Consider adding &#39;undefined&#39; to the types of the target&#39;s properties. Types of property &#39;property&#39; are incompatible. Type &#39;undefined&#39; is not assignable to type &#39;string&#39;.</pre><p>What happened here is that Typescript refused to let us define a property of undefined. If property is not explicitly annotated to a type of undefined first. To solve this, we can annotate the property with the type undefined.</p><pre>//exactOptionalPropertyTypes = true</pre><pre>interface Test {<br>  property?: string | undefined;<br>}</pre><pre>const test1: Test = {};<br>console.log(&quot;property&quot; in test1); //false</pre><pre>const test2: Test = { property: undefined };<br>console.log(&quot;property&quot; in test2);  //true</pre><p>Our code runs smoothly again, logging false and true values. Typescript becomes aware of these two different ways of having an undefined property when exactOptionalPropertyTypes is enabled. It also ensures that if we want to explicitly define a property as undefined, it must first be annotated with the type undefined.</p><h3>forceConsistentCasingInFileNames</h3><p>This is a highly recommended compiler option among teams, and it encourages team members to use best practices and to be consistent. When this option is set to false, the case sensitivity rules of the operating system (OS) on which Typescript is running are followed. It could be either case sensitive (the operating system distinguishes between lowercase and uppercase characters in file names) or case insensitive (the operating system does not distinguish between character cases). When forceConsistentCasingInFileNames option is set to true, Typescript will raise an error If we try to import a file with a name casing that differs from the file’s name casing on the disk.</p><pre>// StringValidator.ts</pre><pre>export interface StringValidator {<br>  isAcceptable(s: string): boolean;<br>}</pre><pre>// ZipCodeValidator.ts<br>import { StringValidator } from &quot;./stringValidator&quot;;<br>export const numberRegexp = /^[0-9]+$/;<br>export class ZipCodeValidator implements StringValidator {<br>  isAcceptable(s: string) {<br>    return s.length === 5 &amp;&amp; numberRegexp.test(s);<br>  }<br>}</pre><p>Without considering the file’s name case, we import the StringValidator file in the code above. If forceConsistentCasingInFileNames option is set to true, an error will be raised:</p><pre>error TS1149: File name &#39;C:/Users/acer/Desktop/workBase/writing/Typescript/tsc/stringValidator.ts&#39; differs from already included file name &#39;C:/Users/acer/Desktop/workBase/writing/Typescript/tsc/StringValidator.ts&#39; only in casing.</pre><p>To solve this, use the exact character case for your file’s name when importing.</p><h3>Conclusion</h3><p>This article took a long look at some compiler options, the errors they generate, how to solve them and how to improve code quality by using them. Many other compiler options that can help with code quality can be found <a href="https://www.typescriptlang.org/tsconfig">here</a>.</p><p><em>This article was originally published at </em><a href="https://blog.openreplay.com/improving-code-quality-in-typescript-with-compiler-options-part-2"><em>blog.openreplay.com</em></a><em> on July 27th, 2022</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cc7cb258015" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stackanatomy/improving-code-quality-in-typescript-with-compiler-options-part-2-5cc7cb258015">Improving code quality in Typescript with compiler options — Part 2</a> was originally published in <a href="https://medium.com/stackanatomy">StackAnatomy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2D sketches with React and the Canvas API]]></title>
            <link>https://medium.com/stackanatomy/2d-sketches-with-react-and-the-canvas-api-710e8991771b?source=rss-537a53a5b2d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/710e8991771b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html-canvas]]></category>
            <dc:creator><![CDATA[Isaac Okoro]]></dc:creator>
            <pubDate>Fri, 03 Jun 2022 18:31:08 GMT</pubDate>
            <atom:updated>2022-06-17T00:01:09.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*LVH8grxEg0AtywqjR-5exA.jpeg" /></figure><p>The Canvas API is a built-in HTML5 API for building and effectively drawing shapes to the screen. The following definition comes from the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API">MDN web docs</a>: <em>The **Canvas API</em>* allows drawing graphics via Javascript and the HTML &lt;canvas&gt; element. We can use it for animation, game graphics, data visualization, photo manipulation, and real-time video processing.*</p><p>The Canvas API is primarily used to render 2D graphics to the screen. To render 3D graphics, the <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API">WebGL API</a> should be used, but we’ll focus on 2D work here. The WebGL API can also render 2D graphics because it uses the canvas element.</p><p>This tutorial will cover the creation of the following:</p><ul><li>A simple animation</li><li>A blank canvas where we can draw shapes and graphics</li></ul><h3>Properties and methods available in the Canvas API</h3><p>Some properties and methods are available in the Canvas API, and this section will cover them. The difference between the properties and methods is that the properties set or return a particular color or pattern used in the drawings. In contrast, the methods create the designs used by the properties in the drawing. Some properties and methods include:</p><ul><li>fillStyle: This property specifies the color or pattern used in the drawing.</li><li>font: This property specifies the font property for text content</li><li>strokeStyle: This property specifies the color used for the stroke.</li><li>createLinearGradient(): This method creates a linear gradient that can be used on the canvas.</li><li>rect(): This method creates a rectangle on the canvas.</li><li>fillRect(): This method draws a filled rectangle.</li><li>stroke(): This method draws the path you define.</li></ul><p>You can read more about the methods and properties available to the canvas API <a href="https://www.w3schools.com/tags/ref_canvas.asp">here</a>. The complete code for this article can be found <a href="https://github.com/IsaacThaJunior/react-and-canvas-api">here</a>.</p><h3>Creating a simple animation</h3><p>Navigate to the folder of your choice and run the following command to create a new React application.</p><pre>yarn create react-app &lt;NAME OF YOUR CHOICE&gt;</pre><p>You can clean up the file structure by deleting unnecessary files in the src folder. Create an Animation.jsx file, which will hold the code for the animation. Copy and paste the code below into the file.</p><pre>// Animation.jsx<br>import React, { useRef } from &#39;react&#39;<br><br>const Animation =() =&gt; {<br><br>  const canvasRef = useRef(null)<br>  const draw = (ctx, frameCount) =&gt; {<br>    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);<br>    ctx.fillStyle = &#39;blue&#39;;<br>    ctx.beginPath();<br>    ctx.arc(170, 50, 30 * Math.sin(frameCount * 0.05) ** 2, 0, 2 * Math.PI);<br>    ctx.fill();<br>  };<br><br>  return &lt;canvas style={{ width: &#39;700px&#39; }} ref={canvasRef} /&gt;;<br>}<br><br>export default Animation</pre><p>We returned a canvas element in the code block above and then imported the useRef hook from React. The useRef hook gives us a way to access the DOM elements without using the document.getElementById in React. Next, we created a draw function that takes two parameters: the ctx and the frameCount. Ctx is used to assess methods and properties in canvas API, while the frameCount counts the frames and provides a timer for animations in canvas. After that, the canvas was cleared, and the color used for the drawing was set. Then, we called the beginPath() method, which tells the canvas to start drawing. In the following line, we defined what we wanted to draw, which in this case is an arc. The arc() takes in five (5) mandatory parameters and one (1) optional parameter:</p><ul><li>The x-coordinate</li><li>The y-coordinate</li><li>The radius of the circle</li><li>The starting angle in radians</li><li>The ending angle in radians</li></ul><p>The optional parameter is the choice to specify if the drawing should be clockwise or counterclockwise. It is set to false by default which means clockwise.</p><pre>useEffect(() =&gt; {<br>  const canvas = canvasRef.current;<br>  const context = canvas.getContext(&#39;2d&#39;);<br>  let frameCount = 0;<br>  let animationFrameId;<br>  const render = () =&gt; {<br>    frameCount++;<br>    draw(context, frameCount);<br>    animationFrameId = window.requestAnimationFrame(render);<br>  };<br>  render();<br>  return () =&gt; {<br>    window.cancelAnimationFrame(animationFrameId);<br>  };<br>}, []);</pre><p>In the code above block, we created a useEffect hook that will handle our application’s side effects because we won’t be able to run the animation for the application without it. Next, we define the canvas with the useRef and then get the canvas’s context which we set as 2D. We provided a render function that takes in the frameCount and the draw function, and we also provided it with the animationFrameId, which we set to the window.requestAnimationFrame() method. The window.requestAnimationFrame() method then calls the render function recursively</p><p>The window.requestAnimationFrame() method informs the browser that you want an animation performed. You can read more about the window.requestAnimationFrame() method <a href="https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame">here</a>. Next, we provide a cleanup function to the useEffect hook. This cleanup function takes in the window.cancelAnimationFrame(), which calls and cancels the animationFrameId.</p><p>Import the file into App.js, and with that, run yarn start to view the animation in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*UwuOreecWQe4ETRE.gif" /></figure><h3>Open Source Session Replay</h3><p><a href="https://github.com/openreplay/openreplay"><em>OpenReplay</em></a><em> is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yhOMPPJmTGUzBaH3.png" /></figure><p><em>Start enjoying your debugging experience — </em><a href="https://github.com/openreplay/openreplay"><em>start using OpenReplay for free</em></a><em>.</em></p><h3>Building a blank canvas that accepts drawings</h3><p>When building a canvas for accepting drawings or graphics, we have to take note of the mouse movements. We are interested in three (3) of those mouse movements. onMouseDown, onMouseUp, onMouseMove:</p><ul><li>onMouseDown: The drawing starts when we hold the mouse down (Holding the mouse&#39;s left key or double-tapping when using the trackpad on a laptop).</li><li>onMouseUp: The drawing stops whenever we stop holding the mouse down (when we stop holding the left key of the mouse or stop double-tapping when using the trackpad on a laptop).</li><li>onMouseMove: The drawing follows the movement of the mouse while the mouse is being held down.</li></ul><p>We will write functions for handling those mouse movements. Create another file and name it Drawing.jsx. This file will hold the code that will allow us to draw on the canvas.</p><pre>import { useEffect, useRef, useState } from &#39;react&#39;;<br>export default function Drawing() {<br>  const [drawing, setDrawing] = useState(false);<br>  const canvasRef = useRef(null);<br>  const ctxRef = useRef(null);<br><br>  return (<br>    &lt;&gt;<br>      &lt;canvas<br>        onMouseDown={startDraw}<br>        onMouseUp={stopDraw}<br>        onMouseMove={draw}<br>        ref={canvasRef}<br>      /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>In the code block above, we created a ref event for interacting with the canvas, and then we passed the ref to the canvas along with the three mouse movements. The second ref event is for storing the context so that we can use it when drawing on the canvas.</p><pre>const startDraw = ({ nativeEvent }) =&gt; {<br>  const { offsetX, offsetY } = nativeEvent;<br>  ctxRef.current.beginPath();<br>  ctxRef.current.moveTo(offsetX, offsetY);<br>  setDrawing(true);<br>};<br><br>const stopDraw = () =&gt; {<br>  ctxRef.current.closePath();<br>  setDrawing(false);<br>};<br><br>const draw = ({ nativeEvent }) =&gt; {<br>  if (!drawing) return;<br>  const { offsetX, offsetY } = nativeEvent;<br>  ctxRef.current.lineTo(offsetX, offsetY);<br>  ctxRef.current.stroke();<br>};<br><br>const clear = () =&gt; {<br>  ctxRef.current.clearRect(<br>    0,<br>    0,<br>    canvasRef.current.width,<br>    canvasRef.current.height<br>  );<br>};</pre><p>The code block above holds the functionalities that fire off the various mouse events. In the startDraw function, we pulled out the nativeEvent from the available browser events. Then we pulled out the offsetX and offsetY of the mouse event to know the mouse&#39;s position at any point on the canvas. We then set the state of the drawing to true. In the stopDraw function, we called the closePath() method and then set the state of the drawing to true. An if check was set in the draw function, which returns immediately whenever there is no drawing on the canvas. A clear function was added to enable the clearing of the canvas when done with the drawing.</p><pre>// Import, state and ref events<br><br>useEffect(() =&gt; {<br>  const canvas = canvasRef.current;<br>  // For supporting computers with higher screen densities, we double the screen density<br>  canvas.width = window.innerWidth * 2;<br>  canvas.height = window.innerHeight * 2;<br>  canvas.style.width = `${window.innerWidth}px`;<br>  canvas.style.height = `${window.innerHeight}px`;<br>  // Setting the context to enable us draw<br>  const ctx = canvas.getContext(&#39;2d&#39;);<br>  ctx.scale(2, 2);<br>  ctx.lineCap = &#39;round&#39;;<br>  ctx.strokeStyle = &#39;blue&#39;;<br>  ctx.lineWidth = 20;<br>  ctxRef.current = ctx;<br>}, []);<br><br>// Drawing functionalities</pre><p>We imported the useEffect hook to manage the application’s side effects in the code block above. The context used is the 2D context, and we set the properties for the canvas. Import the code in the App.js so that it can be seen in the browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*_bp_RR12geianB6S.gif" /></figure><h3>Conclusion</h3><p>This article taught about the Canvas API. The use of the Canvas API ranges from building signature pads for remote companies to data visualization and real-time video processing. The methods used in this article can be improved upon and used to develop complex animations and even game graphics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*Zn4PVXMR74co28X7.png" /></figure><p><em>Originally published at </em><a href="https://blog.openreplay.com/2d-sketches-with-react-and-the-canvas-api"><em>blog.openreplay.com</em></a><em> on June 3, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=710e8991771b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stackanatomy/2d-sketches-with-react-and-the-canvas-api-710e8991771b">2D sketches with React and the Canvas API</a> was originally published in <a href="https://medium.com/stackanatomy">StackAnatomy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving code quality in Typescript with compiler options]]></title>
            <link>https://medium.com/stackanatomy/improving-code-quality-in-typescript-with-compiler-options-d0a39b26de69?source=rss-537a53a5b2d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0a39b26de69</guid>
            <category><![CDATA[webdesign-and-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Isaac Okoro]]></dc:creator>
            <pubDate>Fri, 27 May 2022 11:10:09 GMT</pubDate>
            <atom:updated>2022-05-27T11:10:09.612Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*-qha2CJFwo5OjVJk3iwx8w.jpeg" /></figure><p><a href="https://www.typescriptlang.org/">Typescript</a> is a programming language developed by Microsoft to bring about security in terms of strict type-checking and type safety, for the Javascript language. It is a superset of Javascript that also compiles to Javascript. TypeScript provides several <em>compiler options</em> that change the way it operates. These options have various important uses, like removing comments or adding a base URL for resolving module names.</p><p>In this article, we will look at options for improving code quality in Typescript by appropriately setting some options.</p><h3>The tsconfig.json file</h3><p>The tsconfig.json file houses all compiler options. The presence shows and specifies the presence of the Typescript project root. The file can be gotten by typing the tsc --init command in the terminal. Below are some examples of some compiler options</p><pre>{<br>    &quot;compilerOptions&quot;: {<br>        &quot;module&quot;: &quot;system&quot;,<br>        &quot;noImplicitAny&quot;: true,<br>        &quot;removeComments&quot;: true,<br>        &quot;allowUnreachableCode&quot;: false,<br>        &quot;strictNullChecks&quot;: true,<br>        &quot;target&quot;: &quot;es5&quot;, <br>        &quot;module&quot;: &quot;commonjs&quot;, <br>        &quot;rootDir&quot;: &quot;.&quot;,<br>        &quot;outDir&quot;: &quot;../dist/&quot;,<br>        &quot;sourceMap&quot;: true <br>    }<br>}</pre><p>In this article we will talk about improving code quality with the noUnusedLocals, noUnusedParameters, noImplicitReturns, noFallthroughCasesInSwitch, strictNullChecks, noImplicitAny, noImplicitThis, and strictBindCallApply options.</p><h3>noUnusedLocals</h3><p>With this option set to true, the compiler will check and generate errors on unused local variables, in a way similar to the no-unused-vars in <a href="https://eslint.org/docs/rules/no-unused-vars">ESLint</a>. This compiler option aims at eliminating and removing unused variables in Typescript. Consider the example below:</p><pre>const numHandler = (input: number) =&gt; {<br>  let digits;<br>  return input;<br>};</pre><p>In the example above, we defined a function called numHandler, which takes a parameter of type number. Next, we defined a digits variable and returned the input parameter. When we compile the above code, we get presented with the error below from the terminal:</p><pre>error TS6133: &#39;digits&#39; is declared but its value is never read</pre><p>This error is produced because we declared the digits variable without using it. You can get rid of this error by using the declared value somewhere in the code, or by setting the option in the tsconfig.json file to false.</p><h3>noUnusedParameter</h3><p>This compiler option is somewhat similar to the noUnusedLocals option. The difference is that while noUnusedLocals generate an error on unused local variables, noUnusedParameter generates an error when function parameters are declared but aren&#39;t used. Consider the example below:</p><pre>const anExample = (input: string) =&gt; {<br>  const someStrings = &#39;The name is Isaac&#39;<br>  return { true, someStrings };<br>};</pre><p>We defined a function called anExample, which takes a type string parameter. Next, we defined a variable called someStrings and then returned a boolean value and the defined variable. When we compile the above code, we get presented with the error below from the terminal:</p><pre>error TS6133: &#39;input&#39; is declared but its value is never read</pre><p>This happens because we declared the input parameter in the function without using it. You can get rid of this error by using the declared parameter in the function body or by setting the option in the tsconfig.json file to false.</p><h3>noImplicitReturns</h3><p>This compiler option ensures that any function with a return declaration returns something. This option generates an error when a code path in a function doesn’t return a value. Consider the example below:</p><pre>function add(input: number, output: number) {<br>  if (input + output &gt; 0) {<br>    return input + output;<br>  }<br>}</pre><p>In the example above, we defined a function with two parameters of type number. Next, we set an if statement, which checks that the sum of both parameters is greater than zero, and then it returns that sum. With this compiler option set to true, the compiler raises the type error below:</p><pre>error TS7030: Not all code paths return a value.</pre><p>Typescript detects here that not all the code paths return something. There is no return statement for when the sum of the arguments isn&#39;t positive, and this can introduce bugs into our code because the above function will return undefined. To resolve this issue, make sure that all parts of the code return something. Consider the solution to the above code below:</p><pre>function add(input: number, output: number) {<br>  if (input + output &gt; 0) {<br>    return input + output;<br>  }<br>  return<br>}</pre><p>By using the return keyword, we ensure that all parts of our code return something. The compiler option helped us detect a possible missing situation, and avoid an error.</p><h3>Open Source Session Replay</h3><p><a href="https://github.com/openreplay/openreplay"><em>OpenReplay</em></a><em> is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*zBjY2ksLV69FzkJl.png" /></figure><p><em>Start enjoying your debugging experience — </em><a href="https://github.com/openreplay/openreplay"><em>start using OpenReplay for free</em></a><em>.</em></p><h3>noFallthroughCasesInSwitch</h3><p>When set to true, this compiler option generates errors whenever we have switch statements that flow from one branch to the other without either a break or return keyword. Consider the example below:</p><pre>let name = &#39;Isaac&#39;;</pre><pre>switch (name) {<br>  case &#39;Isaac&#39;:<br>    console.log(&#39;Isaac is a developer&#39;);<br>  case &#39;John&#39;:<br>    console.log(&#39;John is my friend&#39;);<br>    break;           <br>}</pre><p>When we compile the code above, we get the error below.</p><pre>error TS7029: Fallthrough case in switch</pre><p>This happens because there is an omitted break keyword in the branch of the first switch statement. There might be times that you might have valid reasons for omitting said break keyword, but it often is a bug. Some solutions to this are:</p><ul><li>Set noFallthroughCasesInSwitch to false in the tsconfig.json file</li><li>Use the // @ts-ignore command to suppress the error</li></ul><h3>strictNullChecks</h3><p>This compiler option checks instances where Typescript expects a concrete type (number, string, boolean) but gets null or undefined when set to true. This option helps us eliminate Uncaught TypeError errors.Consider the example below:</p><pre>let title: string;<br>name = title;<br>console.log(name);</pre><p>When we compile and run the code above, we get the error below:</p><pre>error TS2454: Variable &#39;title&#39; is used before being assigned</pre><p>The solution to this error is to assign a value to the variable before using it, as we see in the code block below:</p><pre>let title: string = &quot;Student&quot;<br>name = title<br>console.log(name)</pre><h3>noImplicitAny</h3><p>Every variable in Typescript has a type; either we define the type or Typescript tries to guess at it. Consider the example below:</p><pre>function value(a) {<br>  return;<br>}</pre><p>In the code block above, we have a function with an argument of a; since we didn&#39;t define the type for that argument, then Typescript infers that the argument has an any type. With this compiler option set to true, the compiler generates the error below:</p><pre>error TS7006: Parameter &#39;a&#39; implicitly has an &#39;any&#39; type</pre><p>The solution to this is to make sure that you correctly define the type for every argument.</p><h3>noImplicitThis</h3><p>With this compiler option set to true, Typescript will complain wherever there are instances where we are using the this keyword improperly or in a place that is not clear where the this refers to.</p><pre>class Person {<br>  weight: number;<br>  height: number;</pre><pre>  constructor(weight: number, height: number) {<br>    this.weight = weight;<br>    this.height = height;<br>  }</pre><pre>  getBodyMassIndex() {<br>    return function () {<br>      return this.weight / (this.height * this.height);<br>    };<br>  }<br>}</pre><p>We get the error below when we compile the code above due to scoping in Javascript. This is because the context of the this keyword is not bound to any instance of Person by default.</p><pre>error TS2683: &#39;this&#39; implicitly has type &#39;any&#39; because it does not have a type annotation</pre><p>The solution to this is arrow functions. This will work because arrow functions <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#arrow_functions">use the parent’s execution context</a>:</p><pre>class Person {<br>  weight: number;<br>  height: number;</pre><pre>  constructor(weight: number, height: number) {<br>    this.weight = weight;<br>    this.height = height;<br>  }</pre><pre>  getBodyMassIndex() {<br>    return () =&gt; {<br>      return this.weight / (this.height * this.height);<br>    };<br>  }<br>}</pre><h3>strictBindCallApply</h3><p>This compiler option ensures that you are using the call(), bind() and apply() functions with the right arguments.</p><pre>const numHandler = (a: number) ={<br>  console.log(`log ${a}!`);<br>}</pre><pre>numHandler.call(undefined, &#39;Isaac&#39;)</pre><p>When we run the above code with this compiler option set to true, we get an error:</p><pre>error TS2345: Argument of type &#39;string&#39; is not assignable to parameter of type &#39;number&#39;</pre><p>To resolve this, we need to pass in the correct argument, and the error will be resolved.</p><pre>const numHandler = (a: number) ={<br>  console.log(`log ${a}!`)<br>}</pre><pre>numHandler.call(undefined, &#39;25&#39;)</pre><h3>Conclusion</h3><p>In this article, we looked at some compiler options, the errors they generate, how to solve them and how to improve code quality by using them. Many other compiler options can help with code quality, and you can check them out <a href="https://www.typescriptlang.org/tsconfig">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oM7fmNSffl9yYfL2.png" /><figcaption><a href="https://newsletter.openreplay.com/">newsletter</a></figcaption></figure><p><em>This article was originally published at </em><a href="https://blog.openreplay.com/improving-code-quality-in-typescript-with-compiler-options"><em>blog.openreplay.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0a39b26de69" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stackanatomy/improving-code-quality-in-typescript-with-compiler-options-d0a39b26de69">Improving code quality in Typescript with compiler options</a> was originally published in <a href="https://medium.com/stackanatomy">StackAnatomy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Shopify problems solved with Medusa]]></title>
            <link>https://medium.com/medusa-commerce/5-shopify-problems-solved-with-medusa-65df62780343?source=rss-537a53a5b2d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/65df62780343</guid>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Isaac Okoro]]></dc:creator>
            <pubDate>Thu, 05 May 2022 14:33:56 GMT</pubDate>
            <atom:updated>2022-05-05T14:33:56.846Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rNog-JkBFwpPb9Rwuykvjg.png" /></figure><h3>Introduction</h3><p><a href="https://www.shopify.com/">Shopify</a> is a popular ecommerce platform used by a lot of merchants. With Shopify, you are able to build your storefront without technical knowledge. However, Shopify merchants with time run through some problems that lead them to employ hacky workarounds in their stores.</p><p><a href="https://medusajs.com/">Medusa</a> is a rising open source Shopify alternative built for developers. Medusa is an open source ecommerce platform that comes with many ecommerce features such as an intuitive admin interface, promotions support, E2E order handling, RMA (return merchandise authorization) flows, and easy-to-integrate third-party services.</p><p>In this article, you’ll learn more about what problems Shopify has that Medusa takes into account and provides a solution for as a platform.</p><h3>Why use Medusa</h3><p>The most important thing about Medusa is its abstraction-based architecture which gives customization capabilities for developers. Medusa’s headless architecture makes it easy to integrate with third-party services such as Content Management Systems (CMS), fulfillment providers, payment providers, and notification systems.</p><p>Its headless architecture combined with its open source nature makes a great starting point for building much more tailored ecommerce setups.</p><p>The flexibility in customization and integration provided for developers means that the merchants can be selective in terms of the services they choose to use with their ecommerce store. For example, you can integrate <a href="https://strapi.io/">Strapi</a> or <a href="https://www.contentful.com/">Contentful</a> to add rich CMS capabilities to your store.</p><p>All of this can be done with Medusa and with no hacky workarounds.</p><h3>Shopify comparison: Problems that Medusa solves</h3><h3>Customization of the backend</h3><p>Shopify is a great option if you are creating an ecommerce store that does not require any custom features. But it falls short of the mark when you want to make customizations based on your business needs, which is often the case. This is the core problem with Shopify, as it leads developers and merchants to add multiple apps to their stores or add code blocks to implement hacky workarounds.</p><p>Whereas Medusa is built with customization in mind. Although it provides <a href="https://github.com/medusajs/medusa#features">tons of features out-of-the-box</a>, you have countless ways to customize the setup based on the composable open source architecture. You can create or use existing plugins to integrate your store with third-party services.</p><p>As for the frontend, you have the freedom to choose the frontend framework of your choice to power your storefront. Be it Next.js, Gatsby, Remix, or any other framework, all you need is to connect to <a href="https://docs.medusajs.com/api/store">Medusa’s REST APIs</a>. This gives you more flexibility in optimizing your storefront for the best user experience.</p><h3>Poor site performance</h3><p>In Shopify, a lot of advanced features that merchants might want to add to their stores can only be added either through purchasing Shopify Apps or including custom code blocks in their store, as mentioned in the previous section. This is more the case when the features being added are custom to the merchants’ use case.</p><p>Adding too many apps to your Shopify store or filling it up with custom code can have an adverse effect on page load speed. A slow ecommerce store can make customers frustrated and lead them to leave your store in favor of another faster store.</p><p>On the other hand, Medusa’s headless architecture which decouples the backend from the frontend releases the frontend from the shackles of the backend and makes it faster. This means that your store loads independently from the backend and just interacts with it to fetch or post data.</p><p>Moreover, this separation of the frontend from the backend means that additional features that you wish to add to your Medusa server as plugins do not affect your storefront’s speed. This leads to a better user experience and more traffic to your store.</p><h3>Omnichannel Support</h3><p>Omnichannel refers to the ability to sell on multiple channels (across devices and platforms) while giving your customers a seamless experience across multiple channels. It also gives merchants the ability to manage orders logistically the same way regardless of where the customer places the order.</p><p>To truly provide omnichannel support you need an ecommerce platform that allows you to utilize your store’s resources similarly across platforms and devices.</p><p>Shopify’s 3 plans (Basic, Shopify, and Advanced) don’t provide a clear way to support omnichannel in your store. There are some unofficial apps that provide it, but merchants will often need multiple of them rather than just one. This can further slow down your store and fills it with more apps.</p><p>Alternatively, Shopify provides a headless commerce solution through its Shopify Plus plan which comes at a heavy price of <a href="https://www.shopify.com/plus/pricing">$2000 per month</a>. The headless architecture can make it easier for you to make use of your store’s resources across platforms, but it comes at a big price.</p><p>With Medusa, omnichannel support is available by default due to its headless architecture. Medusa’s REST APIs are designed to be consumed uniformly regardless of which client is sending the requests. So, you can provide a seamless experience to your users on both ecommerce websites as well as mobile apps.</p><p>Omnichannel support is achievable in Medusa without additional integrations or added costs.</p><h3>Multi-currency support</h3><p>By supporting multiple currencies in a store, your customers will be able to view prices based on their local currency. This gives your customers a better experience and more clarity when shopping around the world.</p><p>In Shopify, this feature is only available if the merchant can activate Shopify Pay, which is only available in <a href="https://help.shopify.com/en/manual/payments/shopify-payments/shopify-payments-requirements#supported-countries-and-regions">17 countries</a>, as well as activate Shopify Market. Even with these 2 activated, merchants still need an Advanced plan if they want to customize the price format in different currencies or the exchange rates.</p><p>An alternative approach that Shopify merchants use is creating multiple stores that give them more control over the product prices in different currencies. A big disadvantage of this approach is the difficulty that comes with managing multiple products, orders, and settings, among other resources separately for each store. This makes your store more prone to human errors and miscommunications.</p><p>With Medusa, there is no need to create or have multiple stores just to handle multiple currencies. Medusa lets you do it all from one admin dashboard. You can create multiple regions in the same store and select the currency of the region. Then, you’ll be able to set the price of the product differently for each currency.</p><p><a href="https://dev.to/medusajs/how-an-open-source-platform-resolves-shopifys-multi-currency-issues-47lg"><em>Suggested Read: How Medusa Resolves Shopify’s Multi-Currency Issues.</em></a></p><h3>Scalability and Maintainability</h3><p>Most ecommerce stores start small and then gradually get bigger with time. Starting small means that there is no need for heavy resources, custom features, or complex integrations to provide various features like customer service.</p><p>With time, businesses using Shopify find that their stores are incapable of growing with their business needs. This is due to all the problems mentioned earlier in this article. Businesses tend to need later on, if not from the start, more customization capabilities, multi-currency and omnichannel support, and better performant ecommerce websites.</p><p>This often leads businesses to continue employing hacky workaround or pay additional costs to try and keep their store performant with a good user experience. Also, if they use Shopify apps in their store it can become hard to maintain the store in case some apps don’t play well together.</p><p>Medusa, on the other hand, not only resolves all the problems mentioned above, but it is capable of scaling with businesses’ growth. A business can tailor their ecommerce platform to their needs or make sure the server can handle more users or products, at lower costs.</p><p>Furthermore, Medusa is lightweight to maintain even after adding custom logic due to its abstraction-based architecture. Medusa’s existing use cases show examples of global stores (+30M USD in yearly revenue) being able to run an entire ecommerce setup on Medusa with only 1 frontend developer supporting it.</p><h3>Conclusion</h3><p>Choose an ecommerce platform that will not only meet your current business needs but also be able to scale as your business grows.</p><p>Medusa is an ecommerce platform that aims to provide a good experience for both developers and merchants. As a merchant, you are no longer restricted by the shackles of proprietary software. As a developer, you are free to customize and make changes to the code as you see fit.</p><p>To get started with Medusa, check out the <a href="https://docs.medusajs.com/quickstart/quick-start">Quickstart guide</a>.</p><blockquote><em>Should you have any issues or questions related to Medusa, then feel free to reach out to the Medusa team via </em><a href="https://discord.gg/F87eGuwkTp"><em>Discord</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65df62780343" width="1" height="1" alt=""><hr><p><a href="https://medium.com/medusa-commerce/5-shopify-problems-solved-with-medusa-65df62780343">5 Shopify problems solved with Medusa</a> was originally published in <a href="https://medium.com/medusa-commerce">Medusa</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and Rendering charts with Nivo in React]]></title>
            <link>https://medium.com/stackanatomy/building-and-rendering-charts-with-nivo-in-react-35f90eb7d44b?source=rss-537a53a5b2d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/35f90eb7d44b</guid>
            <dc:creator><![CDATA[Isaac Okoro]]></dc:creator>
            <pubDate>Sun, 10 Apr 2022 01:27:05 GMT</pubDate>
            <atom:updated>2022-04-11T11:04:44.340Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*MLmnayvWh2c39JKorklW7g.jpeg" /></figure><p>Data visualization is an essential tool when building web applications as it seeks to grab viewers’ interest and keep their eyes on the message. This is one of the things developers endeavor to develop and use in their web applications. In this tutorial, we will discuss <a href="https://nivo.rocks/">Nivo</a> as a solution to data visualization in React applications by building charts and knowing how to implement them in your React application. Nivo is open source with more than 9.1k stars on Github.</p><h3>What is Nivo</h3><p>According to its official <a href="https://nivo.rocks/about">documentation</a>,</p><ul><li><em>Nivo provides supercharged React components to easily build Dataviz apps, it’s built on top of d3.</em></li><li><em>Several libraries already exist for React d3 integration, but only a few provide server side rendering ability and fully declarative charts.</em></li></ul><p><a href="https://nivo.rocks/">Nivo</a> is a robust and well-documented data visualization library built with d3. It is a package that leverages d3 to make beautiful, responsive data visualizations in React applications. It has helpful documentation, interactive widgets, and lots of examples of how to solve complex problems.</p><h3>Concept of Nivo</h3><p><a href="https://nivo.rocks/">Nivo</a> aims to provide beautiful and eye-catching graphs and charts that are easy to use and incorporate into your next react application. Its server rendering ability is top-notch, and it’s a solution to your data visualization needs.</p><h3>Problems with using D3 in React</h3><p><a href="https://d3js.org/">D3</a> is one of the top libraries for creating, manipulating, and visualizing data. There are still some problems associated with using it, and one of them is that it has a steep learning curve and requires learning many concepts about D3. It may take days to learn how to create a chart instead of being easy to use.</p><p>Another issue is that React and D3 both manipulate the DOM. It is advisable when using react to not mess around with the DOM. So when using D3 in React and you change or influence its DOM manipulating function, you are changing the real DOM, which means that you are sacrificing most of what React has to offer in terms of efficiency and performance.</p><p>Another issue is that you will be importing quite a large bundle size when using D3, which negatively impacts page load, and when building with D3, you tend to write lots of code for rendering a basic line chart and if you want to build something like a stream or calendar chart, it becomes bulky thereby making the code more complex and more challenging to maintain and debug.</p><h3>Why use Nivo instead of other data visualization libraries</h3><p><a href="https://nivo.rocks/">Nivo</a> has a dedicated documentation site that is interactive and includes lots of examples. It also customizes attributes and shows a live simulation of each chart directly in the site’s UI.</p><p>Nivo also has a code splitting feature. It is put into smaller packages that allow individual charts component loading instead of parsing through the entire library, which ultimately results in a better performance.</p><p>Nivo also gives you different options for server-side rendering. If you have lots of data, then you can render it in isomorphic rendering. There is also the option of rendering in canvas or SVGs.</p><h3>Installing Nivo</h3><p>Before we install Nivo in our application, we will create a new React application using the command below:</p><p>npx create-react-app Nivo-app</p><p>Next, we will install Nivo into our React application using the yarn package manager in the code block below:</p><p>yarn add @nivo/core</p><p>The code above will only install the core package without the entire library component. That’s because, as we said earlier, Nivo has code-splitting features that allow for the movement of small packages instead of the whole library, and that means that we can add a specific package when we need to use a particular component.</p><p>Let’s go ahead and add the first Nivo component to our application.</p><h3>Building Stream Chart with Nivo</h3><p>Stream charts are ideal for displaying high-volume datasets to discover trends and patterns over time across a wide range of categories.</p><p>To build a stream chart with Nivo in our React application, we install the <a href="https://nivo.rocks/stream/">stream package</a> from Nivo to enable us to build our stream chart, let’s do this below:</p><p>yarn add @nivo/stream</p><p>In the source folder of our app, we will create a `streamData.js` file and populate the file with the data which will be used in our Stream chart as shown below:</p><pre>// streamData.js</pre><pre>export const streamData = [<br>{<br>   Ronaldo: 116,<br>   Neymar: 17,<br>   Messi: 37,<br>},</pre><pre>{<br>   Ronaldo: 101,<br>   Neymar: 11,<br>   Messi: 54,</pre><pre>},</pre><pre>{<br>   Ronaldo: 156,<br>   Neymar: 166,<br>   Messi: 141,</pre><pre>},</pre><pre>{<br>   Ronaldo: 196,<br>   Neymar: 160,<br>   Messi: 63,</pre><pre>},</pre><pre>{<br>   Ronaldo: 173,<br>   Neymar: 167,<br>   Messi: 94,</pre><pre>},</pre><pre>{<br>   Ronaldo: 103,<br>   Neymar: 194,<br>   Messi: 188,</pre><pre>},</pre><pre>{<br>   Ronaldo: 114,<br>   Neymar: 105,<br>   Messi: 40,<br>},<br>{<br>   Ronaldo: 55,<br>   Neymar: 12,<br>   Messi: 49,</pre><pre>},<br>{<br>   Ronaldo: 78,<br>   Neymar: 29,<br>   Messi: 90,<br> },<br>];</pre><p>Next, we create a Stream.jsx file and inside we will import the stream component and then kick off the creation of our stream chart.</p><pre>// Stream.jsx</pre><pre>import { ResponsiveStream } from &quot;@nivo/stream&quot;;<br>import { streamData } from &quot;../streamData&quot;;<br>const Stream = () =&gt; {<br>  return (<br>    &lt;div <em>style</em>={{ height: &quot;400px&quot; }}&gt;<br>      &lt;h2&gt;My Awesome Stream&lt;/h2&gt;<br>      &lt;ResponsiveStream<br>        <em>data</em>={streamData}<br>        <em>keys</em>={[&quot;Ronaldo&quot;, &quot;Neymar&quot;, &quot;Messi&quot;]}<br>        <em>margin</em>={{ top: 50, right: 180, bottom: 50, left: 100 }}<br>        <em>axisTop</em>={null}<br>        <em>axisRight</em>={null}<br>        <em>axisBottom</em>={{<br>          orient: &quot;bottom&quot;,<br>          tickSize: 5,<br>          tickPadding: 5,<br>          tickRotation: 0, <br>          legend: &quot;Number of Years Playing&quot;,<br>          legendOffset: 36,<br>        }}<br>        <em>axisLeft</em>={{<br>          orient: &quot;left&quot;,<br>          tickSize: 5,<br>          tickPadding: 5,<br>          tickRotation: 0,<br>          legend: &quot;Number of Goals&quot;,<br>          legendOffset: -40,<br>        }} <br>        <em>offsetType</em>=&quot;silhouette&quot;<br>        <em>colors</em>={{ scheme: &quot;accent&quot; }}<br>        <em>fillOpacity</em>={0.85}<br>        <em>borderColor</em>={{ theme: &quot;background&quot; }}<br>        <em>dotBorderColor</em>={{ from: &quot;color&quot;, modifiers: [[&quot;darker&quot;,            0.7]] <br>}}<br>        <em>legends</em>={[<br>         {<br>         anchor: &quot;bottom-right&quot;,<br>         direction: &quot;column&quot;,<br>         translateX: 100,<br>         itemWidth: 80,<br>         itemHeight: 20,<br>         itemTextColor: &quot;#999999&quot;,<br>         symbolSize: 12,<br>         symbolShape: &quot;circle&quot;,<br>         effects: [<br>           {<br>             on: &quot;hover&quot;,<br>             style: {<br>               itemTextColor: &quot;#000000&quot;,<br>             },<br>          },<br>        ],<br>      },<br>    ]}<br>  /&gt;<br>   &lt;footer&gt;<br>     &lt;p&gt;Representing football goals stats with Nivo stream&lt;/p&gt;<br>     &lt;p <em>style</em>={{ fontStyle: &quot;oblique&quot;, marginTop: &quot;0.5rem&quot; }}&gt;<br>       PS: Not real stats<br>     &lt;/p&gt;<br>   &lt;/footer&gt;<br>  &lt;/div&gt;<br> );<br>};<br>export default Stream;</pre><p>In the code block above, we imported the streamData to populate our stream chart and also the ResponsiveStream from nivo. We also defined some properties for our stream component and passed our data to the stream chart.</p><pre>// App.js</pre><pre><em>import</em> Stream <em>from</em> &#39;./components/stream&#39;;<br><em>const App = () </em>=&gt;<em> {<br>  return (<br>     &lt;div&gt;<br>        &lt;Stream /&gt;<br>     &lt;/div&gt;<br>   );<br>}</em>;</pre><pre><em>export</em> <em>default</em> App;</pre><p>In our App.js file, we import the stream component and then run the command below to start up the development server on localhost:3000.</p><p>yarn start</p><p>The results should look like the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/0*mip-8VJOdhcXdwQl.png" /></figure><p><strong>Note</strong>: There are no negative goals, we are showing the goals using a stream chart and we want to make it clearly visible the goals scored by each person. Look out for the peaks and the shallow periods for the total values over time. Pick the colours and look for peaks and troughs to identify patterns or outliers. <a href="http://seeingdata.org/taketime/inside-the-chart-stream-graph/">Here</a> is a link to learn more on Stream charts and how to read them.</p><h3>Open Source Session Replay</h3><p><em>Debugging a web application in production may be challenging and time-consuming. </em><a href="https://github.com/openreplay/openreplay"><em>OpenReplay</em></a><em> is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder. OpenReplay is the only open-source alternative currently available.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*krtzrA2JrHj_TQ3B.png" /></figure><p><em>Happy debugging, for modern frontend teams — </em><a href="https://github.com/openreplay/openreplay"><em>Start monitoring your web app for free.</em></a></p><h3>Building a Calendar with responsiveCalendar component</h3><p>A calendar chart is a visualization tool that shows activity over a long period, such as months or years.</p><p>To build a calendar chart with Nivo in our React application, we will install the <a href="https://nivo.rocks/calendar/">calendar package</a> from Nivo to build our calendar chart. Let’s do this below:</p><p>yarn add @nivo/calendar</p><p>Next, we create a calendarData.js file which will contain all the data for the population of the calendar chart.</p><pre>// calendarData.js</pre><pre>export const calendarData = [<br>   {<br>    value: 290,<br>    day: &quot;2021-03-03&quot;,<br>   },<br>   {<br>    value: 289,<br>    day: &quot;2021-03-14&quot;,<br>   },<br>   {<br>    value: 316,<br>    day: &quot;2021-04-08&quot;,<br>   },<br>   {<br>    value: 297,<br>    day: &quot;2021-02-10&quot;,<br>   },<br>   {<br>    value: 256,<br>    day: &quot;2021-04-02&quot;,<br>   },<br>   {<br>    value: 49,<br>    day: &quot;2021-07-15&quot;,<br>   },<br>   {<br>    value: 374,<br>    day: &quot;2021-05-11&quot;,<br>   },<br>   {<br>    value: 55,<br>    day: &quot;2021-08-09&quot;,<br>   },<br>   {<br>    value: 274,<br>    day: &quot;2021-05-19&quot;,<br>   },<br>   {<br>    value: 20,<br>    day: &quot;2021-03-28&quot;,<br>   },<br>   {<br>    value: 29,<br>    day: &quot;2021-07-04&quot;,<br>   },<br>   {<br>    value: 374,<br>    day: &quot;2021-01-11&quot;,<br>   },<br>   {<br>    value: 377,<br>    day: &quot;2021-03-27&quot;,<br>   },<br>   {<br>    value: 371,<br>    day: &quot;2021-02-15&quot;,<br>   },<br>   {<br>    value: 327,<br>    day: &quot;2021-05-28&quot;,<br>   },<br>   {  <br>    value: 289,<br>    day: &quot;2021-03-12&quot;,<br>   },<br>   {<br>    value: 335,<br>    day: &quot;2021-03-21&quot;,<br>   },<br>   {<br>    value: 119,<br>    day: &quot;2021-06-14&quot;,<br>   },<br>   {<br>    value: 369,<br>    day: &quot;2021-08-04&quot;,<br>   },<br>   {<br>    value: 116,<br>    day: &quot;2021-06-11&quot;,<br>   },<br>   {<br>    value: 294,<br>    day: &quot;2021-04-29&quot;,<br>   },<br>   {<br>    value: 381,<br>    day: &quot;2021-01-23&quot;,<br>   },<br>   {<br>    value: 223,<br>    day: &quot;2021-05-24&quot;,<br>   },</pre><pre>   // More and more pieces of data as the case may be<br>];</pre><p>Next, we will create a Calendar.jsx file and then import the ResponsiveCalendar component from Nivo and also our created data.</p><pre>// Calendar.jsx</pre><pre>import { ResponsiveCalendar } from &quot;@nivo/calendar&quot;;<br>import { calendarData } from &quot;../calendarData&quot;;</pre><pre>const Calendar = () =&gt; {<br>   return (<br>     &lt;div <em>style</em>={{ height: 400 }}&gt;<br>       &lt;h2&gt;Nivo Calendar&lt;/h2&gt;<br>       &lt;ResponsiveCalendar<br>          <em>data</em>={calendarData}<br>          <em>from</em>=&quot;2021-01-08&quot;<br>          <em>to</em>=&quot;2021-08-09&quot;<br>          <em>emptyColor</em>=&quot;#eeeeee&quot;<br>          <em>colors</em>={[&quot;#61cdbb&quot;, &quot;#97e3d5&quot;, &quot;#e8c1a0&quot;, &quot;#f47560&quot;]}<br>          <em>margin</em>={{ top: 40, right: 40, bottom: 40, left: 40 }}<br>          <em>yearSpacing</em>={40}<br>          <em>monthBorderColor</em>=&quot;#ffffff&quot;<br>          <em>dayBorderWidth</em>={2}<br>          <em>dayBorderColor</em>=&quot;#ffffff&quot;<br>          <em>legends</em>={[<br>            {<br>              anchor: &quot;bottom-right&quot;,<br>              direction: &quot;row&quot;,<br>              translateY: 36,<br>              itemCount: 4,<br>              itemWidth: 42,<br>              itemHeight: 36,<br>              itemsSpacing: 14,<br>              itemDirection: &quot;right-to-left&quot;,<br>            },<br>         ]}<br>      /&gt;<br>    &lt;/div&gt;<br>   );<br> };</pre><pre>export default Calendar;</pre><p>In the code block above, we imported the calendarData and also the ResponsiveCalendar from Nivo. Then we defined properties for our data from the margin to the colors and also passed the calendarData to the chart.</p><p>Finally, we import the calendar component into our App.js file. We also added some routing to make everything look good</p><pre>// App.js</pre><pre><em>import</em> { BrowserRouter, Route, Switch, NavLink } <em>from</em> &#39;react-router-dom&#39;;<br><em>import</em> Calendar <em>from</em> &#39;./components/calendar&#39;;<br><em>import</em> Stream <em>from</em> &#39;./components/stream&#39;;</pre><pre><em>const App = () </em>=&gt;<em> {<br>   return (<br>     &lt;BrowserRouter&gt;<br>       &lt;nav&gt;<br>         &lt;NavLink exact activeStyle={{ textDecoration: &#39;underline&#39; }} to=&quot;/&quot;&gt;<br>           Stream<br>         &lt;/NavLink&gt;<br>         &lt;NavLink<br>           exact<br>           activeStyle={{ textDecoration: &#39;underline&#39; }}<br>           to=&quot;/calendar&quot;<br>         &gt;<br>           Calendar<br>         &lt;/NavLink&gt;<br>        &lt;/nav&gt;<br>        &lt;Switch&gt;<br>          &lt;Route exact path=&quot;/&quot; component={Stream} /&gt;<br>          &lt;Route exact path=&quot;/calendar&quot; component={Calendar}/&gt; <br>        &lt;/Switch&gt;<br>      &lt;/BrowserRouter&gt;<br>  );<br>}</em>;<br><em>export</em> <em>default</em> App;</pre><p>Our final results should look like the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*DB4tr6rf-4_pBzxK.png" /></figure><p>Here is a link to the code on <a href="https://github.com/IsaacThaJunior/Nivo-react">Github</a> and a live version of the app can be found <a href="https://nivo-react.netlify.app/">here</a>.</p><h3>Conclusion</h3><p>In this article, we learnt about Nivo, a robust and well-documented data visualization library that provides a better experience through beautiful charts. We had a glimpse of what we could achieve with Nivo. Have fun using Nivo and its various components for your next React application.</p><h3>Resources</h3><ul><li><a href="https://nivo.rocks/">Nivo docs</a></li><li><a href="https://github.com/plouc/nivo">Nivo GitHub page</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35f90eb7d44b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stackanatomy/building-and-rendering-charts-with-nivo-in-react-35f90eb7d44b">Building and Rendering charts with Nivo in React</a> was originally published in <a href="https://medium.com/stackanatomy">StackAnatomy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s talk Sass and why you should use it for your Stylesheets]]></title>
            <link>https://medium.com/@officialisaacjunior/lets-talk-sass-and-why-you-should-use-it-for-your-stylesheets-3677bc6eb316?source=rss-537a53a5b2d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3677bc6eb316</guid>
            <category><![CDATA[scss]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Isaac Okoro]]></dc:creator>
            <pubDate>Sat, 04 Dec 2021 00:39:21 GMT</pubDate>
            <atom:updated>2021-12-04T00:39:21.440Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*YtyRguVBr4eqqUk2i_pY7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*YtyRguVBr4eqqUk2i_pY7w.png" /></figure><h3>Introduction</h3><p>Styling with CSS is a pain and that’s the truth of the matter. Most developers find it hard to use the box model and center divs and even after trying and learning how to center divs, you then get the shocker that not every browser is compatible with your styling and you have to add extra lines of code to provide compatibility for other browsers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*_IakDowH0NZ0-cfr.jpg" /></figure><p>Well, worry no more. Sass takes care of compatibility issues of browsers by being compatible across different browsers and also new versions of Sass are backward-compatible meaning that older Sass syntax or lines of Sass code can still work without modifications. And if you want to have fun while writing CSS code then I can think of no better way than to learn SASS</p><p>Without further ado, let’s get into it.</p><p>SASS supports two different syntaxes which can load up each other and they are Indented Syntax which is the original SASS syntax and SCSS.</p><h3>What is Indented Syntax or SASS?</h3><p>SASS is short for <strong>Syntactically Awesome Style Sheet</strong>. I know, I know, syntactically sounds like a lot no? Well, what it means is that the lines( syntax ) of SASS code are so awesome that it is known as CSS with superpowers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/0*onf3GXON5p3BB_Hf.jpeg" /></figure><p>SASS is known as a CSS preprocessor meaning that it lets you create and write code that is then compiled into CSS. SASS uses the file extension .sass</p><p>SASS code has a loose syntax with no semicolons, it is preferred for those that want to be concise as possible when writing CSS code. An example of SASS code is given below:</p><p>body</p><p>display: inline-flex</p><p>position: relative</p><p>border: 2px solid #FF0000</p><p>border-radius: 3px</p><h3>What is SCSS?</h3><p>SCSS is short for <strong>Sassy Cascading Style Sheets</strong>. SCSS uses the file extension .scss and it’s a superset of CSS which means that all valid codes of CSS are also valid codes of SCSS. Based on its closeness and similarities with CSS, it is the easiest syntax to get used to and also to write which makes it the most popular between the two syntaxes. SCSS is preferred by those that prefer similarities when writing CSS code. An example of SCSS code is given below:</p><p>body{</p><p>display: inline-flex</p><p>position: relative</p><p>border: 2px solid #FF0000</p><p>border-radius: 3px</p><p>}</p><h3>Compiler for SASS and SCSS</h3><p>One of the disadvantages of SCSS and SASS is the fact that browsers cannot read SCSS and SASS code. Therefore for your SCSS code to work, you have to install a compiler in whichever code editor you are using. The code editor will then take that written SCSS code and then interpret it into CSS which can then be understood by browsers. I use Visual Studio Code editor which is a free code editor by Microsoft and which supports extensions. I use Live Sass Compiler which is shown in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*8Xv1TEb7dciL8qXG.png" /></figure><p>Now after you have installed the extension, you will see the Watch Sass icon below meaning that it is watching and compiling every SASS code to CSS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*y7AeBBfy9WYb5rJT.png" /></figure><h3>Benefits of using SCSS</h3><ul><li><strong>Code Splitting:</strong> One of the benefits of using SCSS is that it allows for code splitting meaning that instead of having a huge and bulky SCSS file, you can have small, separate files for styling different parts of your web app and this also helps in the long run as it makes code debugging easier. All you need to do is put a _ in front of the file you want to split and then when you are done you then use the @import rule to import that file into your main SCSS file which won’t have the __ in front of it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/0*DFnP7SWn29Jue4Kj.png" /></figure><ul><li><strong>Using Variables</strong>: SCSS offers the ability for you to create variables. Variables allow you to store a certain value and then re-use that variable throughout your code thereby keeping it DRY ( Don’t Repeat yourelf ). Below you can see how variables can be created:</li></ul><p>$primary-color: hsl(210, 36%, 96%);</p><p>$secondary-color: #2ffff5;</p><p>$ubuntu-font: &#39;Ubuntu&#39;, &#39;Arial&#39;, &#39;Helvetica&#39;, sans-serif;</p><p>$nunito-font: &#39;Nunito&#39;, &#39;Arial&#39;, &#39;Helvetica&#39;, sans-serif;</p><p>We can then use those variables anywhere in our code like so:</p><p>h1{</p><p>color: $primary-color;</p><p>font: $nunito-font;</p><p>}</p><p>p{</p><p>color: $secondary-color;</p><p>font: $ubuntu-font;</p><p>}</p><ul><li><strong>Nested Syntax</strong>: Imagine you have a section with a class of projects and inside that section, you have a div and a button with a class of projects__items and projects__btn respectively. Now SCSS allows you to nest those classes together instead of using the traditional CSS way of targeting each class separately. Now nesting allows for easy to read and maintainable code, it also prevents us from rewriting selectors multiple times. An example of nesting is shown below:</li></ul><p>.projects {</p><p>color: $primary-color;</p><p>font: $ubuntu-font;</p><p>padding-bottom: 2rem;</p><p>&amp;__items {</p><p>width: 60vw;</p><p>margin: 2rem auto 0 auto;</p><p>display: grid;</p><p>grid-template-columns: 1fr;</p><p>grid-gap: 2rem;</p><p>}</p><p>&amp;__btn {</p><p>font: $nunito-font;</p><p>color: $secondary-color;</p><p>font-size: 1.4rem;</p><p>opacity: 0;</p><p>}</p><p>}</p><ul><li><strong>Mixins</strong>: Using variables in your code is amazing right, but mixins are more cool and amazing. Mixins let you define styles that can be reused throughout your code. We then use @include to ‘include’ our mixin wherever we want to use it</li><li>An example of mixin is given below:</li></ul><p>@mixin transition-ease {</p><p>color: $secondary-color;</p><p>font: $ubuntu-font;</p><p>transition: all 0.5s ease-in-out;</p><p>}</p><p>To include our mixin in any part of our code:</p><p>a{</p><p>@include transition-ease;</p><p>}</p><h3>Conclusion</h3><p>In this article, we introduced and talked about SASS, its benefits, and why you should start using it instead of conventional CSS. You can visit <a href="https://sass-lang.com/guide">here</a> to learn more about SASS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*WvFK2mG0DWrKdV5Z.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3677bc6eb316" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Doppler in Serverless Applications]]></title>
            <link>https://medium.com/@officialisaacjunior/using-doppler-in-serverless-applications-e90c73ba6a5c?source=rss-537a53a5b2d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e90c73ba6a5c</guid>
            <category><![CDATA[doppler]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Isaac Okoro]]></dc:creator>
            <pubDate>Tue, 28 Sep 2021 04:57:16 GMT</pubDate>
            <atom:updated>2021-09-28T04:57:16.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mc-bG3krBels2vltCIMekg.png" /></figure><h3>Summary</h3><p>Secrets management is a core part of any application development as it helps keep secrets safe and ensures that you can control how and when your secrets are stored. Secret management might be tough for any developer as it requires broader security controls and a coordinated process for managing all types of secrets. Doppler was created to manage your secrets. In this tutorial, we will learn how to manage secrets in serverless applications using Doppler.</p><h3>Goals</h3><p>In this tutorial, you will learn how to build a simple serverless application. We’ll then set up our project with Doppler to store these secret keys instead of using the native .env file. At the end of this tutorial you will learn how Doppler can be used to store all your secrets credentials.</p><h3>What are Serverless applications?</h3><p>Serverless applications are cloud native applications that run without having us manage servers. they also have service integrations that are built in so that we can put our focus into building our applications instead of configuring it and thinking about servers. Serverless applications scale automatically as needed and respond to change faster.</p><h3>What are secrets?</h3><p>Simply put, secrets are sets of sensitive information that unlocks protected resources and are used to authenticate privileged users. They are also known as digital authentication credentials. Passwords are a well-known example, but there are APIs, SSH keys, private certificates, etc. These secrets are fundamental to an application’s productivity. Still, they can cause huge risks if not handled properly, and that is why you need a secret manager to help remove these risks. This is where <a href="https://www.doppler.com/">Doppler</a> comes in.</p><h3>ENV files and why you should stop using it</h3><p>A .env file is a simple configuration file used for customizing and controlling app environment variables. Simply put, it is used to keep secrets out of source code and has been used and is still used by developers today. Inasmuch as it has served us in the past and is still serving us, you should not use them again for storing confidential information.</p><p>One of the reasons is that .env files breaks down during updates and branch merging. Another is that it is hard to track access because the domain where they are stored is completely available.</p><p>One other reason is that managing .env files is time consuming and error prone if done manually which might give rise to misconfiguration.</p><p>These reasons are why you need a fully automated secret manager like<a href="https://www.doppler.com/"> Doppler</a>.</p><h3>What is Doppler?</h3><p>According to its<a href="https://docs.doppler.com/docs/enclave-guide"> documentation</a>,</p><ul><li><em>Doppler’s secure and scalable </em><strong><em>Universal Secrets Manager</em></strong><em> seeks to make developers lives easier by removing the need for env files, hardcoded secrets, and copy-pasted credentials.</em></li><li><em>The Doppler CLI provides easy access to secrets in every environment from local development to production and a single dashboard makes it easy for teams to centrally manage app configuration for any application, platform, and cloud provider.</em></li><li><em>Doppler works for every language with a steadily growing list of integrations and to get started, choose your type of adventure. Whether you want to create your first project or install the Doppler CLI, you have come to the right place.</em></li></ul><p>Doppler provides a safe and secure place for developers to store secrets, thereby doing away with hardcoded secrets and .env files, which have a very high risk of your secrets getting exposed or accessed by unauthorized parties. Doppler also removes the human element and automates the secret management process.</p><p>Doppler also has its CLI that makes it easier to install, authenticate and run your applications in a few clicks. Doppler groups secrets together by application in its dashboard so that access is served when the application starts.</p><p>Doppler also makes it easier for users to integrate directly from most major cloud platforms like Heroku, Netlify, and other secret managers.</p><h3>Setting up a Serverless application</h3><p>In this section, readers will learn how to manage app secrets in a serverless application using Doppler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/0*ItZ25y7lA-gG1iis" /></figure><p>In the image above, we have our serverless application. We need to get our secret keys from FaunaDB to store them in our secret manager.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*2Sn5-yAwkEL4WMDC" /></figure><p>Then we navigated to the security tab, and there we got the secret key which we will use for our application, as we will see from the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/0*QRXCIjECxq7J5dA4" /></figure><h3>Setting up Doppler</h3><p>Before we start saving our secrets on Doppler, we first have to create an account. Then we create a workplace that we can save with any name we want. Our workplace should look like the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*913cYcMHY2c55XCj" /></figure><h3>Creating our serverless project</h3><p>We will create our project on Doppler by navigating to the create project card when setting up our workspace. Then we will add the details of our projects, and the results should look like the image below if done correctly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*2tOt-QPsl2Tn6pt6" /></figure><p>After we have created our application, we will then navigate to the dev environment. Then we will store our secret from Fauna in the secrets card, which should look like the image below if done correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*hi0m9pCLUAbe9ZCO" /></figure><h3>Conclusion</h3><p>We have successfully set up Doppler for a serverless application to secure our apps secrets. We have drastically reduced risks by doing away with .env files.</p><p>With this article, serverless teams can now learn how to use Doppler for building serverless apps. First, using our serverless application, we connected it to FaunaDB for our secret keys. Next, we then stored the said keys using Doppler instead of the traditional .env file. Readers can find the code used in this tutorial<a href="https://github.com/IkehAkinyemi/serverless-ui-project"> here</a>, you can also learn more about Doppler<a href="https://docs.doppler.com/docs"> here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e90c73ba6a5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>