<?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 Sander de Bruijn on Medium]]></title>
        <description><![CDATA[Stories by Sander de Bruijn on Medium]]></description>
        <link>https://medium.com/@sanderdebr?source=rss-30103e53d329------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*HT95LFY5n71P8vqcbYlQQQ.png</url>
            <title>Stories by Sander de Bruijn on Medium</title>
            <link>https://medium.com/@sanderdebr?source=rss-30103e53d329------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:44:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sanderdebr/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[What is prototype in JavaScript?]]></title>
            <link>https://medium.com/@sanderdebr/what-is-prototype-in-javascript-5be975376292?source=rss-30103e53d329------2</link>
            <guid isPermaLink="false">https://medium.com/p/5be975376292</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[prototype]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sander de Bruijn]]></dc:creator>
            <pubDate>Sun, 08 Mar 2020 09:14:03 GMT</pubDate>
            <atom:updated>2020-03-08T09:14:03.423Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDO_MoZCD4n1CJV3sk_xoQ.jpeg" /></figure><p>JavaScript currently has seven primitives which are: Boolean, Null, Undefined, Number, BigInt, String and Symbol. Everything else is an object— including arrays and dates.</p><p>const myArr = [];<br>typof myArr // returns &quot;object&quot;<br>const yourArr = new Array;<br>typof yourArr// also returns &quot;object&quot;</p><p>You’re probably used to using the .slice() or .push() methods often on arrays. Where do these build-in methods come from?</p><p>const fruits = [&#39;apple&#39;, &#39;peach&#39;, &#39;kiwi&#39;];<br>fruits.pop(); // removes kiwi</p><p>They come from the methods of the prototype of the array object you created.</p><p>const apples = new Array(3).fill(&#39;apple&#39;);<br>console.log(Array.prototype); // returns methods of Array prototype</p><p>When you log the above you will see all the methods that are build-in and ready to use. When you call pop() your are actually calling a function (method) of the prototype object your array is part of. The object that you are calling becomes the value of the this keyword in the method(). So when you do:</p><p>apples.pop(); // removes and apple</p><p>the apples array is set as the value of the this keyword. The .slice() method is just a shorthand we are using</p><p>Array.prototype.pop.call(apples);</p><p>With call we can borrow methods to use on objects that contain the this keyword (like Array). So actually, we can borrow the pop() method from the Array prototype to use on array-like objects:</p><p>const fishes = {0: &#39;Neo&#39;, 1: &#39;Clown&#39;, 2: &#39;Angel&#39;, length: 3};<br>Array.prototype.pop.call(fishes);</p><p>Object are foundational to almost every aspect of the JavaScript language. The most common way is to create them with curly braces and add properties and methods using dot notation.</p><p>const fish = {};<br>fish.name = &#39;Nemo&#39;;<br>fish.food = 5;<br>fish.eat = function(food, amount) { <br>console.log(`${this.name} is eating ${food}`);<br>this.food += amount<br>}</p><p>What if we want to create more fishes? We can place the login inside a function and invoke it when we want to create a new fish.</p><h4>Functional Instantiation</h4><p>function Fish(name, food) {<br>const fish = {};<br>fish.name = name;<br>fish.food = food;<br>fish.eat = function(food, amount) { <br>console.log(`${this.name} is eating ${food}`);<br>this.food += amount<br>}<br>return fish<br>}<br>const nemo = Fish(&#39;Nemo&#39;, 5);<br>const angel = Fish(&#39;Angel&#39;, 5);</p><p>The eat method is generic, so we are wasting memory by using the above function and making each fish bigger than it needs to be.</p><h4>Functional Instantiation with shared methods</h4><p>const fishMethods = {<br>eat(food, amount) { <br>console.log(`${this.name} is eating ${food}`);<br>this.food += amount<br>}</p><p>}<br>function Fish(name, food) {<br>const fish = {};<br>fish.name = name;<br>fish.food = food;<br>fish.eat = fishMethods.eat<br>return fish<br>}<br>const nemo = Fish(&#39;Nemo&#39;, 5);<br>const angel = Fish(&#39;Angel&#39;, 5);</p><p>We’ve solved the problem of memory waste. It still seems a bit weird using a seperate object with methods in order to share methods across instances. Well, that is where prototypes come into place!</p><p>Instead of having a seperate object for methods, we call add the methods directly to the prototype of Fish.</p><h4>Prototypal Instantiation</h4><p>function Fish(name, food) {<br>const fish = {};<br>fish.name = name;<br>fish.food = food;<br>fish.eat = fishMethods.eat<br>return fish<br>}<br>Fish.prototype.eat = function(food, amount) { <br>console.log(`${this.name} is eating ${food}`);<br>this.food += amount<br>}<br>const nemo = Fish(&#39;Nemo&#39;, 5);<br>const angel = Fish(&#39;Angel&#39;, 5);</p><p>Boom! All the functionality is the same, but instead of having to manage a seperate object for all the methods we can just use a built in object from Fish called Fish.prototype.</p><h4>Object.create</h4><p>To improve our code even more, we will using Object.create() to avoid failed lookups. This method creates a new object with the specified prototype.</p><p>const fish = Object.create(Fish.prototype);</p><h4>The ‘new’ keyword</h4><p>When you invoke a function with the new keyword, it automatically assigns the this keyword to the new object that is created. So we do not need to assign the this and return it anymore.</p><p>function Fish(name, food) {<br>// const this = Object.create(Fish.prototype);<br>fish.name = name;<br>fish.food = food;<br>fish.eat = fishMethods.eat<br>// return this<br>}</p><p>const nemo = new Fish(&#39;Nemo&#39;, 5);<br>const angel = new Fish(&#39;Angel&#39;, 5);</p><h4>Classes</h4><p>A class creates a blueprint for an object, basically the same thing as we just made. There is an easier way to do it and JavaScript isn’t a dead language. So, in 2015, EcmaScript 6 introduced support for Classes and the ‘class’ keyword. How are code looks like with a class:</p><p>class Fish {<br>constructor(name, food) {<br>this.name = name;<br>this.food = food;<br>}<br>eat(food, amount) { <br>console.log(`${this.name} is eating ${food}`);<br>this.food += amount<br>}<br>}</p><p>const nemo = new Fish(&#39;Nemo&#39;, 5);<br>const angel = new Fish(&#39;Angel&#39;, 5);</p><p>Looks much better, right?</p><p>Why is it still helpful to learn how to do it the old way? Because classes are actually <em>syntactic sugar </em>over the old way. The class gets converted to the old way!</p><h4>Static methods</h4><p>What if we want a method that we want to use on the class (object constructor) but not in each instance of the class? We just add the static keyword before our method.</p><p>class Person {<br>constructor(name, age) {<br>this.name = name;<br>this.age = age;<br>}<br>walk(time) { console.log(`${this.name} is walking for ${time} minutes.`) }<br>static sayHi() { alert(&#39;Hi!&#39;) }<br>}<br>const tim = new Person(&#39;Tim&#39;, 25);<br>tim.walk(5) // works<br>tim.sayHi() // does not work<br>Person.sayHi() // works</p><p>That’s it, have fun creating objects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5be975376292" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revealing module pattern in Javascript]]></title>
            <link>https://medium.com/@sanderdebr/revealing-module-pattern-in-javascript-d62299add76b?source=rss-30103e53d329------2</link>
            <guid isPermaLink="false">https://medium.com/p/d62299add76b</guid>
            <category><![CDATA[revealing-module-pattern]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[modules]]></category>
            <dc:creator><![CDATA[Sander de Bruijn]]></dc:creator>
            <pubDate>Sun, 01 Mar 2020 16:10:45 GMT</pubDate>
            <atom:updated>2020-03-01T16:10:53.505Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewT3zoPntM1edKtNUUp1Jw.jpeg" /></figure><p>Design patterns are crucial for writing maintainable, readable and reusable code. There is a diverse list of design patterns we can use with Javascript. In this article I will provide an intro to the the revealing module pattern, which is useful in many cases.</p><p>Although ES6 modules have replaced this technique and have been implemented in today’s major browsers, it is still useful if you are not using a transpiler.</p><blockquote>A design pattern is a term used in software engineering for a general, reusable solution to a commonly occurring problem in software design.</blockquote><p>First we wrap out function inside an IIFE (immediately invoked function expression) to create a local scope for our functions and variables.</p><p>const myWidget = (function() { ... })();</p><p>With this function we can return an object referring to methods that we want to expose publicly. These public methods are the only ones who have access to our private methods and variables inside our myWidget function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e864d10e7cd36d285dfc5887e04f038/href">https://medium.com/media/4e864d10e7cd36d285dfc5887e04f038/href</a></iframe><p>In this example, we are getting the likes of Jenny and also adding a like called ‘travel’. Outside our module, we are only allowed to call the myWidget.getLikes() method, we do not have access to the data object or the addLike method which are private.</p><p><strong>Advantages<br></strong>It allows us to write more consistent code and also makes clear which variables and functions are accessed publicly.</p><p><strong>Disadvantages</strong><br>When you have a private function that refers to a public function, you can not override that public function when you want to change or update your module. This is why modules created with the Revealing Module pattern may be more fragile than modules from the original module pattern.</p><p><strong>ES6+<br></strong>With the introduction of the <strong>let </strong>and <strong>const</strong> keywords we are able to create block scoped pieces of code to make sure our variables are private. Before this was only possible inside a function or IIFE (immediately invoked function expression). Also we can use the import and export declarations to divide our code up into modules and declare local variables. Make sure to use a transpiler because to support all browser, e.g. Babel. Or use a bundler that already has a compiler included, e.g. webpack or pacel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d62299add76b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A brief explanation of the Javascript Engine and Runtime]]></title>
            <link>https://medium.com/@sanderdebr/a-brief-explanation-of-the-javascript-engine-and-runtime-a0c27cb1a397?source=rss-30103e53d329------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0c27cb1a397</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-engine]]></category>
            <dc:creator><![CDATA[Sander de Bruijn]]></dc:creator>
            <pubDate>Sat, 22 Feb 2020 07:15:23 GMT</pubDate>
            <atom:updated>2020-02-22T07:15:23.920Z</atom:updated>
            <content:encoded><![CDATA[<p>Having a solid foundation of Javascript requires understanding the mechanics behind the language itself. In this article I will share insights that power the language of Javascript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3aloVeRWM-_HTJlN9yNuQ.jpeg" /><figcaption>A different kind of engine</figcaption></figure><h3>Javascript Engine</h3><p>The most famous one is the V8 Engine developed by Google which is used in Chrome and Node.js, but actually there are many more Javascript engines. As long as they follow the standard set by the ECMAScript standards, anyone can write a JS engine. Here you can find a list of all the JS engines:</p><p><a href="https://en.wikipedia.org/wiki/List_of_ECMAScript_engines">List of ECMAScript engines</a></p><h4>How does the JS engine work?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMpj4sUa0yeBKP7bij7ajg.jpeg" /></figure><h4>1. Parser</h4><p>The HTML parser encounters a script tag with a source. The source code inside this script gets loaded as a UTF-16 byte stream to a byte stream decoder. This byte stream decoder then decodes the bytes into token which are sent to the parser. To save time, the engine tries to avoid parsing code that’s not necessary right away.</p><h4>2. AST</h4><p>The parser creates nodes based on the tokens it receives. With these nodes, it creates an Abstract Syntax Tree (AST).</p><p>Here you can check out how your code gets transformed to AST:<br> <a href="https://astexplorer.net/">https://astexplorer.net/</a></p><h4>3. Interpreter</h4><p>Next up is the interpreter, it walks through the AST and generates byte code. It reads the code line by line. When the byte code has been generated, the AST is deleted, clearing up memory space.</p><p>The problem with interpreters is that running the same code multiple times can get really slow, that’s why we have the compiler which does not repeat loops and is more optimized.</p><h4>4. Profiler</h4><p>The Profiler monitors and watches code to optimize it.</p><h4>5. Compiler</h4><p>The compiler works ahead of time and creates a translation of the code that has been written and compiles down to a lower level language that machines can read.</p><p>Other examples of compilers are Babel, which converts modern JS to browser compatible JS, and Typescript, which is a superset of JS that compiles down to JS.</p><h4>6. Optimized code</h4><p>Why do you need to know these things? So we can optimize the code to be run quicker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nky4WQwzPx1fDENxcf4GdA.jpeg" /><figcaption>Similar to a stack of functions?</figcaption></figure><h4>Call stack and Memory Heap</h4><p>The call stack keeps track of where we are in the code. It uses first in and last out and stacks for example functions. The memory heap is a place to store and write information, where we allocate, use and remove memory. The callstack calls a function from the memory heap and after executing removes it from the stack. When the maximum call stack has been reached, e.g. with an infinite loop, we call it a <strong>stack overflow</strong>.</p><p>JS automatically frees up memory that no longer is used. It marks and sweeps it from the memory. For example when a value gets reassigned and the original value is not used anymore. We call this <strong>garbage collection.</strong></p><p><strong>Memory leaks</strong> happens when a piece of memory is no longer being used or is required by an application but still is taking memory. This happens for example when you:</p><ol><li>Accidentally set global variables</li><li>Don’t close eventListeners or setIntervals</li><li>Reference out of the DOM</li></ol><h4>Event loop and Callback Queue</h4><p>If the call stack does not know what to do with a function it will send it to the Web API. When it is ready, for example when the data has been fetched, the function gets send to the callback queue and then the event loop pushes it onto the call stack only when the call stack is empty.</p><p>Here is a great resource where you can see it all in action:<br> <a href="http://latentflip.com/loupe/">http://latentflip.com/loupe/</a></p><h3>JS Runtime</h3><p>JS is a single threaded language which means that only one set of instructions can be executed at a time. There is only one call stack. Except behind the scenes we do not only have the JS Engine but also there is the JS Runtime. The runtime is the whole package including all the tools, the engine is responsible of composing JS.</p><p>The browser comes with the web API which is not native to JS. The web API can take care of asynchronous actions. You can access the web API by using methods on the window object. If we look at the Node.js, which is a runtime that enables us to run JS outside of the browser written in C++, it uses the V8 engine from the browser but extends it with a global API instead of the web API the browser uses.</p><h4>Global execution context</h4><p>Every code in JS is run inside an execution context. The global execution context is the first to run being pushes from the call stack. It gives access to the global object and the this keyword and is created in the so called creation phase.</p><p><em>This article will get updated from time to time.</em></p><p><strong><em>If you’ve learned something from this article please leave a clap.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0c27cb1a397" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting CSV to a 2D array of objects]]></title>
            <link>https://medium.com/@sanderdebr/converting-csv-to-a-2d-array-of-objects-94d43c56b12d?source=rss-30103e53d329------2</link>
            <guid isPermaLink="false">https://medium.com/p/94d43c56b12d</guid>
            <category><![CDATA[csv]]></category>
            <category><![CDATA[reduce]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sander de Bruijn]]></dc:creator>
            <pubDate>Sat, 15 Feb 2020 13:31:19 GMT</pubDate>
            <atom:updated>2020-02-15T13:32:40.483Z</atom:updated>
            <content:encoded><![CDATA[<h3>Converting CSV string to a 2D array of objects in ES6</h3><p>In this article I will explain how to convert a comma-separated values (CSV) string to a 2D array of object using Javascript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*78xdOOxeMwV-_8s-kVPH4w.jpeg" /></figure><p>Let’s say you have a CSV list of users ordered in three columns: id, name and email and you want to convert it to JSON to send it over an API for example.</p><p>First we’ll set up a function that takes in two parameters: a string and the delimiter by which we need to divide the rows by. Then we grab the title by slicing the first row and splitting it by our delimiter. If our delimiter is not set, we’ll set it to a comma by default.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddbcbe326460ebc7df951ae8da2a1096/href">https://medium.com/media/ddbcbe326460ebc7df951ae8da2a1096/href</a></iframe><p>Now we have the titles in an array, let’s get the rows inside an array. We do this by mapping over our rows array and splitting each row by our delimiter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce71b2ce931b871e532846e6e77147b9/href">https://medium.com/media/ce71b2ce931b871e532846e6e77147b9/href</a></iframe><p>Now comes the exciting part. Inside our map loop we will convert the current row to an object by running the reduce() function on our titles array. This way we can set the correct value for each title. Then we’ll return our created object back and repeat the process for every row.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a2201c01db1d24918352a1a41a95704/href">https://medium.com/media/6a2201c01db1d24918352a1a41a95704/href</a></iframe><p>Great! Let’s refractor our code and make it shorter. Also we can test it with a different delimiter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f3c97559b13ba846792c5919c20b30b/href">https://medium.com/media/0f3c97559b13ba846792c5919c20b30b/href</a></iframe><p>That’s it! Hope you’ve learned something from this short article. If so, please leave a clap.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94d43c56b12d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chaining async await API calls in Redux]]></title>
            <link>https://medium.com/@sanderdebr/chaining-async-await-api-calls-in-redux-faf02fce871d?source=rss-30103e53d329------2</link>
            <guid isPermaLink="false">https://medium.com/p/faf02fce871d</guid>
            <dc:creator><![CDATA[Sander de Bruijn]]></dc:creator>
            <pubDate>Sat, 08 Feb 2020 13:05:27 GMT</pubDate>
            <atom:updated>2020-02-15T13:33:08.657Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CRnXksTZ2wN8XC1_CUSUPw.jpeg" /></figure><p>While learning Redux I encountered several problems from which I will share the solutions to you in this article.</p><p>Let’s say you want to fetch data from the Pokémon API <a href="https://pokeapi.co/">https://pokeapi.co/</a> using Redux.</p><p>Example: <a href="https://master.d1or1a1srkom3l.amplifyapp.com/">https://master.d1or1a1srkom3l.amplifyapp.com/</a><br>Github repo: <a href="https://github.com/sanderdebr/pokedex">https://github.com/sanderdebr/pokedex</a></p><p>We will handle these async API calls outside of our main reducers of actions, instead we will use Redux Saga.</p><p>Inside our saga we have a watcherSaga and workerSaga, everytime the action DATA_REQUESTED gets called it will fire our workerSaga which fetches the return of our API call.</p><p>Our fetch function fetchAll() is an async function that retrieves a list of pokemon names. Based on this list we retrieve details for every pokemon by nesting API calls within fetchAll(). The function returns aPromise.all object that contains nested fetches described in another function called fetchPokemon().</p><p>Besides that I’ve included a timer that returns the milliseconds it took to fetch the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59808cd0cec5ec774cf0ba6e36af5500/href">https://medium.com/media/59808cd0cec5ec774cf0ba6e36af5500/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faf02fce871d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Build: Full Stack Visited Places App — Node.js API, MongoDB and MapBox]]></title>
            <link>https://medium.com/@sanderdebr/lets-build-full-stack-visited-places-app-node-js-api-mongodb-and-mapbox-2fbcbae857a3?source=rss-30103e53d329------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fbcbae857a3</guid>
            <category><![CDATA[mapbox]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Sander de Bruijn]]></dc:creator>
            <pubDate>Tue, 04 Feb 2020 11:08:59 GMT</pubDate>
            <atom:updated>2020-02-04T11:08:59.372Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Build: Full Stack Visited Places App — Node.js API, MongoDB and MapBox</h3><p>In this tutorial we will build a full stack application that shows user generated locations on an interactive map! Let’s get started.</p><p>Live demo: <a href="https://visited-places-api.herokuapp.com/">https://visited-places-api.herokuapp.com/</a><br>Github repo: <a href="https://github.com/sanderdebr/visited-places-api">https://github.com/sanderdebr/visited-places-api</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1YuJqxOJLxaKkRZU3jmqBw.png" /></figure><h3>Structure</h3><p>For the back-end we will build an API with express in Node and store the location in a MongoDB database stored on Heroku. We will test the API using Postman.</p><p>We will the MapQuest API to convert any user entered address into GeoJSON that MapBox can understand and plot on a map.</p><p>On the front-end we will show a map with all locations and update it directly when a user adds his location. For styling we will use a simple CSS framework called Bulma CSS.</p><p>Finally we will deploy the app using Heroku.</p><p>This tutorial is divided up into the following sections:</p><ol><li>Creating the API</li><li>Setting up MongoDB</li><li>Adding GeoJSON and MapBox</li><li>Front-end rendering the map</li><li>Deploying on Heroku</li></ol><h3>Creating the API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5JwXrqubprXSMUIIQ5_Fg.jpeg" /></figure><p>Let’s create a new github repo called “visited-places-api” and add it locally by running the following commands:</p><p>mkdir visited-places-api<br>cd visited-places-api<br>git init<br>npm init</p><p>Leave all the fields as is but set the main file as “server.js”.</p><p>When package.json is created, add a script so that Heroku will node how to run the app:</p><p>...<br>&quot;start&quot;: &quot;node server.js&quot;,<br>...</p><p>Next up we will install all the packages that we will need:</p><p>npm install express dotenv cors mongoose node-geocoder</p><p>And we will add nodemon so we do not have to refresh every time:</p><p>npm install nodemon -dev</p><p>Then we’ll create a file called server.js and include our packages and define app with express:</p><p>const path = require(&#39;path&#39;);<br>const express = require(&#39;express&#39;);<br>const detenv = require(&#39;dotenv&#39;);<br>const cors = require(&#39;cors&#39;):</p><p>const app = express();</p><p>We will use express.json() to recognize incoming requests as JSON:</p><p>app.use(express.json());</p><p>And enable CORS:</p><p>app.use(cors());</p><p>Next up create a new folder called “config” with a file called “config.env”.</p><p>Here we will specify environment variables, which are not publicly accessible by the user. Only on our local environment and later on Heroku. In this file add:</p><p>NODE_ENV=development</p><p>Then include them inside server.js:</p><p>dotenv.config({ path: ./config.config.env });</p><p>Then in the main folder create a file called “.gitignore” and add:</p><p>node_modules<br>config.env</p><p>So that these files are not uploaded to GitHub.</p><p>Then in our server.js we will define the PORT variable to the PORT set by the environment (later automatically by Heroku) or otherwise default 5000:</p><p>const PORT = process.env.PORT || 5000;</p><p>Let’s listen to this port and try out our app. Server.js now looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5edf667a74dc1f0042ffbe28125ec402/href">https://medium.com/media/5edf667a74dc1f0042ffbe28125ec402/href</a></iframe><p>Run npm start and check if out server is logging out: “Server running in development mode on port 5000”.</p><p>Great, we have our server running!</p><h3>Setting up MongoDB</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iD669cRfoMdL5TCIqFplkw.jpeg" /></figure><p>To connect our server to the MongoDB database from Heroku we will first connect to Heroku:</p><p>If you do not have Heroku yet:</p><ol><li>Create a free account on heroku.com</li><li>Install the Heroku command line interface: npm install -g heroku</li><li>Login using the CLI: heroku login</li></ol><p>Then run heroku create</p><p>This will create a Heroku app for you and will show up on your Heroku personal apps page.</p><p>Browse to add-ons and add the mLab MongoDB sandbox version to your app.</p><p>If you go back to the overview page of the app in Heroku, and click on the external link icon add the MongoDB add-on, you should go to the database overview page. On this page you can see the data that has been entered inside the database.</p><p>First add a new user called admin in the database. Then copy the Mongo URI listed in the header on this page and add in your newly created user and password. Then paste this into our config.env file behind “MONGO_URI=”.</p><p>Next up we will connect our server to this database. Create a new file inside our config folder called “db.js”.</p><p>In here we will connect to our database using mongoose with an async await function. We will also export out our function and import it into server.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bc577477538f23e373238ecd89a5b22/href">https://medium.com/media/6bc577477538f23e373238ecd89a5b22/href</a></iframe><p>const connectDB = require{&#39;./config/db&#39;);<br>// Connect to database<br>connectDB();</p><p>Run npm start again to check if your database connection is succesfull.</p><p>Now let’s set up our routes. Inside server.js add:</p><p>//Routes<br>app.use(&#39;/api&#39;, require(&#39;./routes/places&#39;));</p><p>Then add a new folder called “routes” with a file called “places.js” where we will define our routes.</p><p>Inside this file we are already on the “/api” path so we can define the route as “/”. Then for the get request we will retrieve the places with a function getPlaces(), and for the post request we will add a place with the addPlace() function which will write after this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7e1f3146727689df645fd0a5f9b1755/href">https://medium.com/media/e7e1f3146727689df645fd0a5f9b1755/href</a></iframe><p>For the actual request, create a folder called “controllers” with a file called “places.js”.</p><p>Before we define our controllers, we will first create a model of a place. Models are responsible for creating and reading documents from the underlying MongoDB database. Create another folder called “models” with a file called “Place.js”. Convention is to use a capital for models.</p><p>We will keep our model very simple for now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f813e11a614d48cf205ee8682fd4a981/href">https://medium.com/media/f813e11a614d48cf205ee8682fd4a981/href</a></iframe><p>Now let’s go back to our controllers inside “places.js” and add the addPlace() controller:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a6ff8d19529cb0a66e20b91c4c6f26e/href">https://medium.com/media/8a6ff8d19529cb0a66e20b91c4c6f26e/href</a></iframe><p>Again we are using an async function here. As parameters, express always asks for a request and a response and we need to add next because this is a middleware function. We wait for the Place model schema to create and send a succes status when finished, otherwise we will log out the error.</p><p>We will use Postman to check if our API is working correctly by sending test requests. If you do not have it you can get it for free at <a href="https://www.getpostman.com/">https://www.getpostman.com/</a></p><p>Open up Postman and make a POST request to <a href="http://localhost:5000/api/">http://localhost:5000/api/</a> using the header Content-Type: application/json and as body a JSON object containing any address you like:</p><p>{ &quot;address&quot;: &quot;amsterdam&quot; }</p><p>Send the request and you should receive a 200 status. Now check inside MongoDB if your collection has been updated.</p><p>We have build an API which updates an remote database, yay!</p><p>To retrieve the list of places we will use a similar controller:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6451703197c145aadb95b9b02d4ec919/href">https://medium.com/media/6451703197c145aadb95b9b02d4ec919/href</a></iframe><p>Also try to test the getPlaces request by using Postman GET <a href="http://localhost:5000/api/">http://localhost:5000/api/</a> — it should give you a 200 success status with the count and data.</p><h3>Adding GeoJSON and MapBox</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yWXVuYWZzE6ielkp-ATJjQ.jpeg" /></figure><p>Next up we will automatically convert the user entered address to JSON that MapBox can read to plot out all locations on a map.</p><p>We already have the node-geocoder package installed, so let’s get an API key from MapQuest to convert our address to geo code. You can get one for free from <a href="https://developer.mapquest.com/">https://developer.mapquest.com/</a></p><p>Then inside our config.env file add two new configs:</p><p>GEOCODER_PROVIDER=mapquest<br>GEOCODER_API_KEY=&lt;your api key&gt;</p><p>Create a new folder called “utils” with a file “geocoder.js”. Inside here we will use our mapquest key inside the options NodeGeocoder expects:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5d19b97b07d9daee9422fdcebd290b5/href">https://medium.com/media/c5d19b97b07d9daee9422fdcebd290b5/href</a></iframe><p>We will use the geoCoder inside our Place model. Our location will have three properties: type, coordinates and a formattedAddress.</p><p>Now before our Place model gets saved we have to convert the user address to geo code. We do this by adding an async function before saving the model. Then we do not save the user entered address anymore and move on with our function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c3123602a565191be4121a2501c3519/href">https://medium.com/media/2c3123602a565191be4121a2501c3519/href</a></iframe><p>Start you server again npm run start and open up Postman to send a new POST request with an application/json Content-Type and JSON body with an address.</p><p>If you’ll receive an 200 status code and see the location with coordinates, also make sure the item is inserted correctly inside MongoDB.</p><p>Let’s start working on our front-end!</p><h3>Front-end rendering the map</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4sWmDKxguuAJyRsXLLbZg.jpeg" /></figure><p>First, let’s define a public folder inside our API. Create a new folder called “public” and add an “index.html” file inside.</p><p>Now inside “server.js” add the following line so express recognizes the static folder to publish on the front-end.</p><p>// Set static folder<br>app.use(express.static(path.join(__dirname, &#39;public&#39;)));</p><p>Inside the index.html file of our public folder if you are using Visual Studio Code just type in doc en press enter to render a basic HTML template.</p><p>If you now run the app again with npm run start you’ll should see an empty HTML page on <a href="http://localhost:5000/">http://localhost:5000/</a></p><p>I have made a starter template for you here that uses the CSS framework Bulma so that we do not have to style everything ourselves. As well as an “app.js” file that we have to create inside a “/js” folder.</p><p><em>I’ve addes some quick inline styles to make it look better, the purpose of this tutorial is not to learn CSS so it is fine for now.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3338393ee60fa2b49e726996ff696765/href">https://medium.com/media/3338393ee60fa2b49e726996ff696765/href</a></iframe><p>Create an account at <a href="https://account.mapbox.com/">https://account.mapbox.com/</a> and then click on “Install the Maps SDK” for web inside your account page. Choose CDN and paste to files in the head of your index.html</p><p>Then create a new folder inside our public folder called “js” with a file called “app.js”. Inside here we will call the MapBox map and also plot our points retrieved via our API.</p><p>In the documentation examples you’ll find many snippets on parameters you can set for the map. We will set the style to street and zoom to 1. You can also define a start location by “center”. We’ll also indicate our container with id “map”.</p><p>mapboxgl.accessToken = &#39;&lt;your token&gt;&#39;;<br>const map = new mapboxgl.Map({<br> container: &#39;map&#39;,<br> style: &#39;mapbox://styles/mapbox/streets-v11&#39;,<br> zoom: 1,<br>});</p><p>Then you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gnxmk2QeC9dNToMcLVIFJg.png" /></figure><p>Let’s create an async function getPlaces() that retrieves the places from our API and store them in a variable called “places”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49f0f0a5f432187006cd18e0765ecded/href">https://medium.com/media/49f0f0a5f432187006cd18e0765ecded/href</a></iframe><p>Then we’ll create a function showMap(places) that shows the places on the map with the places variable we just created as an input. We have to call this function at the end of our async function so the places variable is filled.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fc106853a670b680c0435e00a354d63/href">https://medium.com/media/8fc106853a670b680c0435e00a354d63/href</a></iframe><p>If you add a place now through Postman with our API it should show up on the map. Great!</p><p>Now let’s create the add place functionality. First we will set up some event listeners on our form, input and submit so we can show the user an error message when no address has been filled.</p><p>We will make the addPlace(e) an async function because we have to await the api fetch. When the user gets a 200 status message, we will retrieve the API data gain to update their map.</p><p>So the user sees his added adres directly appear on screen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc616270315e74789be511fa1a7de761/href">https://medium.com/media/bc616270315e74789be511fa1a7de761/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1YuJqxOJLxaKkRZU3jmqBw.png" /></figure><p>We have come a long way! I’ve made my map dark, which you can set in settings by changing the style to “dark-v10”. Let’s publish our app in the next section.</p><h3>Deploying on Heroku</h3><p>We already created our app in Heroku and attached their MongoDB add-on. First we will add our environment variables inside Heroku. Go to the app’s settings and click on “reveal config vars” and add the following:</p><p>NODE_ENV=production<br>MONGO_URI=&lt; your uri from your config.env file &gt;<br>GEOCODER_PROVIDER=mapquest<br>GEOCOVER_API_KEY=&lt; your api key &gt;</p><p>Run heroku local web to check if your app is working correctly on <a href="http://localhost:5000/">http://localhost:5000/</a></p><p>Now we need to deploy our app. We can do this by the following commands:</p><p>git add .<br>git commit -m &#39;...&#39;<br>git push heroku master</p><p>If there were no issues, your app should be live!</p><p><a href="https://visited-places-api.herokuapp.com/">Visited Places</a></p><p><em>Please clap this story if you’v enjoyed it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fbcbae857a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a workout tracker with React and Firebase part 4: database]]></title>
            <link>https://medium.com/@sanderdebr/building-a-workout-tracker-with-react-and-firebase-part-4-database-837678323bec?source=rss-30103e53d329------2</link>
            <guid isPermaLink="false">https://medium.com/p/837678323bec</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Sander de Bruijn]]></dc:creator>
            <pubDate>Sun, 02 Feb 2020 08:26:34 GMT</pubDate>
            <atom:updated>2020-02-04T06:35:03.588Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Build: Workout tracker with React and Firebase part 4: database and deployment</h3><p>In this part we will connect the Firebase realtime database to our application so users can add, update and delete workouts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xl3jB19bvmIdLhy4EHRxCg.png" /></figure><h3>Signing up</h3><p>When a new user signs up we also need to list this user in our database so we can attach activities to this specific user.</p><p>Inside the firebase console, go to the database page and create a new realtime database using the TEST mode for now.</p><p>Inside our firebase.js file we will import the database and add it to our constructor:</p><p>import &#39;firebase/database&#39;;<br>...<br>this.db = app.database();</p><p>And inside the class we will add the methods to insert a new user:</p><p>user = uid =&gt; this.db.ref(`users/${uid}`):<br>users = () =&gt; this.db.ref(&#39;users&#39;);</p><p>When the user method is called, a new user is created inside users, using the user ID retrieved from the authUser object.</p><p>In SignUp.jsx we’ll add this method in the handleSubmit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a2ab1c0bdbcce44421f78260dc860c1/href">https://medium.com/media/9a2ab1c0bdbcce44421f78260dc860c1/href</a></iframe><p>The username and email gets stores, as well as activities which we’ll set to “not set” for now. Notice that the password does not get stored in the database, for security reasons. One of the benefits of Firebase is seperating a secure authentication.</p><p>Now try to sign up a new user and check if it is added into your realtime database in Firebase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTDCs1vzcdGbZwF7xh89JA.png" /><figcaption>First user has been added, yay!</figcaption></figure><h3>Adding an activity</h3><p>To avoid making our Calendar component too big, we will create a new component called AddActivity inside our /components folder.</p><p>Let’s think about what this component needs to receive.</p><ol><li>The day on which the activity will be added</li><li>Firebase class to add the activity to the database</li><li>A notification when the activity has been added</li></ol><p>Create an empty functional component in the AddActivity.jsx file for now.</p><p>Inside our Calendar.jsx file we will add the AddActivity component with all the props it needs to receive.</p><p>The state of the alert (called the snackbar component in Material UI) we will manage with a hook, as well as the alert text.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d8be8924b92da58af47710f57334787/href">https://medium.com/media/3d8be8924b92da58af47710f57334787/href</a></iframe><p>Inside AddActivity.jsx we will add several Material UI components:</p><ol><li>Textfield for the activity name</li><li>Dropdown for the activity type</li><li>Slider for the activity duration</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7a8217596ffeddc64a1060d70b14bb1/href">https://medium.com/media/d7a8217596ffeddc64a1060d70b14bb1/href</a></iframe><p>Now let’s add the functionalities inside our AddActivity function.</p><p>First off we will destructure off all our props again. Then we will grab the user id from authUser.uid</p><p>We will setup the queryData for our activity by converting our selectedDay object to a date string.</p><p>The activity will be managed by a state hook which has the defaultActivity as follows:</p><p>const defaultActivity = {<br> name: &#39;&#39;,<br> type: 1,<br> duration: 60,<br> date: queryDate<br>};<br>const [activity, setActivity] = useState(defaultActivity);</p><p>When the textfield or selectbox changes we want to update our activity:</p><p>const handleChange = e =&gt; {<br> const {name, value} = e.target;<br> setActivity({<br> ...activity,<br> date: queryDate,<br> [name]: value<br>});<br>};</p><p>We keep the existing activity and dynamically update the e.target fields by using the name and value.</p><p>To update our slider, we will grab the aria-valuenow attribute from the element and update it with setActivity.</p><p>Our isValid function only checks if an activity type has been entered.</p><p>On pressing submit, we’ll check if the authUser actually exist before sending it to the database. We will add the addActivity method inside our Firebase class in the next section.</p><p>With setTimeout() we can hide the alert after a couple seconds.</p><p>AddActivity.jsx now contains the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76b284a72174779ee243cf4282caa4a4/href">https://medium.com/media/76b284a72174779ee243cf4282caa4a4/href</a></iframe><p>Add the following function inside firebase.js:</p><p>addActivity = (uid, activity) =&gt; {<br> const ref = this.db.ref().child(`users/${uid}/activities`):<br> ref.push(activity);<br>}</p><p>This creates a new /activities branch inside our user branch with a new activity.</p><p>Now try to add an activity, it should show in inside the realtime database under the correct user. Check if the date is correct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*91ctN54XFPN6xamm0c5hdQ.png" /><figcaption>Many 5k’s have been ran!</figcaption></figure><p>Now we will add the alert message so our user knows what happend. The only thing we have to do is add a Snackbar component within our main Grid.</p><p>Make sure you have Grid, Paper and Snackbar imported from material UI.</p><p>&lt;Snackbar<br> anchorOrigin={{ vertical: &#39;bottom&#39;, horizontal: &#39;right&#39; }}<br> open={openSnackbar}<br> message={snackbarMsg}<br>/&gt;</p><p>Now our alert should show up when we add a new activity and automatically disappear after 3 seconds.</p><p>Next up we will set up the activity list.</p><h3>List of activities</h3><p>Create a new folder called ActivityList inside our /components folder with a file index.jsx and import it into our Calendar component. Like we did before, let’s think of all the properties we need our ActivityList component to have.</p><ol><li>List of activites</li><li>The authUser</li><li>Alert open/closed</li><li>Alert message</li><li>Loading true/false</li></ol><p>For the activities and loading we will use a state by using hooks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aeba03c3c9cab975ce4bbcb778fabbeb/href">https://medium.com/media/aeba03c3c9cab975ce4bbcb778fabbeb/href</a></iframe><p>Then we will create a function retrieveData() that fetches the activities of the user and stores them inside our activities state hook.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2bf492d77594ff6d17fbb63cbe661ec/href">https://medium.com/media/c2bf492d77594ff6d17fbb63cbe661ec/href</a></iframe><p>Now we will fire this function as soon as our component mounts, because we are using a functional component we have to use the useEffect lifecycle hooks to achieve this.</p><p>useEffect(() =&gt; retrieveData());</p><p>Make sure to import it also in Calendar.jsx. You can read more about the useEffect hook here: <a href="https://reactjs.org/docs/hooks-effect.html">https://reactjs.org/docs/hooks-effect.html</a></p><p>Now console.log some text and load your application, you will see that the component re renders infinitely. We need to connect the useEffect hook to the selectedDay variable so that it run the retrieveData() function everytime the selectedDay state changes.</p><p>useEffect(() =&gt; retrieveData(), [selectedDay]);</p><p>Run your app again and check in the console that the component only re renders whenever you select another day.</p><p>Now if you console.log the activities state you will see that the activities are coming in as one big object containing activity objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2OJYgQlixWiYlyA0T6kzMg.png" /><figcaption>Activities as objects inside one main object</figcaption></figure><p>The keys are auto generated by Firebase. So inside our ActivityList we will map over the activities using the values of the object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cd7a17d8e211f71fe829733be7a3822/href">https://medium.com/media/4cd7a17d8e211f71fe829733be7a3822/href</a></iframe><p>We will add a loader icon inside our /ActivityList folder. I’m using loading.io to generate a loader icon, you can make your own icon here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*4s_x0KQdsGGsIyqBlLpD0Q.gif" /><figcaption>Custom loader icon made with loading.io</figcaption></figure><p>Inside our ActivityList, we will again import the Table components from Material UI and destructure off the properties that this component receives.</p><p>If loading is true, we will show the image with the loader icon.</p><p>If the activities are not set (new user) or if there are no activities found, we will notify the user.</p><p>We are also importing a delete and edit icon that fire off functions.</p><h3>Deleting an activity</h3><p>For deleting an activity in our Firebase realtime database, we will just update the activity with empty values and Firebase will automatically delete this activity from our user. This way we can also use the updateActivity function for editing an activity.</p><p>Inside our firebase.js class:</p><p>updateActivity = (uid, activity, activityKey) =&gt; {<br> const ref = this.db.ref().child(`users/${uid}/activities/${activityKey)`);<br> ref.update(activity);<br>};</p><p>The activity key we will retrieve by getting the object key from our activity:</p><p>const activityKey = Object.keys(activities)[i];</p><p>Our ActivityList.jsx then finally looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bf32e596713803ad1b29bea0082c725/href">https://medium.com/media/2bf32e596713803ad1b29bea0082c725/href</a></iframe><p>In the next section we will add the editing functionality.</p><h3>Editing an activity</h3><p>Like we do everytime, let’s add a new folder inside components called EditActivity with a file index.jsx (empty functional component for now). Then import it into our Calendar.jsx component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0giAi4BJNYT-RSrHQPr9VQ.png" /></figure><p>Then we think about the properties this component needs to receive.</p><ol><li>If the user is currently editing</li><li>The to be edited activity</li><li>The activity key inside the database</li><li>Alert message</li></ol><p>const [editing, setEditing] = useState(false);<br>const [activity, setActivity] = useState(null);<br>const [activityKey, setActivityKey] = useState(null);</p><p>Based on the state of editing we’ll show the AddActivity or EditActivity component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1b1f919e5ccf25e9aa3b5be48b635dd/href">https://medium.com/media/c1b1f919e5ccf25e9aa3b5be48b635dd/href</a></iframe><p>Let’s copy all our code from AddActivity to EditActivity as they are quite similar.</p><p>On our handleSubmit function we will use the updateActivity method. Besides that, this component is almost exactly the same:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac6bec42a8dd483ca1a6fed5c8f5231d/href">https://medium.com/media/ac6bec42a8dd483ca1a6fed5c8f5231d/href</a></iframe><p>Try to edit an activity, it should update immediately.</p><p>We are almost finished with building our workout tracker application, great job!</p><h3>Showing active days</h3><p>It would be nice for the user to see which days contain activities by highlighting them right? Let’s build that.</p><p>Let’s create a hook with an empty array for our active days inside our Calendar component.</p><p>const [activeDays, setActiveDays] = useState([]);</p><p>And send the activeDays state to the CalendarBody component as props.</p><p>We will add another function inside Calendar to retrieve all the active days from the user. We will map over every activity and store the month/day combination by slicing the result. This result gets stored inside a new array which we will update activeDays with.</p><p>Everytime retrieveDate() function is called (so when another day is clicked) we also have to check again if the activeDays are changed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f9611606c76d98552b010efae409791/href">https://medium.com/media/5f9611606c76d98552b010efae409791/href</a></iframe><p>Then inside calendar-body.jsx we’ll check if the selected day is found inside the array of activeDays. If so, we’ll add an extra class to the table cell which makes the day have a little green circle behind it.</p><p>Add some activities and now they should show up with a little green circle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xl3jB19bvmIdLhy4EHRxCg.png" /></figure><p>Well, that is it for now. Great job! Using these techniques you can expand this app with functionalities like:</p><ol><li>Admin page</li><li>User settings</li><li>Advanced activities</li><li>Custom activities</li><li>Activity chart</li><li>Workout programs</li></ol><p>And store it into Firebase.</p><p>As a last step, I want to quickly show you how to deploy our application in minutes using a free AWS service called Amplify.</p><p><em>This only works if you are storing your application on Github.</em></p><ol><li>Create a free account on aws.amazon.com</li><li>Browse to the Amplify service inside the console</li><li>Click connect app, Github and continue</li><li>Select your Github repository of the workout tracker and choose the master branch</li><li>Press next, save and deploy and … you’re app will be live in minutes!</li></ol><p>Amplify is a smart service that decides which files and configs are needed to setup your application.</p><p>Thanks for checking out one of my first tutorials!</p><p>Checkout the final result: <a href="https://master.d2e0orovu8bxyk.amplifyapp.com/">https://master.d2e0orovu8bxyk.amplifyapp.com/</a><strong><br></strong>Source code: <a href="https://github.com/sanderdebr/workout-tracker">https://github.com/sanderdebr/workout-tracker</a></p><p><a href="https://medium.com/@sanderdebr/building-a-workout-tracker-with-react-and-firebase-part-1-e1b13c073135"><strong>Click here for part 1: project setup</strong></a><strong><br></strong><a href="https://medium.com/@sanderdebr/building-a-workout-tracker-with-react-and-firebase-part-2-authentication-220e5b863d5b"><strong>Click here for part 2: authentication</strong></a><strong><br></strong><a href="https://medium.com/@sanderdebr/building-a-workout-tracker-with-react-and-firebase-part-3-custom-calendar-7f13a580b085"><strong>Click here for part 3: custom calendar component</strong></a></p><p><strong>Please clap this story if you enjoyed it!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=837678323bec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a workout tracker with React and Firebase part 3: custom calendar]]></title>
            <link>https://medium.com/@sanderdebr/building-a-workout-tracker-with-react-and-firebase-part-3-custom-calendar-7f13a580b085?source=rss-30103e53d329------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f13a580b085</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Sander de Bruijn]]></dc:creator>
            <pubDate>Sat, 01 Feb 2020 15:51:56 GMT</pubDate>
            <atom:updated>2020-02-04T06:34:57.978Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Build: Workout tracker with React and Firebase part 3: custom calendar</h3><p>In this section we will build our dashboard that includes a custom calendar component which we will build from scratch!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8zN2KyQ81v37pet7TQmkg.png" /></figure><h3>Dashboard</h3><p>Let’s first start with adding a Route for Dashboard inside App.js:</p><p>import Dashboard from &#39;./pages/Dashboard&#39;;<br>...<br>&lt;Route path=&quot;/dashboard&quot;&gt; <br>&lt;Dashboard /&gt;<br>&lt;/Route&gt;<br>....</p><p>In the pages folder add a file called Dashboard.jsx</p><p>We will use the dashboard template from the Material UI framework which you can find here: <a href="https://material-ui.com/getting-started/templates/">https://material-ui.com/getting-started/templates/</a></p><p>First strip down all the items that we do not need.</p><p>Then import the withFirebase and withRouter components and export the Dashboard with them.</p><p>export default withRouter(withFirebase(Dashboard));</p><p>Also import our copyright component and insert it into the correct place.</p><p>Remove the sidebar completely for now, as well as the main content.</p><p>The styles we will move to our /config folder. Create a new file called theme.dashboard.js inside /config with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/525aa3925fca21bd70c81e47110a2d1b/href">https://medium.com/media/525aa3925fca21bd70c81e47110a2d1b/href</a></iframe><p>Then import it into Dashboard.jsx</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d18a8cbf7f6167ebede110a0350e3694/href">https://medium.com/media/d18a8cbf7f6167ebede110a0350e3694/href</a></iframe><p>Now you should see an empty dashboard when logging in or signing up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3afJtm-BmPfUTrZnwn8ZwA.png" /></figure><p>Let’s add the sidebar component. Create a new folder called Sidebar inside components with an index.jsx file.</p><p>Create a function called Sidebar and place in the return the sidebar from the Material UI dashboard template.</p><p>The Sidebar will receive props which we will send from the Dashboard.jsx page. Also we will import react router to make our navigation working.</p><p>You can see that we are receiving 3 props:</p><ol><li>open</li><li>handleDrawerClose</li><li>signOut()</li></ol><p>Inside the Sidebar function you could also destructure these props like this:</p><p>const {open, handleDrawerClose, signOut()} = props;</p><p>Whatever you prefer. Check your Sidebar code with the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e416bf9f92d98b8be001a6121abc15b/href">https://medium.com/media/6e416bf9f92d98b8be001a6121abc15b/href</a></iframe><p>Workout direct to the current page, which is the dashboard. Admin directs to the current page/admin.</p><p>Now import the Sidebar into Dashboard.jsx and load it on the correct place.</p><p>You should see an empty closed Sidebar in the dashboard now.</p><p>Let’s send the props to the Sidebar.:</p><p>&lt;Sidebar signOut={signOut} open={open} handleDrawerClose={handleDrawerClose} /&gt;</p><p>And set the functions inside the Dashboard component:</p><p>const [open, setOpen] = React.useState(true);</p><p>We’ll use a hook to set the open state of our Sidebar, default on true (open).</p><p>const handleDrawerOpen = () =&gt; setOpen(true);<br>const handleDrawerClose = () =&gt; setOpen(false);</p><p>On clicking on the sidebar icon we will open or close it by changing the state.</p><p>const signOut = () =&gt; {<br>props.firebase.auth.signOut();<br>props.history.push(&quot;/&quot;);<br>}</p><p>The props in signOut are received through our higher order components, we’ll send our user to the homepage after signing out.</p><h4>Session</h4><p>Currently everyone can see the dashboard page, this should not be possible. Let’s check if the user is authenticated and only then show the dashboard page.</p><p>Add a new folder called Session inside our components folder. In here add three files: context.js, index.js and withAuthentication.js</p><p>Inside the context.js we will only set the Context API:</p><p>import React from &#39;react&#39;;<br>const AuthUserContext = React.createContext(null);<br>export default AuthUserContext;</p><p>withAuthentication file needs firebase and also the context API which we just made, so first we will import them.</p><p>What we will do here, is create a higher order component that add the state of the authUser to the component. Then we will also add withFirebase so we do not have to call that again.</p><p>We’ll use onAuthStateChanged from firebase to check if the state has changed and set our user state accordingly. We will fire this as soon as the component has mounted, and also when the component gets removed the authUser gets removed from the class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/743211e9d6780ba86b5d5003a65a9333/href">https://medium.com/media/743211e9d6780ba86b5d5003a65a9333/href</a></iframe><p>Inside index.js let’s import and export the files above:</p><p>import AuthUserContext from &#39;./context&#39;;<br>import withAuthentication from &#39;./withAuthentication&#39;;<br>export { authUserContext, withAuthentication };</p><p>Now import authUserContext and withAuthentication inside Dashboard.jsx:</p><p>import { AuthUserContext, withAuthentication } from &#39;../components/Session&#39;;</p><p>Then check if the authUser variable exists, if so return the complete dashboard component, if not show a message or send the user back to homepage (whichever you prefer, make sure to use the router with redirecting).</p><p>&lt;AuthUserContext.Consumer&gt;<br>{ authUser =&gt; authUser ? ( .... ) : ( &lt;p&gt;Not authorized!&lt;/p&gt; ) }<br>&lt;/AuthUserContext.Consumer&gt;</p><p>Instead of using the withFirebase HOC, we’ll use:</p><p>export default withRouter(withAuthentication(Dashboard));</p><p>Try to access the dashboard now, you should see the error message. Try logging in and out, if it works, great job!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rI_gLJYubpTDvS1nyKa-Ng.png" /></figure><p><em>You can always check the original github repo if something is not working.</em></p><h3>Custom Calendar</h3><p>Next up is our calendar component, which will hold all the workout activities the user tracks.</p><p>Start with creating a folder called Calendar inside our components folder with a file Index.jsx.</p><p>Add the following basic code and import and show it on Dashboard.jsx so that you’ll see Calendar written in the Dashboard. We just add authentication onto the calendar here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03692a7148b73e8357aa3094214b5d51/href">https://medium.com/media/03692a7148b73e8357aa3094214b5d51/href</a></iframe><p>Let’s start by splitting up our Calendar into a header, where the users selects the month, and a body, where they can pick a day.</p><p>Create calendar-body.jsx and calendar-head.jsx files inside /Calendar folder. For now add simple functional components inside that return some text. Then import them inside the Calendar index file.</p><p>You should see the contents of the body and head files onto the Dashboard.</p><p>Next up we will send authUser and firebase as properties to the Calendar component. We do this by changing Dashboard.jsx:</p><p>&lt;Calendar firebase={props.firebase} authUser={authUser} /&gt;</p><p>Now our Calendar component has access to these properties. Add inside the calendar function:</p><p>const {firebase, authUser} = props;<br>console.log(firebase, authUser);</p><p>You should see both object now in your console log.</p><p>To manage our date and times we will use the moment package, run the command npm install moment and import it into the calendar component. We’ll also import the material UI grid so it gets placed better.</p><p>If you want to change the language to your own, you can add import &#39;moment/locale/en-gb&#39;; but then with your own language.</p><p>index.jsx from Calendar now looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa4f266bab77762cd5650cf142e63b9d/href">https://medium.com/media/aa4f266bab77762cd5650cf142e63b9d/href</a></iframe><h4>Calendar CSS</h4><p>Create a file called calendar.css inside our /Calendar folder with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b12e2df63b02d13b84b97fc78e361773/href">https://medium.com/media/b12e2df63b02d13b84b97fc78e361773/href</a></iframe><h4>Calendar Head</h4><p>Let’s start with selecting the correct month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8MWGNMptHWOFoDtetRseA.png" /></figure><p>We’ll be using hooks to manage our state so add useState in the import:</p><p>import React, { useState } from &#39;react&#39;;</p><p>To decide what we want to use hooks for, we need to think about which variables we would like to have managed inside the state.</p><p>This will be:</p><ol><li>Date object from moment where we can play with</li><li>If the month selection table should be shown or not</li></ol><p>The calendar head also needs to retrieve the current month, current year and a list of all months from moment.</p><p>We can set the new month by adding a function which receives the month-to-be, creates a copy of the dateObject in our state and assigns it the new month. Then we’ll replace that copy with our current dateObject.</p><p>Also we will toggle the month with the ! operator.</p><p>And then we will pass all those functionalities to our calendar header.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb100a24ec4c9a4f4b89e6f9878889a6/href">https://medium.com/media/eb100a24ec4c9a4f4b89e6f9878889a6/href</a></iframe><p>In calendar-head.jsx we first destructure off our props.</p><p>const {allMonths, setMonth, toggleMonthSelect, currentMonth, currentYear, showMonthTable} = props;</p><p>Then we’ll create an empty array called months and for every month that we receive from the props allMonths we add a TableCell to the array that contains the month name and a onClick function called setMonth.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebdccbd10b7b902f01946fe0afc27a26/href">https://medium.com/media/ebdccbd10b7b902f01946fe0afc27a26/href</a></iframe><p>Then we’ll create two more empty arrays, one for rows and one for cells. We will loop over our months array and add it to a row until it reaches three, then we create a new row.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bdb364ca5e58ea926ad5fb79c52911b/href">https://medium.com/media/1bdb364ca5e58ea926ad5fb79c52911b/href</a></iframe><p>In our return we will add another Table from Material UI containing our monthList with rows if showMonthTable is true. We also import an arrow icon from Material UI and use the currentMonth() and currentYear() getter functions from props to display them.</p><p>Now you should be able to select a year from the list and it should update immediately.</p><p>Our complete CalendarHead component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6398477ab27cac4303db55cdf50ad0b6/href">https://medium.com/media/6398477ab27cac4303db55cdf50ad0b6/href</a></iframe><h4>Calendar Body</h4><p>Next up we will build our calendar body. First let’s decide which hooks and props we need to send to the body.</p><p>As state we only need to date that the users select, lets call is selectedDay. This will be an object containing the day and month combination.</p><p>const [selectedDay, setSelected] = useState(defaultSelectedDay);<br>const defaultSelectedDay = {<br> day: moment().format(&quot;D&quot;),<br> month: moment().month()<br>}</p><p>As default we will select the current day and month with moment.</p><p>To set a new selectedDay we will add a custom setSelectedDay function that takes in the new day and updated our state hook:</p><p>const setSelectedDay = day =&gt; {<br> setSelected({ day, month: currentMonthNum() });<br>}</p><p>The day stays the same, it is the same as saying day: day. The currentMonthNum() is a getting function that gets the dateObject state hooks month:</p><p>const currentMonthNum = () =&gt; dateObject.month();</p><p>Same goes for the daysInMonth() and currentDay() functions. The actual month we’ll use to indicate the current date.</p><p>Now we also need to know the first day of the month, to decide where we need to start counting our days inside our calendar body table.</p><p>const firstDayOfMonth = () =&gt; moment(dateObject).startOf(&quot;month&quot;).format(&quot;d&quot;);</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d01d4499ccf8c32f4a0e343cac11548c/href">https://medium.com/media/d01d4499ccf8c32f4a0e343cac11548c/href</a></iframe><p>Let’s start working on the calendar-body.jsx file now. Again we’ll use the table components from Material UI.</p><p>First destructure off al our props, and then install the package react-id-generator so we can add unique keys when we map over lists (having unique keys is a prerequisite from React).</p><p>npm install react-id-generator&#39;;<br>import nextId from &quot;react-id-generator&quot;;</p><p>Until our month starts, we will add empty cells inside an array called blanks.</p><p>Then for each day in the month, we push a filled TableCell containing the day number, the onClick function setSelectedDay with the current day, and a variable className that shows different colours if the day is today or the selected day.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c56ff0f7d4d93130bf75609181ec62d/href">https://medium.com/media/3c56ff0f7d4d93130bf75609181ec62d/href</a></iframe><p>Then we combine the blanks and days arrays together by using the spread operator:</p><p>let totalSlots = [...blanks, ...monthDays];</p><p>And just like we did in the head, we loop over every cell and push it into a row untill it reaches seven.</p><p>In the return we add the Table components from Material UI and loop over the week days and also the rows which contain our day cells.</p><p>The complete calendar body then looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bd10d64487384049e87efc92f13280b/href">https://medium.com/media/6bd10d64487384049e87efc92f13280b/href</a></iframe><p>Now you should be able to select a day and the table should highlight today. Great! We have come so far already.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a7cP1dezXxy3_X6Einkx0w.png" /></figure><p><strong>In the next part we will add, update and delete activities which we will store in the Firebase real time database using noSQL.</strong></p><p>Checkout the final result: <a href="https://master.d2e0orovu8bxyk.amplifyapp.com/">https://master.d2e0orovu8bxyk.amplifyapp.com/</a><strong><br></strong>Source code: <a href="https://github.com/sanderdebr/workout-tracker">https://github.com/sanderdebr/workout-tracker</a></p><p><a href="https://medium.com/@sanderdebr/building-a-workout-tracker-with-react-and-firebase-part-1-e1b13c073135"><strong>Click here for part 1: project setup</strong></a><strong><br></strong><a href="https://medium.com/@sanderdebr/building-a-workout-tracker-with-react-and-firebase-part-2-authentication-220e5b863d5b"><strong>Click here for part 2: authentication</strong></a><strong><br></strong><a href="https://medium.com/@sanderdebr/building-a-workout-tracker-with-react-and-firebase-part-4-database-837678323bec"><strong>Click here for part 4: database and deployment</strong></a></p><p><strong>Please clap this story if you enjoyed it!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f13a580b085" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a workout tracker with React and Firebase part 2: authentication]]></title>
            <link>https://medium.com/@sanderdebr/building-a-workout-tracker-with-react-and-firebase-part-2-authentication-220e5b863d5b?source=rss-30103e53d329------2</link>
            <guid isPermaLink="false">https://medium.com/p/220e5b863d5b</guid>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[higher-order-components]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Sander de Bruijn]]></dc:creator>
            <pubDate>Sat, 01 Feb 2020 08:51:59 GMT</pubDate>
            <atom:updated>2020-02-04T06:34:51.935Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Build: Workout tracker with React and Firebase part 2: authentication</h3><p>Let’s start building our workout application!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5YbsilKnRHMcSdKndG3zA.png" /></figure><h3>SignIn</h3><p>First, we will create a Signin component. Let start by creating the SignIn.jsx file inside /src/Pages. I’m using .jsx as extension as this indicates that this file uses JSX.</p><p>echo &gt; SignIn.jsx</p><p><em>I’m using a Window machine, which creates new files with the echo command.</em></p><p>For our pages we will use the Material UI templates which you can find here:<br> <a href="https://material-ui.com/getting-started/templates/">https://material-ui.com/getting-started/templates/</a></p><p>View the source code of the sign-in-side template and copy and paste the code inside our SignIn.jsx file.</p><p>Now inside App.js import our SignIn component and replace it inside our home router:</p><p>import SignIn from &#39;./pages/SignIn&#39;;<br> &lt;SignIn /&gt;</p><p>Now the default sign in page should show up. Let’s add some basic styling.</p><h4>SignIn Styling</h4><p>In our config folder we will add a file called theme.config.jsx where we will declare our color palette and font settings:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9dce0588f549e388daf43e13d82af6a/href">https://medium.com/media/b9dce0588f549e388daf43e13d82af6a/href</a></iframe><p>For the custom Nanum Gothic font we will add the Google Fonts link inside the header of index.html:</p><p><em>&lt;link href=”https://fonts.googleapis.com/css?family=Nanum+Gothic&amp;display=swap&quot; rel=”stylesheet”&gt;</em></p><p>On fonts.google.com you may find many more fonts which are free to use. Of course you can change colors in the settings document as you like.</p><p>To apply the same styling in our whole application, we need to provide a theme inside the highest components. Inside App.js we will import ThemeProvider from material UI and add this component that uses a theme variable as parameters.</p><p>We are make use of the context API of React to provide the theme through all our components inside our Router inside App.js. You can find more information here <a href="https://reactjs.org/docs/context.html">https://reactjs.org/docs/context.html</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02ed985539573091877cc1b5ec509504/href">https://medium.com/media/02ed985539573091877cc1b5ec509504/href</a></iframe><p>Great! Now our app should have custom colors and font.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8XgiDq0ciBrVCwZoS-54w.png" /></figure><p>Now we will copy the whole useStyles hook from SignIn to a seperate theme config file called /config/theme-signinup.jsx and import this file.</p><p>Also we will move the copyright component to a new file inside /components/Copyright/index.jsx and import it into SignIn.jsx.</p><h4><strong>SignIn functions</strong></h4><p>First remove the remember me checkbox. Then add a handleChange function on both TextField components for email address and password:</p><p>onchange={handleChange}</p><p>Also remove the default reload of the page by adding onto the form element a preventDefault function:</p><p>onSubmit={e =&gt; preventDefault()}</p><p>And on the Sign In button add an onClick and disabled property:</p><p>onClick={handleSubmit}<br>disabled={isValid}</p><p>Then we will set up an initialUser object:</p><p>const initialUser = {id: null, email: &#39;&#39;, password: &#39;&#39;, error null, auth: null}</p><p>and use this object as the default user inside our React Hook:</p><p>const [user, setUser = useState(initialUser()</p><p>Make sure you have useState imported:</p><p>import React, { useState } from &#39;react&#39;;</p><p>When the user types inside the email or password field, we will dynamically update the user object with the input:</p><p>const handleChange = e =&gt; {<br> const { name, value } = e.target;<br> setUser({...user, [name]: value})<br>};</p><p>First the name and value of the input gets retrieved by destructering the event.target object, then we dynamically set the object key and value of user while keeping the rest of the user object the same (using the three dots which are called the spread operator).</p><p>Let’s add an empty function handleSubmit for now, which will use the firebase class later to sign in our user.</p><p>To enable the submit button we have to check if both the email and password fields are filled in:</p><p>const isValid = user.email === &#39;&#39; || user.password === &#39;&#39;;</p><p>Console.log out your user object and check if it is working correctly. SignIn component at this point:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bb702d9cc5a6fc3586fe77fcbde6c40/href">https://medium.com/media/2bb702d9cc5a6fc3586fe77fcbde6c40/href</a></iframe><p>Before we can actually verify if the user is authenticated, we have to setup Firebase and a new user has to signup onto our Firebase authentication.</p><h3>Firebase</h3><p>Go to firebase.google.com, create an account and add a new project which we will call “Workout Tracker”</p><p>Inside the console browse to “Authentiction” and add a new login method “Email/password”.</p><p>On the project overview page press the web icon to add a web app which we will call “workout-tracker”, skip the hosting.</p><p>Then you’ll receive the script, copy the “var firebaseConfig = { … }” object.</p><p>Create a new folder inside our components called “Firebase” with a new file “firebase.js” and copy the script inside this file.</p><p><em>Usually it is bad practice to keep the API key publicly in our file like we do here, but in this case it is just to identify the Firebase project. It is not a security risk.</em></p><p>Great! Now we will add the firebase package to our project by running:</p><p>npm install firebase</p><p>Now we will import the firebase package into our “Firebase.js” file:</p><p>import app from &#39;firebase/app&#39;;<br>import &#39;firebase/auth&#39;;<br>import &#39;firebase/database&#39;;</p><p>We will now create a class called “Firebase” which will hold our config, authentication and database functions inside its constructor and add methods so we can use the firebase functionalities from everywhere inside our application.</p><p>Your code now should look like this, with your own settings:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3feb7c885d05a1632fbd93979ad1bb01/href">https://medium.com/media/3feb7c885d05a1632fbd93979ad1bb01/href</a></iframe><p>Next up we will create a so called higher order component (HOC) which basically enhances a component with anything that we would like to add to that component, in this case our Firebase class. Create a new file called context.js inside the Firebase folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e30660ead34f4202b1a37da29fe41b09/href">https://medium.com/media/e30660ead34f4202b1a37da29fe41b09/href</a></iframe><p>The function above does the following:</p><ol><li>Takes in a component</li><li>Keeps it properties by spreading them out {…props}</li><li>Consumes Firebase by using the Context API</li><li>Add the firebase class as an added property</li></ol><p>You can read more about React HOC’s here: <a href="https://reactjs.org/docs/higher-order-components.html">https://reactjs.org/docs/higher-order-components.html</a></p><p>And here is more information on React Context API: <a href="https://reactjs.org/docs/context.html">https://reactjs.org/docs/context.html</a></p><p>Create a new file called index.js inside our Firebase folder where we will import and export our firebase and context files.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/440a975b49899cf601aa2f26d081d74b/href">https://medium.com/media/440a975b49899cf601aa2f26d081d74b/href</a></iframe><p>Now we will provide our Firebase class inside /src/index.js file. The context API always uses a Provider and Consumer component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cb780cb53b38ee909e0f4b84bdbd816/href">https://medium.com/media/3cb780cb53b38ee909e0f4b84bdbd816/href</a></iframe><h3>Signup</h3><p>Let’s copy our SignIn.jsx page into a new page called SignUp.jsx.</p><p>First we will make it possible to browse to signup from the SignIn page. Import our router functions inside SignIn.jsx</p><p>import { Link, withRouter } from &#39;react-router-dom&#39;;</p><p>And change the link to signup:</p><p>&lt;Link to=&quot;/sign-up&quot;&gt;Don&#39;t have an account? Sign up&lt;/Link&gt;</p><p>Into App.js import the SignUp page and add it into the route.</p><p>&lt;Route path=&quot;/sign-up&quot;&gt; &lt;SignUp /&gt; &lt;/Route&gt;</p><p>Now it should direct us to the SignUp page.</p><p>Let’s direct the user to the homepage when they already have an account by changing the Link again and add an extra textfield for the username.</p><p>Our initialuser object also should contain a name now and isValid should check if the name is set.</p><h3>Signing up a user</h3><p>First import the withFirebase function from our Firebase component</p><p>import { withFirebase } from &#39;../components/Firebase&#39;;</p><p>Then export our page with firebase by:</p><p>export default withRouter(withFirebase(SignUp));</p><p>Now we have enhanced our SignUp component with Firebase and Router.</p><p>Add props to our SignUp function:</p><p>function SignUp(props) { ... }</p><p>and add the SignUp functionality inside handleSubmit, see the code snipper below:</p><ol><li>We have access to the Firebase props via the Higher Order Component we made.</li><li>Firebase returns a promise from where we will set our user state to the initial empty user and forward the user to the dashboard page using react-router.</li><li>If authUser is not returned with an error, we will keep the current state and add the error message with the spread operator.</li></ol><p>Just before the submit button insert the error message.</p><p>Check you code with the snipper below and try to sign up a new user.</p><p>You should get an error message or redirected to /dashboard. Great, signing up is working! You can see the new user in the Firebase console authentication.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/257093f77b588771b9fee5f88d0722a7/href">https://medium.com/media/257093f77b588771b9fee5f88d0722a7/href</a></iframe><h3>Signing in a user</h3><p>Now that the user has been signed up, let’s also make sure he/she is able to sign in to our application.</p><p>We will add the preventDefault on form submit and the error message component before the submit button.</p><p>The handleSubmit functionality is also similar to the one in SignUp.jsx.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ztr0cFG9Rl4KBwprFK0UbQ.png" /></figure><p>We will export our SignIn function again using withRouter() and withFirebase() which are imported into SignIn.jsx.</p><p>Check you code with the snipper below and try to login.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5047ae3c3b7e8b9965ff391d1e56d0c/href">https://medium.com/media/f5047ae3c3b7e8b9965ff391d1e56d0c/href</a></iframe><p>We already made huge progress, great job!</p><p>Next up we will add the forgot password functionality.</p><h3>Forgot password</h3><p>Let’s create a new component for our password forgot functionality by adding a folder PasswordForget inside components with a file Index.jsx.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U6NqrLyJsadLk3OwoJ9kBA.png" /></figure><p>We will be using the Dialog and Snackbar components from the Material UI framework. The open/close state of these items is managed by two hooks which are false (closed) by default:</p><p>const [open, setOpen] = React.useState(false)<br>const [openAlert, setOpenAlert] = React.useState(false)</p><p>We will also add firebase to this component so we can use the doPasswordReset function. Inside SignIn.jsx we will import the forgot password component and add it inside the grid item:</p><p>import PasswordForget from &#39;../components/PasswordForget&#39;;<br>&lt;PasswordForget /&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*RVPfHRX1H0jN9bTXrIWl_g.png" /><figcaption>That’s better!</figcaption></figure><p>Analyse the code below and add it to your project inside /src/components/PassWordForget/index.jsx</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf8469db23079af51c802b1576849eed/href">https://medium.com/media/bf8469db23079af51c802b1576849eed/href</a></iframe><p>Super! We have added signing up, in and password forget functionalities by adding authentication with Firebase by using:</p><ul><li>Higher order components</li><li>Context API</li><li>React Hooks</li><li>Firebase</li><li>Material UI components</li></ul><p><strong>In the next section we will build a custom calendar component which will hold all our workouts.</strong></p><p>Checkout the final result: <a href="https://master.d2e0orovu8bxyk.amplifyapp.com/">https://master.d2e0orovu8bxyk.amplifyapp.com/</a><strong><br></strong>Source code: <a href="https://github.com/sanderdebr/workout-tracker">https://github.com/sanderdebr/workout-tracker</a></p><p><a href="https://medium.com/@sanderdebr/building-a-workout-tracker-with-react-and-firebase-part-1-e1b13c073135"><strong>Click here for part 1: project setup</strong></a><strong><br></strong><a href="https://medium.com/@sanderdebr/building-a-workout-tracker-with-react-and-firebase-part-3-custom-calendar-7f13a580b085"><strong>Click here for part 3: custom calendar component</strong></a><strong><br></strong><a href="https://medium.com/@sanderdebr/building-a-workout-tracker-with-react-and-firebase-part-4-database-837678323bec"><strong>Click here for part 4: database and deployment</strong></a></p><p><strong>Please clap this story if you enjoyed it!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=220e5b863d5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a workout tracker with React and Firebase: part 1]]></title>
            <link>https://medium.com/@sanderdebr/building-a-workout-tracker-with-react-and-firebase-part-1-e1b13c073135?source=rss-30103e53d329------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1b13c073135</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Sander de Bruijn]]></dc:creator>
            <pubDate>Fri, 31 Jan 2020 17:34:59 GMT</pubDate>
            <atom:updated>2020-02-04T06:34:48.554Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Build: Workout tracker with React and Firebase part 1: project setup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TBGuvXSd6QUBfg9WqQRBA.png" /></figure><p>Hi all! While building a web application to track my physical activities I have learned many things which I will share with you in this tutorial.</p><p><strong>Live demo:</strong><br><a href="https://master.d3963aoi020v9l.amplifyapp.com/">https://master.d3963aoi020v9l.amplifyapp.com/</a></p><p>This tutorial is targeted for beginners in React who already have experience using ES6 and create-react-app. We will be using:</p><ul><li>100% React Hooks, Router and Context API</li><li>Firebase Authentication and noSQL database</li><li>Material UI components</li></ul><p>This tutorial is divided up in to the following sections:</p><ol><li>Setting up our project</li><li>User authentication with Firebase</li><li>Creating a custom Calendar component</li><li>Adding, updating and deleting workouts with noSQL database</li><li>Deployment</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8zN2KyQ81v37pet7TQmkg.png" /></figure><h3>1. Project setup</h3><p>We will start with creating the new project folder and installing all needed dependencies. I’m using Visual Studio Code, with the shortcut CTRL + ~ you can toggle the command line inside Visual Studio Code. Run the following command:</p><p>npx-create-react-app activity-tracker</p><p>This will create a new folder with our new react app.</p><p>Then delete all the files in /src except App.js, App.css, Index.js, Index.css</p><p>Inside App.js: delete the logo import, remove everything inside the return and add &lt;h1&gt;Hello World!&lt;/h1&gt; in the return.</p><p>Inside Index.js: delete the serviceworker import and unregister line. Now run npm run start to check if the app displays <em>Hello World!</em></p><h4>Material UI</h4><p>To speed up our development we will use pre-build components from Material-UI framework which you can find here: <a href="https://material-ui.com/">https://material-ui.com/</a></p><p>Run the following commands:</p><pre>npm install @material-ui/core<br>npm install @material-ui/icons</pre><h4>Folders</h4><p>Next up we will create our folders, which will be: components, pages and config. Open up command prompt and use the following commands:</p><p>cd src <br>mkdir components pages config</p><p>This way we have our app running in the command line of Visual Code and can run command with command prompt separately.</p><h4>Router</h4><p>To navigate inside our App we will use react-router. We are creating a single-page-application which is basically one big page that does not need to be refreshed, we will just show and load only the components we want the user to see.</p><p>Install react-router by running the command:</p><p>npm install react-router-dom</p><p>Then inside App.js we will import react-router and add a switch to navigate between paths. We will create a path for home “/” and a path for signing up “/sign-up”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72477dae5d567e1330dd4dee0aff6aef/href">https://medium.com/media/72477dae5d567e1330dd4dee0aff6aef/href</a></iframe><p>Now you should see “Signin” in your browser and if you’ll browse to /sign-up you should see “Signup”. Great, our router is working!</p><p><strong>In part 2 we will actually start building our application and adding authentication.</strong></p><p>Checkout the final result: <a href="https://master.d2e0orovu8bxyk.amplifyapp.com/">https://master.d2e0orovu8bxyk.amplifyapp.com/</a><strong><br></strong>Source code: <a href="https://github.com/sanderdebr/workout-tracker">https://github.com/sanderdebr/workout-tracker</a></p><p><a href="https://medium.com/@sanderdebr/building-a-workout-tracker-with-react-and-firebase-part-2-authentication-220e5b863d5b"><strong>Click here for part 2: authentication</strong></a><strong><br></strong><a href="https://medium.com/@sanderdebr/building-a-workout-tracker-with-react-and-firebase-part-3-custom-calendar-7f13a580b085"><strong>Click here for part 3: custom calendar component</strong></a><strong><br></strong><a href="https://medium.com/@sanderdebr/building-a-workout-tracker-with-react-and-firebase-part-4-database-837678323bec"><strong>Click here for part 4: database and deployment</strong></a></p><p><strong>Please clap this story if you enjoyed it!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1b13c073135" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>