<?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 Jumanah Al Asadi on Medium]]></title>
        <description><![CDATA[Stories by Jumanah Al Asadi on Medium]]></description>
        <link>https://medium.com/@jujuontheweb?source=rss-f8e8ba70a756------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-7-XHxqBWKMW-t5rNGQIHA.jpeg</url>
            <title>Stories by Jumanah Al Asadi on Medium</title>
            <link>https://medium.com/@jujuontheweb?source=rss-f8e8ba70a756------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:06:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jujuontheweb/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[Transcoding multiple qualities with Bento4, generating manifest (MPEG-DASH), encryption]]></title>
            <link>https://jujuontheweb.medium.com/transcoding-multiple-qualities-with-bento4-generating-manifest-mpeg-dash-encryption-3d48d39ab5f1?source=rss-f8e8ba70a756------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d48d39ab5f1</guid>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[transcoding]]></category>
            <category><![CDATA[mpeg-dash]]></category>
            <category><![CDATA[bento4]]></category>
            <category><![CDATA[ffmpeg]]></category>
            <dc:creator><![CDATA[Jumanah Al Asadi]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 18:50:09 GMT</pubDate>
            <atom:updated>2023-02-19T19:31:59.781Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transcoding multiple qualities for video, generating manifest MPEG DASH, encryption</h3><p>Bento4 is a helpful tool to transcoding videos and get them ready for streaming.</p><h3>What’s in this article!</h3><p>Before you can share your video to the general public, a standard practise is to break it up into small segments so your users can stream it gradually instead of waiting for the entire file to download. Also, you should create different video qualities, such as high and low to support different internet connection speeds that your users may have.</p><p>There are already two streaming standards available, Apple HLS and MPEG DASH. In this article we will explore MPEG DASH.</p><p>The process of transcoding is having an input single video, and outputting streaming segments with a manifest (file which describes the order to play the segments).</p><p>A great and simple tool to get this done is Bento4 which wraps over ffmpeg libraries.</p><p>To get started, prepare a video in different resolutions!</p><h3><strong>Bento4 Installation</strong></h3><p><strong>1. Installing bento 4 on Mac osx</strong></p><p>- Homebrew: [bento4 — Homebrew Formulae](https://formulae.brew.sh/formula/bento4)</p><p>This will give us access to the bento4 tools like mp4info, mp4fragment, mp4dash, mp4encrypt..</p><p><strong>2. Make sure your Mac OS terminal can access your files</strong></p><p>- [permission — Why do I get “ls: Desktop: Operation not permitted” when I own Desktop? — Ask Different](https://apple.stackexchange.com/questions/425519/why-do-i-get-ls-desktop-operation-not-permitted-when-i-own-desktop)</p><h3><strong>How to Segment and Create Dash Manifests</strong></h3><p>Source Guideline: [How to Package MPEG-DASH using Bento4’s mp4dash — OTTVerse](https://ottverse.com/bento4-mp4dash-for-mpeg-dash-packaging/)</p><p><strong>1. Create a folder, and video files with 3 different resolutions/qualities</strong></p><p>/capture_dash</p><ul><li>CAPTURE_123ABC_1920x1080.mp4</li><li>CAPTURE_123ABC_1280x720.mp4</li><li>CAPTURE_123ABC_640x360.mp4</li></ul><p><strong>2. Pre-requisite: In order to segment the files with bento4, first fragment the files using mp4fragment. Choose how how many ms.. using the — fragment-duration flag.</strong></p><p>i.e 4000ms = 4 seconds etc.</p><pre>mp4fragment — fragment-duration 4000 ./CAPTURE_123ABC_1920x1080.mp4 ./CAPTURE_123ABC_1920x1080_frag.mp4<br><br>mp4fragment - fragment-duration 4000 ./CAPTURE_123ABC_1280x720.mp4 ./CAPTURE_123ABC_1280x720_frag.mp4<br><br>mp4fragment - fragment-duration 4000 ./CAPTURE_123ABC_640x360.mp4 ./CAPTURE_123ABC_640x360_frag.mp4</pre><p>Optional: we can use mp4info to confirm that the video is fragmented.</p><pre>mp4info CAPTURE_123ABC_640x360_frag.mp4</pre><p>Output:</p><pre>Movie:<br>duration: 32600 (media timescale units)<br>duration: 32600 (ms)<br>time scale: 1000<br>*fragments: yes*</pre><p><strong>3. Then run the dashify command! You can specify the name of the manifest file using — mpd-name and provide the three different qualities which were fragmented in the previous step.</strong></p><pre>mp4dash — mpd-name manifest.mpd CAPTURE_123ABC_1920x1080_frag.mp4 CAPTURE_123ABC_1280x720_frag.mp4 CAPTURE_123ABC_640x360_frag.mp4</pre><p><strong>Output:</strong></p><p>Files will be segmented as .m4s files of (1–6 seconds). They will be placed into different folders based on their qualities, and will be sequential.</p><p>Manifest generated will be an manifest.mpd file, bento4 will automatically understand the three qualities from the video / resolutions will be displayed as different representations with different bandwidths.</p><pre>&lt;?xml version=&quot;1.0&quot; ?&gt;<br>&lt;MPD xmlns=&quot;urn:mpeg:dash:schema:mpd:2011&quot; profiles=&quot;urn:mpeg:dash:profile:isoff-live:2011&quot; minBufferTime=&quot;PT1.00S&quot; mediaPresentationDuration=&quot;PT4.004S&quot; type=&quot;static&quot;&gt;<br>&lt;! - Created with Bento4 mp4-dash.py, VERSION=2.0.0–639 →<br>&lt;Period&gt;<br>&lt;! - Video →<br>&lt;AdaptationSet mimeType=&quot;video/mp4&quot; segmentAlignment=&quot;true&quot; startWithSAP=&quot;1&quot; maxWidth=&quot;1920&quot; maxHeight=&quot;1080&quot;&gt;<br>&lt;SegmentTemplate timescale=&quot;1000&quot; duration=&quot;1001&quot; initialization=&quot;$RepresentationID$/init.mp4&quot; media=&quot;$RepresentationID$/seg-$Number$.m4s&quot; startNumber=&quot;1&quot;/&gt;<br>&lt;Representation id=&quot;video/avc1/1&quot; codecs=&quot;avc1.640028&quot; width=&quot;1920&quot; height=&quot;1080&quot; scanType=&quot;progressive&quot; frameRate=&quot;30000/1001&quot; bandwidth=&quot;6320503&quot;/&gt;<br>&lt;Representation id=&quot;video/avc1/2&quot; codecs=&quot;avc1.64001F&quot; width=&quot;1280&quot; height=&quot;720&quot; scanType=&quot;progressive&quot; frameRate=&quot;30000/1001&quot; bandwidth=&quot;3269850&quot;/&gt;<br>&lt;Representation id=&quot;video/avc1/3&quot; codecs=&quot;avc1.64001F&quot; width=&quot;640&quot; height=&quot;360&quot; scanType=&quot;progressive&quot; frameRate=&quot;30000/1001&quot; bandwidth=&quot;1843364&quot;/&gt;<br>&lt;/AdaptationSet&gt;<br>&lt;/Period&gt;<br>&lt;/MPD&gt;</pre><h3><strong>Encryption &amp; DRM:</strong></h3><p>If a media provider needs to encrypt the files they are generating, so that nobody can open them unless they are allowed to or “subscribed”, you can do so using an encryption key. A more production, “real world” and secure way to protect premium media content is accomplished by leveraging a DRM (Digital Rights Management) set up. A DRM will license both an encryption key to secure the content at the time of transcoding, and a decryption key to the Media Player to play the secure files.</p><p>Bento4 works with various DRMs. The simplest way to produce encrypted MPEG DASH streams is to instruct mp4dash to perform the encryption for you automatically, by using the — encryption-key option.</p><p><strong>1. Add encryption flags to the mp4dash command.. For example to encrypt content using a DRM, like Marlin:</strong></p><pre>mp4dash — mpd-name manifest.mpd — marlin — encryption-key=121a0fca0f1b475b8910297fa8e0a07e:a0a1a2a3a4a5a6a7a8a9aaabacadaeaf CAPTURE_123ABC_1920x1080_frag.mp4 CAPTURE_123ABC_1280x720_frag.mp4 CAPTURE_123ABC_640x360_frag.mp4</pre><p>After running this command, the files will be segmented and encrypted at the same time.</p><p>If you try to open any of the files you will see the following: “Protected videos can only be played using…”</p><p>Within the manifest.mpd, there will be extra tags to inform the player of what DRM(s) can be used to obtain the decryption keys for the stream.</p><pre>&lt;?xml version=&quot;1.0&quot; ?&gt;<br>&lt;MPD xmlns:cenc=&quot;urn:mpeg:cenc:2013&quot; xmlns:mas=&quot;urn:marlin:mas:1–0:services:schemas:mpd&quot; xmlns=&quot;urn:mpeg:dash:schema:mpd:2011&quot; profiles=&quot;urn:mpeg:dash:profile:isoff-live:2011&quot; minBufferTime=&quot;PT1.00S&quot; mediaPresentationDuration=&quot;PT4.004S&quot; type=&quot;static&quot;&gt;<br>&lt;! - Created with Bento4 mp4-dash.py, VERSION=2.0.0–639 →<br>&lt;Period&gt;<br>&lt;! - Video →<br>&lt;AdaptationSet mimeType=&quot;video/mp4&quot; segmentAlignment=&quot;true&quot; startWithSAP=&quot;1&quot; maxWidth=&quot;1920&quot; maxHeight=&quot;1080&quot;&gt;<br>&lt;! - MPEG Common Encryption →<br>&lt;ContentProtection schemeIdUri=&quot;urn:mpeg:dash:mp4protection:2011&quot; value=&quot;cenc&quot; cenc:default_KID=&quot;121a0fca-0f1b-475b-8910–297fa8e0a07e&quot;/&gt;<br>&lt;! - Marlin →<br>&lt;ContentProtection schemeIdUri=&quot;urn:uuid:5E629AF5–38DA-4063–8977–97FFBD9902D4&quot;&gt;<br>&lt;mas:MarlinContentIds&gt;<br>&lt;mas:MarlinContentId&gt;urn:marlin:kid:121a0fca0f1b475b8910297fa8e0a07e&lt;/mas:MarlinContentId&gt;<br>&lt;/mas:MarlinContentIds&gt;<br>&lt;/ContentProtection&gt;<br>&lt;SegmentTemplate timescale=&quot;1000&quot; duration=&quot;1001&quot; initialization=&quot;$RepresentationID$/init.mp4&quot; media=&quot;$RepresentationID$/seg-$Number$.m4s&quot; startNumber=&quot;1&quot;/&gt;<br>&lt;Representation id=&quot;video/avc1/1&quot; codecs=&quot;avc1.640028&quot; width=&quot;1920&quot; height=&quot;1080&quot; scanType=&quot;progressive&quot; frameRate=&quot;30000/1001&quot; bandwidth=&quot;6326921&quot;/&gt;<br>…<br>&lt;/AdaptationSet&gt;<br>&lt;/Period&gt;<br>&lt;/MPD&gt;</pre><p><strong>2. Another example using Google Widevine DRM, in order to dashify and encrypt at the same time use the — widevine flags.</strong></p><pre>mp4dash — mpd-name manifest.mpd — widevine-header “#CAESEJA1GVFoa14boiJDns7B8SoaDXdpZGV2aW5lX3Rlc3QiASo=” — encryption-key 90351951686b5e1ba222439ecec1f12a:0a237b0752cbf1a827e2fecfb87479a2 CAPTURE123ABC_1920x1080_frag.mp4 CAPTURE123ABC_1280x720_frag.mp4 CAPTURE123ABC_640x360_frag.mp4```</pre><p>And the manifest will have the following tags inside for the player to find.</p><pre>&lt;! — MPEG Common Encryption →<br>&lt;ContentProtection schemeIdUri=&quot;urn:mpeg:dash:mp4protection:2011&quot; value=&quot;cenc&quot; cenc:default_KID=&quot;90351951–686b-5e1b-a222–439ecec1f12a&quot;/&gt;<br>&lt;! - Widevine →<br>&lt;ContentProtection schemeIdUri=&quot;urn:uuid:edef8ba9–79d6–4ace-a3c8–27dcd51d21ed&quot;&gt;<br>&lt;cenc:pssh&gt;AAAARnBzc2gAAAAA7e+LqXnWSs6jyCfc1R0h7QAAACYIARIQkDUZUWhrXhuiIkOezsHxKhoNd2lkZXZpbmVfdGVzdCIBKg==&lt;/cenc:pssh&gt;<br>&lt;/ContentProtection&gt;</pre><p>If you want to do encryption in a specific way, you can use <em>*mp4encrypt*</em> instead. For example, If you need more precise control over encryption (for example only encryption certain tracks and not others, or use special options), you can encrypt the media before using mp4dash. This is done by calling mp4encrypt directly on the input files before calling mp4dash</p><pre>mp4encrypt — method MPEG-CENC — key 1:a0a1a2a3a4a5a6a7a8a9aaabacadaeaf:0123456789abcdef — property 1:KID:121a0fca0f1b475b8910297fa8e0a07e — key 2:a0a1a2a3a4a5a6a7a8a9aaabacadaeaf:aaaaaaaabbbbbbbb — property 2:KID:121a0fca0f1b475b8910297fa8e0a07e CAPTURE123ABC_1920x1080_frag.mp4 CAPTURE456DEF_1920x1080_frag.mp4</pre><p>See more details:</p><p>[Encryption &amp; DRM — Bento4](https://www.bento4.com/developers/dash/encryption_and_drm/)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d48d39ab5f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiple environment files in a Next.js app (optional + with docker)]]></title>
            <link>https://jujuontheweb.medium.com/multiple-environment-files-in-a-next-js-app-optional-with-docker-4603a0423a51?source=rss-f8e8ba70a756------2</link>
            <guid isPermaLink="false">https://medium.com/p/4603a0423a51</guid>
            <category><![CDATA[nextjs-tutorial]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[environment-variables]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Jumanah Al Asadi]]></dc:creator>
            <pubDate>Thu, 09 Dec 2021 15:58:20 GMT</pubDate>
            <atom:updated>2021-12-09T15:58:20.940Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a next.js app with different environment files, docker, dotenv</p><p>The most recent official documentation from Nextjs for adding environment variables in a next.js app points to creating an <strong>.env.local</strong> file at the root of your project and defining key values in there.</p><p>One rule is that if they need to start with the word <strong>NEXT_PUBLIC_ </strong>in order to be available in the front-end / browser. For example, inside of .env.local</p><pre>NEXT_PUBLIC_API=<a href="http://localhost:9000/api">http://localhost:9000/api</a></pre><p>Another catch is that.. well.. environment variables will only be added at <strong>build</strong> time, not run time. So they must be set and available at build time. Don’t bother setting, changing them at run time, it won’t work (unless with some hacky way I haven’t figured out yet).</p><p>And with that said, you’re done, you don’t need to install dotnet or anything like that, the nextjs app will automatically look for this file when building. Just start the app and you will see a message like, “pulled environment variables from .env.local”!</p><p>If you only wish to build with this single file, and you have only one environment or two, you’re good to go. You don’t need anything in next.config either.</p><p>The second you have <strong>many</strong> <strong>environments</strong> and you’d like to build for staging, test, development and production etc.. you are likely to need multiple environment files with different values, like: .env.prod, .env.staging ..etc. Nextjs has confusing documentation for this, and albeit it did not work for me. I had to dig around for solutions online, and I finally got one working.</p><p>So I found this workaround, and it works great! Follow these steps below to get it working. Don’t worry it’s not too difficult! Finding these steps were difficult though 🤓…</p><h4>Create environment files</h4><p>Let’s assume we have a three environments:</p><ul><li>local</li><li>testing</li><li>prod</li></ul><p>Let’s delete the .env.local file we had initially created, if we had one.</p><p>Then we start by creating an <strong>env</strong> folder in the root of the project. Inside this folder, create create 3 new environment files:</p><pre>env /</pre><pre>.env.local</pre><pre>.env.prod</pre><pre>.env.testing</pre><p>Don’t forget to add these files to our .gitignore so we never push them to Github or Bitbucket..</p><p>In each file, populate your environment variables with different values.</p><h4>Install packages</h4><p>To complete this solution, we need to install two npm packages, npm install dotenv</p><p>and npm install env-cmd they will help us add our own environment system. You may be already familiar with dotenv as it’s quite popular for implementing environment files.</p><h4>Modify Next.config.js</h4><p>The next.config.js file is a file where you can add custom configuration to your nextjs app. If you don’t have this file already, please create it at the root of your project.</p><p>Add the following code inside of it.</p><pre>require(&#39;dotenv&#39;).config()<br>const webpack = require(&#39;webpack&#39;)</pre><pre>module.exports = {<br>  webpack: (config) =&gt; {<br>    config.plugins.push(<br>      new webpack.EnvironmentPlugin(process.env)<br>    )<br>    return config<br>  }<br>}</pre><p>We’re almost done!</p><h4>Add build scripts</h4><p>Now we need a way to build the app, with different environment files. Since environment variables are added at build time, we need to run the build command with a specific environment file. We can use<strong> env-cmd </strong>to do this.</p><p>Let’s modify the scripts inside package.json, and add some new build scripts.</p><p>As you can see I added three new build scripts! Using <strong>env-cmd </strong>will allow us to point to an environment file when building. So we pass it the path of the file, which is located in the env folder we just created.</p><pre>&quot;scripts&quot;: {<br>    <strong>&quot;dev&quot;: &quot;env-cmd -f env/.env.local next dev&quot;,</strong><br>    &quot;build-dev&quot;: &quot;next build&quot;,<br>    &quot;build&quot;: &quot;next build&quot;,<br>    &quot;start&quot;: &quot;next start&quot;,<br>    &quot;lint&quot;: &quot;eslint --fix --ext .js .&quot;,<br><strong>    &quot;build:prod&quot;: &quot;env-cmd -f env/.env.prod yarn build&quot;,<br>    &quot;build:test&quot;: &quot;env-cmd -f env/.env.test yarn build&quot;,<br>    &quot;build:local&quot;: &quot;env-cmd -f env/.env.local yarn build&quot;</strong><br>  },</pre><p>The default build command for a production build, is <strong>next build</strong>, and<strong> next dev</strong> for a development / hot reloading building on the fly / server.</p><p>For this reason, I also added the pointer to the local environment file for running the dev command to start the app in development mode on localhost. This means we will use the env.local file when we run the following command:</p><pre>yarn dev</pre><p>Now we have covered all situations.</p><h4>Basic Usage</h4><p>So to build and run your app in a production environment you can use:</p><pre>yarn build:prod </pre><p>To build in test mode, you can use:</p><pre>yarn build:test</pre><p>Then to start the application you just built, you can use</p><pre>yarn start</pre><h4>Docker usage</h4><p>If you would like to build your app via docker and deploy it as a container somewhere, keep on reading..</p><p>Create a Dockerfile at the root of your project: By the way, this was stolen from <a href="https://nextjs.org/docs/deployment#docker-imagehttps://nextjs.org/docs/deployment#docker-image">https://nextjs.org/docs/deployment#docker-imagehttps://nextjs.org/docs/deployment#docker-image</a> and modified slightly.</p><pre># Install dependencies only when needed<br>FROM node:16.8.0-alpine AS deps</pre><pre># Check <a href="https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine">https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine</a> to understand why libc6-compat might be needed.<br># Open issue <a href="https://github.com/facebook/create-react-app/issues/11565">https://github.com/facebook/create-react-app/issues/11565</a><br>RUN apk add --no-cache libc6-compat<br>WORKDIR /app<br>COPY package.json ./<br>RUN yarn install --frozen-lockfile</pre><pre># Rebuild the source code only when needed<br>FROM node:16.8.0-alpine  AS builder<br>WORKDIR /app<br>COPY . .<br>COPY --from=deps /app/node_modules ./node_modules<br>ARG BUILDCOMMAND=build:local-kb<br>RUN yarn $BUILDCOMMAND &amp;&amp; yarn install --production --ignore-scripts --prefer-offline</pre><pre># Production image, copy all the files and run next<br>FROM node:16.8.0-alpine  AS runner<br>WORKDIR /app</pre><pre>ENV NODE_ENV production</pre><pre>RUN addgroup -g 1001 -S nodejs<br>RUN adduser -S nextjs -u 1001</pre><pre># You only need to copy next.config.js if you are NOT using the default configuration<br># COPY --from=builder /app/next.config.js ./<br>COPY --from=builder /app/public ./public<br>COPY --from=builder --chown=nextjs:nodejs /app/.next ./.next<br>COPY --from=builder /app/node_modules ./node_modules<br>COPY --from=builder /app/package.json ./package.json</pre><pre>USER nextjs</pre><pre>EXPOSE 3000</pre><pre># Next.js collects completely anonymous telemetry data about general usage.<br># Learn more here: <a href="https://nextjs.org/telemetry">https://nextjs.org/telemetry</a><br># Uncomment the following line in case you want to disable telemetry.<br># ENV NEXT_TELEMETRY_DISABLED 1</pre><pre>CMD [&quot;yarn&quot;, &quot;start&quot;]</pre><p>Normally you can just build a docker file without anything else. But I have modified this docker file to accept an arg, to make it customizable, so we can run the different build commands we just created in package.json.</p><p>So to build an image from this docker file, you can pass an argument which will tell the docker file what kind of environment you want to build for.</p><p>To build a specific environment pass the build-arg <strong>BUILDCOMMAND</strong>. There is also a default value present in the docker file if you don’t pass this. This arg was named by myself, feel free to change its name!</p><p>We can pass either: build:local, build:prod, build:test, the ones we defined in our package.json scripts. If you added more, go for it!</p><p>Example:</p><pre>docker build -t next-app --build-arg BUILDCOMMAND=build:prod --no-cache .</pre><p>Then we can run our docker image as a container</p><pre>docker run -p 3000:3000 next-app</pre><p>That’s it! Thanks for reading ^_^</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4603a0423a51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Firebase Database + RestAPI to React App]]></title>
            <link>https://jujuontheweb.medium.com/adding-firebase-database-restapi-to-react-app-8e8ba8d6422e?source=rss-f8e8ba70a756------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e8ba8d6422e</guid>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Jumanah Al Asadi]]></dc:creator>
            <pubDate>Mon, 15 Nov 2021 02:40:31 GMT</pubDate>
            <atom:updated>2021-12-24T02:14:09.405Z</atom:updated>
            <content:encoded><![CDATA[<p>Using the latest version of Firebase SDK. 9+.</p><p>Start by creating a free, google account. Then open the following link to create a new Google Firebase project. The account will be under Google’s Spark plan which is 100% free.</p><p>Click get started. <a href="https://firebase.google.com/">https://firebase.google.com/</a>. Follow the steps. You need to be signed in to your google account. This project will be created under your google account (gmail).</p><h3>Firebase Set Up</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MnwOOB1wSB4a2KZzN8Dq8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tksv3uzknl7YeeIfV1gO2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TDnxi6X-E4AN2e-2dFGMLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9iP_5mRwE6lQuidxSSnqng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MElYDhs175GyMZXybJQjIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kDUYovnxZUYhwmt8DnIS0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*FizEZOChLB_8VGJ3VlGWCg.png" /></figure><p>After you are done going through the wizard to create a new project. You will need to add “Firebase firestore” in this project. Firestore is a scalable noSQL database on the cloud. Since Firebase has a ton of other features like authentication, you can add a Database, Cloud Storage, etc. But for now, only add the Firestore Database.</p><p>Click create database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZaumixakxYvS0aZyun0-Pw.png" /></figure><p>Follow the instructions. Select<strong> test mode</strong> for now. Then choose a location, anything in north america will be fine for our purposes. We can switch to production mode at the end of this tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7bEQhrCMKzPlRxrndL5tFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmy_ZlNK_v1WkZjiDpI47A.png" /></figure><p>Once ready, you can now create a table, or a collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxbQP0RtwHotxkEBV4HCtA.png" /></figure><p>Click start collection, and enter the name of your data, for example pets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d2mrRH9lLxnMxCfKA_BVMQ.png" /></figure><p>Click auto id, to auto generate an ID. This will be non repeatable and completely unique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*92H3hvMGxjowFadHGa9-dw.png" /></figure><p>Then start by adding your first pet. They are called documents. Choose your data, and their data types.</p><ul><li>column name</li><li>type: number, string, boolean ..etc</li><li>value: ..</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-PvTh-HftUc1kgAWGZv01w.png" /></figure><p>To add more, click add Document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*r7UqGITZNNHyHX193KWH0g.png" /></figure><p>To edit existing documents, you can select them by clicking on them, and click the add field button.</p><p>You can also edit values using the pencil icon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSc-VYW0kx-dYtGyX6PS9w.png" /></figure><p>The firestore database automatically can give you a FREE simple API to use. Since your data is in test mode, it is public.</p><p>All you need is your project id. You can grab that from the project settings.</p><p>ex. pet-store-a6611</p><p>Then plop it into this default API url:</p><p><a href="https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/">https://firestore.googleapis.com/v1/projects/<strong>PROJECTID</strong>/databases/(default)/documents/pets/</a></p><p>Ex.</p><p><a href="https://firestore.googleapis.com/v1/projects/pet-store-a6611/databases/(default)/documents/pets/">https://firestore.googleapis.com/v1/projects/<strong>pet-store-a6611</strong>/databases/(default)/documents/pets/</a></p><p>And that will give us a list of all our documents..we can use this JSON object inside our react app!</p><p>Using fetch we can call the API and we will get this data back.</p><p>GET Request</p><pre>const response = await fetch(“<a href="https://firestore.googleapis.com/v1/projects/pet-store-a6611/databases/(default)/documents/pets/">https://firestore.googleapis.com/v1/projects/pet-store-a6611/databases/(default)/documents/pets/</a>”);<br>const data = await response.JSON();</pre><pre>console.log (data);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JgLIxRMAAxecNTOXz7Yylw.png" /></figure><p>POST Request</p><pre>const response = await fetch(“<a href="https://firestore.googleapis.com/v1/projects/pet-store-a6611/databases/(default)/documents/pets/">https://firestore.googleapis.com/v1/projects/pet-store-a6611/databases/(default)/documents/pets/</a>”,<br>{<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;<br>    },<br>    method: &quot;POST&quot;,<br>    body: data<br>})</pre><p>where data is a JSON object, that follows the following syntax. JSON.stringify can be used.</p><pre>const data = {<br>    &quot;fields&quot;: {<br>        &quot;id&quot;: {<br>            &quot;stringValue&quot;: &quot;3&quot;<br>        },<br>        &quot;breed&quot;: {<br>            &quot;stringValue&quot;: &quot;ragdoll&quot;<br>        },<br>        &quot;age&quot;: {<br>            &quot;stringValue&quot;: &quot;3 years&quot;<br>        },<br>        &quot;name&quot;: {<br>            &quot;stringValue&quot;: &quot;Luna&quot;<br>        }<br>    }<br>}</pre><h3>Securing your firebase API</h3><p>After 30 days, your test mode will expire. Therefore navigate to the rules section and update it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4wHLoIPsZvvBccIKav_5Q.png" /></figure><p>As you can see it will stop allowing you access the database after a certain time. The new rule should allow indefinitely for only logged in users. In order to do this you must add a login and sign up page to your application.</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    match /{document=**} {<br>      allow read, write: if request.auth != null;<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2WUU_PfHdQg7Pyrul2QJrA.png" /></figure><p>There are more rules you can put below, such as restricting the user to only seeing documents if they are the ones who created it. But the above will do for our purposes.</p><p><a href="https://firebase.google.com/docs/rules/basics?authuser=0">Basic Security Rules | Firebase Documentation</a></p><p>Click publish, and wait a few minutes.</p><h4>First, add <a href="http://authentication/">authentication</a> using Firebase to your application. Please follow my other tutorial before continuing.</h4><p>Now when sending requests, you must send something special with the request.</p><p>Each user logged into Firebase, inside your application will have their own temporary access token. It is like a ticket to access secure data.</p><p>In order to do use the token, we first get it from user.accessToken. We can get the user who is logged in using getAuth.</p><pre>const user = getAuth().currentUser;<br>const token = user.accessToken;</pre><p>We need to pass the user’s token inside our GET, POST ..etc requests. To do so we use the request options. We first create our options object, and inside we add headers. Inside headers we create an Authorization property. This needs to have a value of</p><pre>“Bearer &lt;token&gt;” </pre><p>So all together:</p><pre>const requestOptions = {<br>     headers: {<br>         <strong> &#39;Authorization&#39;: &#39;Bearer&#39; + &#39; &#39; + user.accessToken,</strong><br>     },<br>  };</pre><p>Then right under, we pass our requestOptions as a second argument to the fetch method. (API URL, options).</p><pre>const response = await fetch(&#39;<a href="https://firestore.googleapis.com/v1/projects/itec-round2/databases/(default)/documents/pets/&#39;,">https://firestore.googleapis.com/v1/projects/pet-store/databases/(default)/documents/pets/&#39;,</a> <strong>requestOptions</strong>);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e8ba8d6422e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Firebase Authentication to React App]]></title>
            <link>https://jujuontheweb.medium.com/adding-firebase-authentication-to-react-app-3b42685a5d8d?source=rss-f8e8ba70a756------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b42685a5d8d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[firebaseauthentication]]></category>
            <dc:creator><![CDATA[Jumanah Al Asadi]]></dc:creator>
            <pubDate>Sun, 14 Nov 2021 22:18:40 GMT</pubDate>
            <atom:updated>2021-11-15T00:48:48.612Z</atom:updated>
            <content:encoded><![CDATA[<p>Using the latest version of Firebase SDK. 9+. Using React.js create react app. Showing examples of login, sign up, logout, check currentUser.</p><p>Start by creating a free, google account. Then open the following link to create a new Google Firebase project. The account will be under Google’s Spark plan which is 100% free.</p><p>Click get started. <a href="https://firebase.google.com/">https://firebase.google.com/</a>. Follow the steps. You need to be signed in to your google account. This project will be created under your google account (gmail).</p><h3>Firebase Set Up</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MnwOOB1wSB4a2KZzN8Dq8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tksv3uzknl7YeeIfV1gO2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TDnxi6X-E4AN2e-2dFGMLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9iP_5mRwE6lQuidxSSnqng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MElYDhs175GyMZXybJQjIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kDUYovnxZUYhwmt8DnIS0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*FizEZOChLB_8VGJ3VlGWCg.png" /></figure><p>After you are done going through the wizard to create a new project. You will need to add “Firebase authentication” in this project. Since Firebase has a ton of other features in addition to authentication, you can add a Database, Cloud Storage, etc. But for now, only add the Authentication.</p><p>When going through this next wizard, I chose the basic email and password option, but you can add any other form of sign in, like sign in with Facebook or Google.. These will not be covered in this tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_782Qq2YYK_UCVW7WwCXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqjFtIk5eSMj7QKrwNSf4g.png" /></figure><p>Then you must create a link to your react app from Firebase. By doing this, it will create new credentials and a configuration for you to paste in your React app so you can access this specific instance of Firebase from your react app.</p><p>To accomplish this, open your project settings, and click add a web app, the &lt;/&gt; icon and fill out the instructions, like choosing a name and analytics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbgzdcbsAjmo8LDzk4ziVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-NQZ01dhi-l4G5ilA-ufxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sA4NU1jY1E-to3tigjAPpw.png" /></figure><p>The end result will be credentials for your react app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3code3BQNCnDPfF1DYUQA.png" /></figure><p>Copy paste this entire blob of code to your react app. Of course you should put all secret data in their environment variables, but for now, let’s just pretend we did that.</p><ul><li>Create an .env file</li><li>Create variables for all the items, REACT_APP_API_KEY ..etc and so on</li><li>Refer to them as process.env.REACT_APP_API_KEY</li></ul><p>Before copying this code, we should install firebase (the newest version). This way we can initialize Firebase in our React app.</p><pre>npm install firebase</pre><p>We can copy all this code from the previous step, supplied to us from the end of the wizard.</p><p>Inside of<strong> index.js</strong>, just above the ReactDOM.render statement, there we can call the initializeApp function with the credentials we have. Don’t forget to put this data instead in .env file and never push them to Github or Bitbucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*QwyTRxSca-QvN1yH3w1E2w.png" /></figure><p>Now we are ready to use our Firebase instance. The configuration is all set up :-)</p><h3>Log in + Sign Up + Log Out examples</h3><p>*Don’t forget to install the Firebase SDK into your project. Alright let’s do this :)</p><p>We can start by creating a login, and sign up page in our application. Add them using react-router-dom and create components for them. Add the following routes.</p><ul><li>/login</li><li>/signup</li></ul><p>In these pages, we can build a form, that will call the functions to authenticate into Firebase.</p><p>We will import them when necessary:</p><pre>import {<br>  getAuth,<br>  createUserWithEmailAndPassword,<br>  signInWithEmailAndPassword,<br>  signOut</pre><pre>} from &quot;firebase/auth&quot;;</pre><p><strong>Let’s start with the LoginPage component:</strong></p><p>A simple form, with no validation, just to illustrate the integration of Firebase. We store the username and password in the state variables. On Submit, we call a function called <strong>loginUser </strong>that I created.</p><pre>     &lt;form onSubmit={loginUser}&gt;<br>        &lt;label htmlFor=&quot;user&quot;&gt; Email &lt;/label&gt;<br>        &lt;input<br>          onChange={(event) =&gt; {<br>            setUsername(event.target.value);<br>          }}<br>          name=&quot;user&quot;<br>          required<br>        /&gt;<br>        &lt;label htmlFor=&quot;password&quot;&gt; Password &lt;/label&gt;<br>        &lt;input<br>          onChange={(event) =&gt; {<br>            setPassword(event.target.value);<br>          }}<br>          name=&quot;password&quot;<br>          type=&quot;password&quot;<br>          required<br>        /&gt;<br>        &lt;input name=&quot;login&quot; type=&quot;submit&quot; value=&quot;login&quot; /&gt;<br>      &lt;/form&gt;</pre><p>The loginUser function can look like this. It will call the signInWithEmailAndPassword method from Firebase Auth. We pass it the username and password.</p><pre>import {<br>  getAuth,<br>  createUserWithEmailAndPassword,<br>  signInWithEmailAndPassword,<br>} from &quot;firebase/auth&quot;;<br>import { useState } from &quot;react&quot;;</pre><pre>export const LoginPage = () =&gt; {<br>  const [username, setUsername] = useState(&quot;&quot;);<br>  const [password, setPassword] = useState(&quot;&quot;);</pre><pre>const <strong>loginUser</strong> = async(event) =&gt; {<br>    <br>    event.preventDefault();<br>    const auth = getAuth();<br>    try {<br>        const user = await signInWithEmailAndPassword(auth,  username, password);<br>        console.log (&quot;User logged in&quot;, user);<br>        history.push(&#39;/&#39;);</pre><pre>    } catch (error) {<br>        const errorCode = error.code;<br>        console.log (&quot;Error&quot;, errorCode);<br>    } <br>};</pre><p>If this works, you can store the current user in a global state, if you like. Otherwise you can redirect the user into the secured part of your application.</p><p>This will display an error if the user doesn’t exist. Which is why we will build the sign up functionality next.</p><p><strong>Let’s create the SignUpPage component:</strong></p><p>A simple form, with no validation, just to illustrate the integration of Firebase. We store the username and password in the state variables. On Submit, we call a function called <strong>signUpUser, </strong>a function I have created<strong>.</strong></p><pre>      &lt;form onSubmit={signUpUser}&gt;<br>        &lt;label htmlFor=&quot;user&quot;&gt; Email &lt;/label&gt;<br>        &lt;input<br>          onChange={(event) =&gt; {<br>            setUsername(event.target.value);<br>          }}<br>          name=&quot;user&quot;<br>          required<br>        /&gt;<br>        &lt;label htmlFor=&quot;password&quot;&gt; Password &lt;/label&gt;<br>        &lt;input<br>          onChange={(event) =&gt; {<br>            setPassword(event.target.value);<br>          }}<br>          name=&quot;password&quot;<br>          type=&quot;password&quot;<br>          required<br>        /&gt;<br>        &lt;input name=&quot;submit&quot; type=&quot;submit&quot; value=&quot;sign up&quot; /&gt;<br>      &lt;/form&gt;</pre><p>Sign up user, will look like this. It will call the createUserWithEmailAndPassword method from Firebase Auth. We pass it the username and password. It will return the new user, it creates.</p><pre>import {<br>  getAuth,<br>  createUserWithEmailAndPassword,<br>  signInWithEmailAndPassword,<br>} from &quot;firebase/auth&quot;;<br>import { useState } from &quot;react&quot;;</pre><pre>export const SignInPage = () =&gt; {<br>  const [username, setUsername] = useState(&quot;&quot;);<br>  const [password, setPassword] = useState(&quot;&quot;);</pre><pre>const <strong>signUpUser</strong> = async (event) =&gt; {<br>    event.preventDefault();<br>    const auth = getAuth();<br>    try {<br>        const user = await createUserWithEmailAndPassword(auth, username, password);<br>        console.log (&quot;New user created&quot;, user);<br>    } catch (error) {<br>        const errorCode = error.code;<br>        console.log (&quot;Error&quot;, errorCode);<br>    }  <br>  };</pre><p>At this point we may auto log the user in, and route the user to the home page, or alternatively we can route them to the login page, where they must login with their new account.</p><p><strong>Let’s create the Logout component:</strong></p><p>In the case that you need to logout a user from Firebase, you can make a log out component, which calls the the logout method. You can put this component in your navigation.</p><p>Anywhere else you need to logout the user, you can call the signOut function from firebase.</p><p>This will clear the current user logged in from the Firebase instance.</p><pre>import { getAuth, signOut, onAuthStateChanged } from &quot;firebase/auth&quot;;<br>import { useEffect, useState } from &quot;react&quot;;<br>import { useHistory } from &#39;react-router-dom&#39;;</pre><pre>import &#39;./styles.css&#39;<br>export const Logout = () =&gt; {<br>    const history = useHistory();<br>    const [user, setUser] = useState(null);</pre><pre>useEffect(<br>        () =&gt; {<br>            const auth = getAuth();<br>            onAuthStateChanged(auth, (user) =&gt; {<br>                if (user) {<br>                    setUser(auth.currentUser)<br>                } else {<br>                    setUser(null)<br>                }<br>            });<br>              <br>        }, []<br>    )</pre><pre>const <strong>logoutUser</strong> = async () =&gt; {<br>        const auth = getAuth();<br>        try {<br>            await <strong>signOut</strong>(auth);<br>            history.push(&#39;/login&#39;)<br>        } catch (error) {<br>            console.log (error)<br>        }<br>    }</pre><pre>return (<br>        user &amp;&amp; &lt;button className=&quot;logout-btn&quot; onClick={logoutUser}&gt; Logout &lt;/button&gt;<br>    )<br>}</pre><p>After doing so, we may push the user back to the login screen. We should also clear any local storage or global state we have, and set our app’s current user to null, if we have one.</p><h3><strong>Check if a user is logged in + Protecting a page from unauthenticated users</strong></h3><p><strong>Getting current user</strong></p><p>To check if a user is logged in we can always get that information from getAuth. An example on a page is:</p><p>We can also push them to the login page, if we see that there is no current user present in the firebase instance.</p><p>If there is a current user, the way to clear this is by calling the Firebase signOut method. Otherwise, we may simply grab the access token, email, and other info about the user from the getAuth() method, ex. if we wish to greet the user by their display name, or photo.</p><pre>import { getAuth, signOut, onAuthStateChanged } from &quot;firebase/auth&quot;;</pre><pre>import { useEffect, useState } from &quot;react&quot;;<br>import { useHistory } from &#39;react-router-dom&#39;;</pre><pre>import &#39;./styles.css&#39;</pre><pre>export const HomePage = () =&gt; {</pre><pre>const history = useHistory();<br>  const [user, setUser] = useState(null);  <br>  <br>  useEffect(<br>        () =&gt; {<br>            const auth = getAuth();<br>            onAuthStateChanged(auth, (user) =&gt; {<br>                if (user) {<br>                    setUser(auth.currentUser)<br>                } else {<br>                    setUser(null);<br>                    history.push(&#39;/login&#39;);</pre><pre>                }<br>            });<br>              <br>        }, []<br>    )<br>}, []);</pre><p>We can also grab the token from here incase we wish to send it with requests to a secured API.</p><p>Here is an example of the data you can get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kJRzRPA24fgVyjx7p7Sd9g.png" /></figure><p>At any time, you may view your signed up users in the Firebase console:</p><ul><li>You can see when they last logged in</li><li>Their sign up method</li><li>Their user id</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OxJbCR7-F0gg5bcRDD_Pg.png" /></figure><h3><strong>Next steps</strong></h3><ul><li>You can protect your React app by storing the logged in user, in a user — context or redux (global state), and check if there is no logged in user, you can boot the unauthenticated user from your application, and route them to the login page</li><li>Create a fancy sign up page, or integrate the Firebase pre-built UI, so you don’t have to make your own sign up and login components from scratch.</li><li>Add / allow other sign in methods (google, facebook, etc)</li><li>Support: <a href="https://firebase.google.com/docs/auth/web/password-auth">https://firebase.google.com/docs/auth/web/password-auth</a></li></ul><p>Thanks for reading :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b42685a5d8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple introduction to authenticating with JWT, JSON Web Tokens, Access tokens]]></title>
            <link>https://jujuontheweb.medium.com/simple-introduction-to-jwt-tokens-3f8d1a7ba880?source=rss-f8e8ba70a756------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f8d1a7ba880</guid>
            <category><![CDATA[jwt-authentication]]></category>
            <dc:creator><![CDATA[Jumanah Al Asadi]]></dc:creator>
            <pubDate>Wed, 10 Nov 2021 20:58:49 GMT</pubDate>
            <atom:updated>2021-11-15T16:37:25.794Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is about authentication, the difference between sessions and JWT, Json Web tokens, and how the structure looks like.</p><p>What is basic user authentication? Simple. The user creates an account, then logs into an application by entering their email and password. Then they can enter the site, and view more pages without logging in again.</p><p>Before JWT, in the past, yes, users would still login to the app with their email and password, the server will verify the credentials and will store a <strong>session id</strong> for that user in the server’s database. This ID will contain a reference to a table with more info about the user, when they logged in, session expiry time etc.</p><p>The server will give this session ID to the user, the first time. Then the user would send this session ID (which can be stored in the browser 🍪) to the server, to authenticate instead of sending their username and password again and again with every request. Then the server will lookup the session ID and see if it is still valid. If it is, it will say yes to the request. ✅</p><p>As long as it has not expired yet, the user can keep sending requests with this session id. But every time a session ID is sent, the server needs to check its own records for that session id, in a database. This means the server store the session ids is the only server that can authenticate the users requests.</p><p>That is a problem when you are scaling, with multiple servers, and a load balancer. 😥 This means that if your load balancer directs the user to a different server, server B, well then that server might not know about that session ID, since the session ID was first stored on server A.</p><p>🖥 🖥 🖥</p><p>So to solve this problem.. JWT came into the picture. Users still login with their username and password, but what happens after is slightly different.</p><p>With JSON web tokens, users still would login to the app, with their email and password, but instead of receiving a session id from a server, the server will send the user a JSON web token. Think of the JSON web token as an <strong>encoded 🔏 </strong>string that has information about who the user is, and when the token expires. The user would need to send this JSON web token with every subsequent request after logging in. Then any server would know who that user is and let them in. For example the JSON web token could have information like:</p><ul><li>user id</li><li>expiry time</li></ul><p>This token is not stored on the server that issued the token!!! But you might be wondering, hmm. I guess this is easy to hack, I can make my own token and encode it with the same information, and pass it to the server to get in.. 🤖 The server wouldn’t know, since it never stored it on its records.</p><p>Dun dun dana…NO. ⚔️ the JSON web token is built in such a way that, it does not need to be stored on the server that issued the token. This is because, before the server sends out the token to the user, it autographs it. 😉 🖊</p><p>This is more formally called “signing the token” . This is how the token becomes impossible to re-create unless it knows the secret autograph. When the server signs the token with something called a “secret” key, unless a hacker knows what that secret key is, they cannot make the same token.</p><p>Ok, you might be wondering, how does this mysterious token look like. When it is encoded, it is just an arbitrary string of characters, separated by dots. There are three parts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1dl_fwlrYVIZW4x-.png" /></figure><p>When it is decoded, it will give you information about the algorithm used to make the token, info about the user (payload), and the type of signature, without revealing the secret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vgICsMDmpUzKLUvu.png" /></figure><p>More formally, there is going to be a <strong>header</strong> which describes the <strong>algorithm</strong> (ex. HS256)<strong> </strong>you used to encode your JWT token, and the <strong>payload</strong> which is the information you are storing on the token, like the username, user id, token expiry, etc. Any data can be here. Do not put sensitive data in here.</p><p>Then lastly, is the <strong>signature</strong>, this is how all your servers will verify that your JWT token is actually valid. The signature requires a “<strong>secret key</strong>”, to create its signature. If the payload part in the JWT has been changed or messed around with, the signature immediately becomes invalid. Other servers can only generate valid tokens if they found out our secret key 😱, that is why you must store it securely.</p><p><em>Note: The JSON web token is not encrypted. So any information that we put in the token is still readable to anyone who decodes the first two parts of the token. So important not to put in the Payload any user information that an attacker could leverage directly, like user password, DOB.</em></p><p>After getting this token then, the user takes the signed JWT and starts sending it with each HTTP request. The JSON web token, acts as a temporary user credential (until it expires). Without forcing the password to be sent each time with the request.</p><p>Whenever the user wants to access a protected route or API, the user should send the JWT, typically in the Authorization header using the Bearer schema.</p><p>Authorization: “Bearer <strong>&lt;token&gt;”</strong></p><p>The server’s protected routes will check for a valid JWT in the Authorization header, and if it exists and is validated, the user will be allowed to access protected resources.</p><p><strong>More on the secret key..</strong></p><p>The secret key is a significant part of how your tokens will be generated. The secret key will be an integral part of the signature. That same secret key will also be used to verify and validate an incoming JWT token. Therefore the server issuing the token and servers validating the token need to get ahold of this secret key.</p><p>The signature portion of the token is composed of = secret key + payload + header</p><p>The token can only be issued by knowing the secret key. So if you change the token contents, without knowing the secret key, the signature will become invalid, therefore the JWT token will be invalid. The server would then reject your request.</p><p>If you are using distributed systems, then all your services need to know this secret key. This can be risky, since the secret key can be compromised.</p><p>Therefore, it might be a good idea to use RSA Keys.</p><p>RSA Keys, where you get two keys, as a pair, one private key and one public key where both are generated using cryptographic algorithms. The private key is only used by one server to generate new tokens.</p><p>Then the rest of the servers, that need to validate or verify the token is valid, can use the public key.</p><p>Public keys, to decode the token you don’t need the secret key.</p><p>Ssh-keygen can be used to, to create an RSA key.. It will create public and private key.</p><ul><li>You have a private key: Jwt-key</li><li>And a public key: Jwt-key.pub</li></ul><p>Now any server that needs to verify tokens will use jwt-key.pub and this file can be shared around. The private key on the other hand should be protected with your life.</p><p>Now only when you need to generate jwt tokens you can use the private key.</p><pre>jwt.encode(payload, private_key, algorithm=[“RS256”])</pre><p>To decode and validate jwt tokens, you do not need the extremely secure private key, you can use the public jwt-key.pub, which is encrypted.</p><pre>jwt.decode(token, public_key, algorithms=[‘RS256’])</pre><p>Now anybody can verify the token, but nobody can generate the token! 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f8d1a7ba880" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React API tutorial — building a mini products page and adding to order]]></title>
            <link>https://jujuontheweb.medium.com/react-api-tutorial-b4d9354c95dd?source=rss-f8e8ba70a756------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4d9354c95dd</guid>
            <category><![CDATA[fetch]]></category>
            <category><![CDATA[react-tutorial]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jumanah Al Asadi]]></dc:creator>
            <pubDate>Fri, 05 Nov 2021 20:10:39 GMT</pubDate>
            <atom:updated>2021-11-19T16:32:37.547Z</atom:updated>
            <content:encoded><![CDATA[<p>Learning how to load products from an API, create product components, dynamic routes, useEffect and hooks.</p><p>We will be building a Pet adoption app. We will display a list of pets from an API and users can add pets to their cart, and request to adopt them.</p><h3>~~~~~~~~~~~ Part 1</h3><p>Before starting we will need an API to grab our data from. You may use the API of your choice, but make sure to adjust the field names. I created my own database and API using Firebase.</p><p>The API will be my own pet-api hosted in Firebase. Each pet will have the following properties</p><ul><li>age (in years)</li><li>breed</li><li>image (url)</li><li>name</li><li>petType (cat, dog)</li><li><em>isAdopted (boolean)</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*L7HQZ5Zu99AlY8nIIWo3BA.png" /></figure><pre><a href="https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/">https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/</a></pre><p>Let’s install a new react project</p><pre>npx create-react-app store-app --use-npm </pre><p>Open the project and install react-router-dom, so we can build out pages.</p><pre>npm install react-router-dom@5.2.0</pre><p>Create a folder inside src, called components. We will add our main components here. We will also add a sub directory called pages for our page components (containers) which we will add to the router.</p><pre>src / components / pages </pre><p>And now we can run</p><pre>npm start</pre><p>App styles site wide — (optional) inside index.css</p><pre><a href="http://twitter.com/import">@import</a> url(https://medium.com/&#39;%3Ca%20href=%22/service/https://fonts.googleapis.com/css?family=Roboto:400,500,700&#39;%22%3Ehttps://fonts.googleapis.com/css?family=Roboto:400,500,700&#39;%3C/a%3E);</pre><pre>body {<br>  margin: 0;<br>  font-family: &#39;Roboto&#39;, sans-serif;<br>  -webkit-font-smoothing: antialiased;<br>  -moz-osx-font-smoothing: grayscale;</pre><pre><em>   color</em>: rgb(29, 29, 29);</pre><pre>}</pre><pre>* {<br>  box-sizing: border-box;<br>  margin: 0;<br>}</pre><p>Let’s begin to add some routes in App.js</p><ul><li>Home page to display all the pets available <a href="http://localhost:3000/pet/3455">http://localhost:3000/</a></li><li>Cart page to see all pets added to shopping basket ex. <a href="http://localhost:3000/pet/3455">http://localhost:3000</a>/cart</li><li>Pet details page — Dynamic route: ex. <a href="http://localhost:3000/pet/3455">http://localhost:3000/pet/3455</a></li></ul><pre>import &#39;./App.css&#39;;<br>import {<br>  BrowserRouter as Router,<br>  Switch,<br>  Route,<br>} from &quot;react-router-dom&quot;;</pre><pre>function App() {<br>  return (<br>    &lt;Router&gt;<br>      {/* Navigation Menu */}<br>      &lt;Switch&gt;<br>        &lt;Route exact path=&quot;/&quot;&gt;<br>          &lt;div&gt;Home page (all pets)&lt;/div&gt;<br>        &lt;/Route&gt;<br>        &lt;Route path=&quot;/cart&quot;&gt;<br>           &lt;div&gt;Shopping cart&lt;/div&gt;<br>        &lt;/Route&gt;<br>        &lt;Route path=&quot;/pet/:id&quot;&gt;<br>          &lt;div&gt;Individual Pet Details&lt;/div&gt;<br>        &lt;/Route&gt;<br>      &lt;/Switch&gt;<br>    &lt;/Router&gt;<br>  );<br>}</pre><pre>export default App;</pre><p>Right now it is empty placeholder content for now. We will add pages later.</p><p>Let’s create a navigation component to be able to switch pages by clicking on links.</p><p>In the components folder, create a Navbar folder and an index.jsx and styles.css files inside.</p><p>Inside index.jsx:</p><pre>import {<br>    NavLink<br>} from &quot;react-router-dom&quot;;</pre><pre>import &quot;./styles.css&quot;</pre><pre>export const Navbar = (props) =&gt; {<br>    return (<br>        &lt;nav className=&quot;navbar&quot;&gt;<br>            &lt;ul className=&quot;navbar-list&quot;&gt;<br>                &lt;li&gt;<br>                    &lt;NavLink exact={true} activeClassName=&quot;nav-selected&quot; to=&quot;/&quot;&gt;Pets &lt;/NavLink&gt;<br>                &lt;/li&gt;<br>                &lt;li&gt;<br>                    &lt;NavLink activeClassName=&quot;nav-selected&quot; to=&quot;/cart&quot;&gt;My Cart&lt;/NavLink&gt;<br>                &lt;/li&gt;<br>            &lt;/ul&gt;<br>        &lt;/nav&gt;<br>    )<br>}</pre><p>And some styles.</p><pre>.navbar ul {<br>    display: flex;<br>    flex-direction: column;<br>    list-style-type: none;<br>    align-items: center;<br>  }<br>  .navbar {<br>    background: coral;<br>    box-shadow: 0 3px 3px -1px rgba(0,0,0,.2);<br>    font-size: 1.5rem;<br>  }<br>  .navbar li {<br>    margin: 1rem;<br>  }<br>  .navbar a {<br>    text-decoration: none;<br>    color: rgb(36, 36, 36);<br>    font-weight: 450;<br>  }<br>  .navbar a.nav-selected {<br>    font-weight: 700;<br>    color: rgb(14, 14, 14);<br>  }<br>  .navbar a:hover {<br>    color: black;<br>    font-weight: 600;<br>  }<br><br>  <a href="http://twitter.com/media">@media</a> only screen and (min-width: 600px) {<br>    .navbar ul {<br>      display: flex;<br>      flex-direction: row;<br>      list-style-type: none;<br>      justify-content: flex-end;<br>    }<br>  }</pre><p>Let’s add our navbar to our App.js so it always displays no matter what URL we are in.</p><pre>import { Navbar } from &#39;./components/Navbar&#39;;</pre><p>and add the navbar component just above the switch tags.</p><pre>function App() {<br>  return (<br>    &lt;Router&gt;<br><strong>      &lt;Navbar /&gt;<br></strong>      &lt;Switch&gt;<br>        &lt;Route exact path=&quot;/&quot;&gt;<br>          &lt;div&gt;Home page (all pets)&lt;/div&gt;<br>        &lt;/Route&gt;<br>        &lt;Route path=&quot;/cart&quot;&gt;<br>           &lt;div&gt;Shopping cart&lt;/div&gt;<br>        &lt;/Route&gt;<br>        &lt;Route path=&quot;/pet/:id&quot;&gt;<br>          &lt;div&gt;Individual Pet Details&lt;/div&gt;<br>        &lt;/Route&gt;<br>      &lt;/Switch&gt;<br>    &lt;/Router&gt;<br>  );<br>}</pre><p>Let’s start on the Pets home page component which displays all the pets.</p><p>Create a <strong>PetsHomePage</strong> folder under pages, and index.jsx and styles.css.</p><p>index.jsx</p><ul><li>create a state variable to store pets from database</li><li>create a function to call the API</li><li>useEffect to call this function when the page loads</li></ul><pre>import { useEffect, useState } from &#39;react&#39;;<br>import &#39;./styles.css&#39;;</pre><pre>export const PetsHomePage = () =&gt; {</pre><pre>const [pets, setPets] = useState([]);</pre><pre>useEffect( () =&gt; {<br>        getPets();<br>    }, [])</pre><pre>const getPets = async() =&gt; {<br>        try {<br>            const response = await fetch(&#39;<a href="https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/&#39;);">https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/&#39;);</a><br>            const data = await response.json(); <br>            console.log(data);<br>            const formattedData = data.documents.map( (item) =&gt; {<br>                return item.fields<br>            })<br>            setPets(formattedData); <br>        } catch(err) {</pre><pre>}<br>    }</pre><pre>return (<br>        &lt;div className=&quot;pets-page&quot;&gt;<br>            &lt;h1 className=&quot;pets-title&quot;&gt;All Pets&lt;/h1&gt;<br>            &lt;div className=&quot;pets-container&quot;&gt;<br>                {/* Dynamic from API */}<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    )</pre><pre>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZdbwN_m9kPjiiWLlBRlT_g.png" /></figure><p>styles.css</p><pre>.pets-page {<br>    padding: 10px;<br>}</pre><pre>.pets-container {<br>    display: flex;<br>    flex-direction: row;<br>    flex-wrap: wrap;<br>}</pre><pre>.pets-title {<br>    padding: 1rem;<br>    text-transform: uppercase;<br>    letter-spacing: 2px;<br>    border-bottom: 1px solid #ddd;<br>    padding-bottom: .5em;<br>}</pre><p>We should see our data in the console.log now, but we should display the data on our website using our PetItem component! We will create that next.</p><p>Import this page into our router in App.js and nest it under the home page route:</p><pre>import { PetsHomePage } from &#39;./components/pages/PetsHomePage&#39;;</pre><p>Under the route for ‘/’</p><pre>&lt;<em>Route</em> exact path=&quot;/&quot;&gt;</pre><pre>&lt;<em>PetsHomePage</em> /&gt;</pre><pre>&lt;/<em>Route</em>&gt;</pre><p>This component should display now when opening the home page of the website.</p><p>Let’s create a reusable button component. Inside the components folder add a Button folder and index and css files.</p><p>We can give it primary and secondary styles.</p><pre>import &#39;./styles.css&#39;;</pre><pre>export const Button = (props) =&gt; {</pre><pre>const {isDisabled, action, isPrimary, text}  = props;</pre><pre>return (<br>        &lt;button onClick={action} disabled={isDisabled} className={isPrimary ? &#39;primary&#39; : &#39;secondary&#39;}&gt;{text}&lt;/button&gt;<br>    )<br>    <br>}</pre><p>And styles</p><pre>button:disabled {<br>    opacity: 0.2;<br>}</pre><pre>button:disabled:hover {<br>    opacity: 0.2;<br>    cursor: default;<br>}</pre><pre>.primary {<br>    border: none;<br>    outline: 0;<br>    padding: 12px;<br>    color: white;<br>    background-color: #000;<br>    text-align: center;<br>    cursor: pointer;<br>    width: 100%;<br>    font-size: 18px;<br>    width: 100%;<br>    margin-top: 1rem;<br>    font-weight: bold;<br>}</pre><pre>.secondary {<br>    border: none;<br>    outline: 0;<br>    padding: 12px;<br>    color: #000;<br>    background-color: #FFF;<br>    text-align: center;<br>    cursor: pointer;<br>    width: 100%;<br>    font-size: 18px;<br>    width: 100%;<br>    margin-top: 1rem;<br>    font-weight: bold;<br>    border: black 1px solid;<br>}</pre><pre>.secondary:hover, .primary:hover {<br>    opacity: 0.8;<br>}</pre><p>Let’s create a <strong>PetItem</strong> component. This component will display an individual pet in a small card, its image, age, name, type etc..</p><p>The user can click on it to view more details and request the pet.</p><p>Inside the components folder add a PetItem folder and index and css files.</p><p>Index.jsx</p><pre>import &#39;./styles.css&#39;;<br>import { Button } from &#39;../Button&#39;;</pre><pre>export const PetItem = (props) =&gt; {<br>  const { image, age, name, breed, type, id }  = props;</pre><pre>return (<br>    &lt;div className=&quot;pet&quot;&gt;<br>      &lt;img className=&quot;pet-photo&quot; src={image} alt={name + breed + &quot; image&quot;} /&gt;<br>      &lt;h1 className=&quot;pet-name&quot;&gt;{name}&lt;/h1&gt;<br>      &lt;p className=&quot;pet-breed&quot;&gt;{breed}&lt;/p&gt;<br>      &lt;p className=&quot;pet-age&quot;&gt;{age} years old &lt;/p&gt;<br>      &lt;<em>Button</em> action={} isDisabled={false} isPrimary={true} text=&quot;Request Pet&quot;&gt;&lt;/<em>Button</em>&gt;</pre><pre>&lt;/div&gt;<br>  );<br>};</pre><p>Styles.css</p><pre>.pet {<br>    width: 300px;<br>    display: flex;<br>    flex-direction: column;<br>    align-items: flex-start;<br>    margin: 1rem;<br>    box-shadow: 0 2px 7px #dfdfdf;<br>    font-family: Arial, Helvetica, sans-serif;<br>    background: #fafafa;<br>}</pre><pre>.pet-photo {<br>    width: 300px;<br>    height: 200px;<br>    object-fit: cover;<br>    margin-bottom: 5px;<br>}</pre><pre>.pet-name {<br>    font-size: 1.3rem;<br>    padding: 5px;<br>    text-transform: uppercase;<br>}<br>.pet-breed {<br>    font-weight: bold;<br>}</pre><pre>.pet-breed, .pet-age {<br>    color: gray;<br>    padding: 5px;<br>    text-transform: uppercase;<br>    font-size: 0.9rem;<br>}</pre><p>And let us add this to the All Pets home page, by mapping through our raw data returned from the API and display this PetItem for each pet.</p><p>Inside src/components/pages/PetsHomePage</p><pre>import { PetItem } from &#39;../../PetItem&#39;;</pre><p>Use map to go through each item in our pets state from API and display a PetItem component. We pass props it requires.</p><pre>return (<br>    &lt;div className=&quot;pets-page&quot;&gt;<br>      &lt;h1 className=&quot;pets-title&quot;&gt;All Pets&lt;/h1&gt;<br>      {pets.length &gt; 0 &amp;&amp; (<br>        &lt;div className=&quot;pets-container&quot;&gt;<br>          {pets.map((pet, index) =&gt; (<br>            &lt;PetItem<br>              key={pet.id.stringValue}<br>              id={pet.id.stringValue}<br>              image={pet.image.stringValue}<br>              age={pet.age.stringValue}<br>              breed={pet.breed.stringValue}<br>              name={pet.name.stringValue}<br>              type={pet.petType.stringValue}<br>            /&gt;<br>          ))}<br>        &lt;/div&gt;<br>      )}<br>  );</pre><p>We can also add a loading state, since calling our API may take some time to return data.</p><pre><em>const</em> [isLoading, setIsLoading] = useState(true);</pre><p>We set this isLoading state to false once our api returns data or fails.</p><pre>try {<br>      const response = await fetch(<br>        &quot;<a href="https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/">https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/</a>&quot;<br>      );<br>      const data = await response.json();<br>      const formattedData = data.documents.map((item) =&gt; {<br>        return item.fields;<br>      });<br>      setPets(formattedData);<br><strong>      setIsLoading(false);<br></strong>    } catch (err) {<br>        console.log(err);<br><strong>        setIsLoading(false);<br></strong>    }<br>  };</pre><p>In our component then, we can also add a loading message when the api is still fetching and also if nothing is found we can display no pets found.</p><pre>{pets.length === 0 &amp;&amp; !isLoading &amp;&amp; &lt;p&gt;No pets found..&lt;/p&gt;}</pre><pre>{isLoading &amp;&amp; &lt;p&gt;Loading..&lt;/p&gt;}</pre><p>Open your home page, it should look like this!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WzQ7C8lbhFinW5uJOCK64w.png" /></figure><h3>~~~~~~~~~~~ Part 2</h3><p>Let’s add a search feature to search between pet breeds. We can add a Search folder in the components folder. Index and styles.css. We will pass it a callback to communicate its value to the main page, so it can decide what pets to display.</p><pre>export const Search = (props) =&gt; {<br>    return (<br>        &lt;input onChange={props.handleSearchUpdate} type=&quot;text&quot; name=&quot;search&quot; placeholder=&quot;Search by breed..&quot; /&gt;<br>    )<br>}</pre><p>In the home page, where all our pets our displayed lets add a search bar at the top</p><pre>import { Search } from &quot;../../Search&quot;;</pre><p>We should add a state now for our search string. So we can update the pets based on the search string. We also should store the state of our filtered pets, based on what we search.</p><pre>export const PetsHomePage = () =&gt; {<br>  const [pets, setPets] = useState([]);<br>  const [isLoading, setIsLoading] = useState(true);</pre><pre><strong>  const [filteredPets, setFilteredPets] = useState([]);<br>  const [searchString, setSearchString] = useState(&#39;&#39;);</strong></pre><p>At the beginning we will set the filteredPets to all the pets..</p><pre>const getPets = async () =&gt; {<br>    try {<br>      const response = await fetch(<br>        &quot;<a href="https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/">https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/</a>&quot;<br>      );<br>      const data = await response.json();<br>      const formattedData = data.documents.map((item) =&gt; {<br>        return item.fields;<br>      });<br>      setPets(formattedData);<br><strong>      setFilteredPets(formattedData);<br></strong>      setIsLoading(false);<br>    } catch (err) {<br>      console.log(err);<br>      setIsLoading(false);<br>    }<br>  };</pre><p>Lets add it at the top of our page</p><pre>&lt;div className=&quot;pets-page&quot;&gt;<br><strong>      &lt;<em>Search</em> handleSearchUpdate={handleSearchUpdate} /&gt;</strong></pre><pre>    &lt;h1 className=&quot;pets-title&quot;&gt;All Pets&lt;/h1&gt;<br>     ...</pre><p>Let’s create a new functions filter by breed from the search. We can call it handle search by breed. We convert text to lowercase because we want it to be case insensitive. We search by breed.</p><pre><em>const</em> handleSearchUpdate = (<em>event</em>) <em>=&gt;</em> {</pre><pre>  setSearchString(<em>event</em>.target.value)</pre><pre>}</pre><pre>const handleSearchByBreed = () =&gt; {<br>    if (searchString == &#39;&#39;) {<br>      setFilteredPets(pets);<br>      return;<br>    }<br>    const filteredPets = pets.filter((pet) =&gt; {<br>      const breed = pet.breed.stringValue.toLowerCase();<br>      const isMatch = breed.indexOf(searchString.trim().toLowerCase());</pre><pre>       return isMatch !== -1;<br>    });<br>    setFilteredPets(filteredPets);<br>  };</pre><p>We need to call this function every time our search string state changes.. we can add it to a dependencies array for the useEffect</p><pre>useEffect(() =&gt; {<br>    handleSearchByBreed();<br>  }, [searchString]);</pre><p>We also need to swap out displaying all pets, to just the filtered ones.</p><pre>&lt;h1 className=&quot;pets-title&quot;&gt;All Pets&lt;/h1&gt;<br>      {<strong>filteredPets</strong>.length &gt; 0 &amp;&amp; (<br>        &lt;div className=&quot;pets-container&quot;&gt;<br>          {<strong>filteredPets</strong>.map((pet, index) =&gt; (<br>            &lt;PetItem<br>              key={pet.id.stringValue}<br>              id={pet.id.stringValue}<br>              image={pet.image.stringValue}<br>              age={pet.age.stringValue}<br>              breed={pet.breed.stringValue}<br>              name={pet.name.stringValue}<br>              type={pet.petType.stringValue}<br>            /&gt;<br>          ))}<br>        &lt;/div&gt;<br>      )}</pre><pre>{<strong>filteredPets</strong>.length === 0 &amp;&amp; !isLoading &amp;&amp; &lt;p&gt;No pets found..&lt;/p&gt;}</pre><pre>{isLoading &amp;&amp; &lt;p&gt;Loading..&lt;/p&gt;}</pre><p>See it in action!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6CNWzeoiOgiig1KRPt1DlQ.png" /></figure><p>Let’s start working on requesting a pet! Adding it to a cart. We can use Context to do this. Whenever we click the request pet button it will add it to our global state of order! Let’s create this react context.</p><p>Create a folder called context in your project and lets create petsOrderContext.js to store our context and our provider.</p><pre>import React, {useState} from &#39;react&#39;;</pre><pre>const PetsOrderContext = React.createContext({<br>    order: [],    <br>    pets: [],<br>    addPetToOrder: () =&gt; {},<br>    removePetFromOrder: () =&gt; {},<br>});</pre><p>Then we can add our provider..</p><pre>import React, {useState} from &#39;react&#39;;</pre><pre>const PetsOrderContext = React.createContext({<br>    order: [],<br>    pets: [],<br>    initializePets: () =&gt; {},<br>    addPetToOrder: () =&gt; {},<br>    removePetFromOrder: () =&gt; {},<br>});</pre><pre>export const PetsOrderContextProvider = (props) =&gt; {<br>    const [order, setOrder] = useState([]);<br>    const [pets, setPets] = useState([]);</pre><pre>const initializePets = (petsFromAPI) =&gt; {<br>        setPets(petsFromAPI);<br>    }</pre><pre>const addPetToOrder = (pet) =&gt; {<br>        let newOrder = order; <br>        newOrder.push (pet);<br>        setOrder(order);<br>    }</pre><pre>const removePetFromOrder = (petId) =&gt; {<br>        let prevOrder = order;<br>        const found = order.findIndex( (pet ) =&gt; {<br>            return (pet.id === petId); <br>        })<br>        if (found !== -1) {<br>            prevOrder.splice(found, 1); // delete one<br>            setOrder([...prevOrder]);<br>        } else {<br>            console.log (&quot;error delete&quot;);<br>        }<br>    }<br>    <br>    return (&lt;PetsOrderContext.Provider<br>     value={{order: order, addPetToOrder: addPetToOrder, removePetFromOrder: removePetFromOrder, initializePets: initializePets, pets: pets }}<br>    &gt;<br>        {props.children}<br>    &lt;/PetsOrderContext.Provider&gt;)</pre><pre>}</pre><pre>export default PetsOrderContext;</pre><p>Now we can wrap this pet order context around our app. Let’s do this in the index.js file.</p><pre>import { PetsOrderContextProvider } from &#39;./context/petsOrderContext&#39;;</pre><p>And then we can do this to wrap it:</p><pre>ReactDOM.render(<br>  &lt;PetsOrderContextProvider&gt;<br>    &lt;App /&gt;<br>  &lt;/PetsOrderContextProvider&gt;,<br>  document.getElementById(&#39;root&#39;)<br>);</pre><p>Let’s start using our context now!</p><p>Let’s go back to Pet Item Component.</p><p>Import the context, and the context hook</p><pre>import {useContext } from &#39;react&#39;<br>import PetsOrderContext from &#39;../../context/petsOrderContext&#39;;</pre><p>Let’s use it inside our component like so</p><pre><em>const</em> orderContext = useContext(PetsOrderContext);</pre><p>Lets update our button to trigger something</p><pre>&lt;button onClick={addPetToCart} className=&quot;pet-btn&quot;&gt;Request Pet&lt;/button&gt;</pre><p>Then we can now define this function as follows:</p><pre>const addPetToCart = () =&gt; {<br>    let petDetails = {<br>        id: id, <br>        name: name,<br>        image: image,<br>        breed: breed,<br>        type: type,<br>        age: age<br>    }<br>    orderContext.addPetToOrder(petDetails);<br>    console.log (orderContext.order);<br>    alert (&quot;Pet added!&quot;)<br>  }</pre><p>Now once we click Request pet, our orders context will be updated. We can reference this in the cart page!</p><p>Now lets display our order in the My Cart page! Lets create a new page in the pages folder.</p><p>src/components/pages/ShoppingCartPage/</p><p>And creates index.jsx and styles.</p><pre>import { useEffect, useState, useContext } from &quot;react&quot;;</pre><pre>import &quot;./styles.css&quot;;</pre><pre>export const ShoppingCartPage = () =&gt; {</pre><pre>return (<br>    &lt;div className=&quot;pets-page&quot;&gt;<br>      &lt;h1 className=&quot;pets-title&quot;&gt;My Shopping Cart&lt;/h1&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>And we should import it into our router. In the App.js</p><pre>&lt;Route path=&quot;/cart&quot;&gt;<br>           &lt;ShoppingCartPage /&gt;<br>        &lt;/Route&gt;</pre><p>Now lets create an Order Item component, which will display our product in a mini way, and contain a remove button to remove it from the order.</p><p>Inside components, add a new OrderItem component!</p><pre>import &quot;./styles.css&quot;;<br>import { useContext } from &quot;react&quot;;<br>import PetsOrderContext from &quot;../../context/petsOrderContext&quot;;<br>import { Button } from &quot;../Button&quot;;</pre><pre>export const OrderItem = (props) =&gt; {<br>  const { image, age, name, breed, id } = props;</pre><pre>const orderContext = useContext(PetsOrderContext);</pre><pre>const removePetFromCart = () =&gt; {<br>    orderContext.removePetFromOrder(id);<br>    console.log(orderContext.order);<br>    alert(&quot;Pet removed!&quot;);<br>  };</pre><pre>return (<br>    &lt;div className=&quot;order-item&quot;&gt;<br>      &lt;img className=&quot;order-photo&quot; src={image} alt={name + breed + &quot; image&quot;} /&gt;</pre><pre>&lt;div className=&quot;order-desc&quot;&gt;<br>        &lt;h1 className=&quot;order-name&quot;&gt;{name}&lt;/h1&gt;<br>        &lt;p className=&quot;order-breed&quot;&gt;{breed}&lt;/p&gt;<br>        &lt;p className=&quot;order-age&quot;&gt;{age} years old &lt;/p&gt;<br>      &lt;/div&gt;<br>      &lt;Button<br>        action={removePetFromCart}<br>        text=&quot;Remove Pet&quot;<br>        isPrimary={false}<br>        isDisabled={false}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>And styles.css</p><pre>.order-item {<br>    min-height: 100px;<br>    padding: 1rem;<br>    border: 1px solid gray;<br>    border-radius: 10px;<br>    margin-top: 1rem;<br>    display: flex;<br>    flex-direction: column;<br>    /* align-items: center; */<br>    justify-content: center;<br>}</pre><pre>.order-desc {<br>    display: flex;<br>    flex-direction: column;<br>    justify-content: flex-start;<br>}</pre><pre>.order-photo {<br>    height: 200px;<br>    object-fit: cover;<br>    margin-bottom: 5px;<br>}</pre><p>Then let us display it in the Shopping cart page!</p><p>In the shopping cart we will map through our order in the context and display the orderItem component.</p><pre>import { useEffect, useState, useContext } from &quot;react&quot;;<br>import PetsOrderContext from &quot;../../../context/petsOrderContext&quot;;<br>import { OrderItem } from &quot;../../OrderItem&quot;;<br>import { Button } from &quot;../../Button&quot;;</pre><pre>import &quot;./styles.css&quot;;</pre><pre>export const ShoppingCartPage = () =&gt; {</pre><pre>const [order, setOrder ] = useState([]);</pre><pre>const orderContext = useContext(PetsOrderContext);</pre><pre>useEffect ( () =&gt; {<br>    setOrder(orderContext.order);<br>  }, [orderContext])</pre><pre>return (<br>    &lt;div className=&quot;pets-page&quot;&gt;<br>      &lt;h1 className=&quot;pets-title&quot;&gt;My Shopping Cart&lt;/h1&gt;<br>      &lt;div className=&quot;order&quot;&gt;<br>        {<br>            order.map((pet, index) =&gt; &lt;OrderItem key={index} image={pet.image} id={pet.id} name={pet.name} breed={pet.breed} age={pet.age} /&gt;)<br>        }<br>      &lt;/div&gt;</pre><pre>&lt;<em>Button</em> text=&quot;Checkout&quot; isPrimary={true}&gt;&lt;/<em>Button</em>&gt;</pre><pre>&lt;/div&gt;<br>  );<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8wH8-m1UwKpmd4Lht562g.png" /></figure><p>Let’s add a link around the pet so we can click on it to go to the details page and learn more about the pet.</p><p>Inside PetItem just add the link. Wrap it around the name of the pet. We will redirect to a dynamic route.. pet/1 or pet/2 ..and display a different pet accordingly.</p><pre>import { Link } from &#39;react-router-dom&#39;;</pre><p>..</p><pre>return (<br>    &lt;div className=&quot;pet&quot;&gt;<br>      &lt;img className=&quot;pet-photo&quot; src={image} alt={name + breed + &quot; image&quot;} /&gt;<br><strong>      &lt;Link to={`/pet/${id}`}&gt;&lt;h1 className=&quot;pet-name&quot;&gt;{name}&lt;/h1&gt;&lt;/Link&gt;</strong><br>      &lt;p className=&quot;pet-breed&quot;&gt;{breed}&lt;/p&gt;<br>      &lt;p className=&quot;pet-age&quot;&gt;{age} years old &lt;/p&gt;<br>      &lt;Button action={addPetToCart} isDisabled={false} isPrimary={true} text=&quot;Request Pet&quot;&gt;&lt;/Button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Now let’s create a dynamic route for each pet. We want to click on a pet and then see the pet details page.</p><p>Remember in App.js we have the following dynamic route:</p><pre>&lt;<em>Route</em> path=&quot;/pet/:id&quot;&gt;</pre><pre>   &lt;div&gt;Individual Pet Details&lt;/div&gt;</pre><pre>&lt;/<em>Route</em>&gt;</pre><p>We haven’t used it yet. Let’s make a Pet Details Page under the pages folder. We can create a PetDetailsPage folder and index.jsx, styles.</p><p>We will grab the id from the route using useParams from react-router-dom</p><p>src/components/pages/PetDetailsPage/index.jsx</p><pre>import { useContext } from &quot;react&quot;;<br>import PetsOrderContext from &quot;../../../context/petsOrderContext&quot;;<br>import { useParams } from &#39;react-router-dom&#39;;</pre><pre>import &quot;./styles.css&quot;;</pre><pre>export const PetDetailsPage = (props) =&gt; {</pre><pre>const { id } = useParams();</pre><pre>const orderContext = useContext(PetsOrderContext);</pre><pre>return (<br>    &lt;div className=&quot;pets-page&quot;&gt;<br>      &lt;h1 className=&quot;pets-title&quot;&gt;Pet Details: {id}&lt;/h1&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>In App.js we have the following dynamic route, lets import the page we just made inside the route:</p><pre>import { PetDetailsPage } from ‘./components/pages/PetDetailsPage’;</pre><p>-</p><pre>&lt;Route path=&quot;/pet/:id&quot;&gt;<br>    &lt;PetDetailsPage /&gt;<br> &lt;/Route&gt;</pre><p>Now we need to either call the API with that id, or we can store our results in our state, so that way we don’t need to recall the API again when we already have the pets from a previous call and we can store it in context. So we can just filter from there and grab the details for that pet.</p><p>Let’s update our Pets Home page, to store the pets we get from the API in context.</p><pre>export const PetsHomePage = () =&gt; {<br>  const [pets, setPets] = useState([]);<br>  const [isLoading, setIsLoading] = useState(true);</pre><pre>  const [filteredPets, setFilteredPets] = useState([]);<br>  const [searchString, setSearchString] = useState(&quot;&quot;);</pre><pre>  const orderCtx = useContext(PetsOrderContext);</pre><p>And then let’s set the pets in the global context, using the initialize pets function</p><pre>const getPets = async () =&gt; {<br>    try {<br>      const response = await fetch(<br>        &quot;<a href="https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/">https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/</a>&quot;<br>      );<br>      const data = await response.json();<br>      const formattedData = data.documents.map((item) =&gt; {<br>        return item.fields;<br>      });<br>      setPets(formattedData);<br>      setFilteredPets(formattedData);<br><strong>      orderCtx.initializePets(formattedData)<br></strong>      setIsLoading(false);<br>    } catch (err) {<br>      console.log(err);<br>      setIsLoading(false);<br>    }<br>  };</pre><p>Now back in the Pets Details page lets filter through the pets in state and grab only the one we are interested in.</p><pre>import { useContext, useEffect, useState } from &quot;react&quot;;<br>import PetsOrderContext from &quot;../../../context/petsOrderContext&quot;;<br>import { useParams } from &#39;react-router-dom&#39;;</pre><pre>import &quot;./styles.css&quot;;</pre><pre>export const PetDetailsPage = () =&gt; {</pre><pre>const [pet, setPet] = useState({});<br>  const orderContext = useContext(PetsOrderContext);</pre><pre>const { id } = useParams();</pre><pre>useEffect( () =&gt; {<br><strong>     const pet = orderContext.pets.find((pet)=&gt; pet.id.stringValue === id);<br></strong>     setPet(pet);<br>  }, []);</pre><pre>if (pet) {<br>      return (<br>    &lt;div className=&quot;pets-page&quot;&gt;<br>      &lt;h1 className=&quot;pets-title&quot;&gt;Pet: {pet.name?.stringValue}&lt;/h1&gt;<br>      &lt;img src={pet.image?.stringValue} /&gt;<br>    &lt;/div&gt;<br>      )<br>   } else {<br>       return ( &lt;p&gt; No pet with this ID. &lt;/p&gt;)<br>   }<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fYjZWu82o5_uIe78t5NABA.png" /></figure><h3>~~~~~~~~~~~ Part 3 — Add Authentication</h3><p>Using the latest version of Firebase SDK. 9+. Using React.js create react app. Showing examples of login, sign up, logout, check currentUser.</p><p>Start by creating a free, google account. Then open the following link to create a new Google Firebase project. The account will be under Google’s Spark plan which is 100% free.</p><p>Click get started. <a href="https://firebase.google.com/">https://firebase.google.com/</a>. Follow the steps. You need to be signed in to your google account. This project will be created under your google account (gmail).</p><h3>Firebase Set Up</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MnwOOB1wSB4a2KZzN8Dq8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tksv3uzknl7YeeIfV1gO2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TDnxi6X-E4AN2e-2dFGMLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9iP_5mRwE6lQuidxSSnqng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MElYDhs175GyMZXybJQjIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kDUYovnxZUYhwmt8DnIS0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*FizEZOChLB_8VGJ3VlGWCg.png" /></figure><p>After you are done going through the wizard to create a new project. You will need to add “Firebase authentication” in this project. Since Firebase has a ton of other features in addition to authentication, you can add a Database, Cloud Storage, etc. But for now, only add the Authentication.</p><p>When going through this next wizard, I chose the basic email and password option, but you can add any other form of sign in, like sign in with Facebook or Google.. These will not be covered in this tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_782Qq2YYK_UCVW7WwCXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqjFtIk5eSMj7QKrwNSf4g.png" /></figure><p>Then you must create a link to your react app from Firebase. By doing this, it will create new credentials and a configuration for you to paste in your React app so you can access this specific instance of Firebase from your react app.</p><p>To accomplish this, open your project settings, and click add a web app, the &lt;/&gt; icon and fill out the instructions, like choosing a name and analytics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbgzdcbsAjmo8LDzk4ziVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-NQZ01dhi-l4G5ilA-ufxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sA4NU1jY1E-to3tigjAPpw.png" /></figure><p>The end result will be credentials for your react app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3code3BQNCnDPfF1DYUQA.png" /></figure><p>Copy paste this entire blob of code to your react app. Of course you should put all secret data in their environment variables, but for now, let’s just pretend we did that.</p><ul><li>Create an .env file</li><li>Create variables for all the items, REACT_APP_API_KEY ..etc and so on</li><li>Refer to them as process.env.REACT_APP_API_KEY</li></ul><p>Before copying this code, we should install firebase (the newest version). This way we can initialize Firebase in our React app.</p><pre>npm install firebase</pre><p>We can copy all this code from the previous step, supplied to us from the end of the wizard.</p><p>Inside of<strong> index.js</strong>, just above the ReactDOM.render statement, there we can call the initializeApp function with the credentials we have. Don’t forget to put this data instead in .env file and never push them to Github or Bitbucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*QwyTRxSca-QvN1yH3w1E2w.png" /></figure><p>Now we are ready to use our Firebase instance. The configuration is all set up :-)</p><h4>Log in + Sign Up + Log Out</h4><p>*Don’t forget to install the Firebase SDK into your project. Alright let’s do this :)</p><p>We can start by creating a login, and sign up in our application. Add the login route using react-router-dom and create components for them. Add the following route: I will put sign up and login in the same page, and show and hide them.</p><ul><li>/login</li><li>In these pages, we can build a form, that will call the functions to authenticate into Firebase.</li></ul><p>We will import them when necessary:</p><pre>import {<br>...</pre><pre>} from &quot;firebase/auth&quot;;</pre><p>In App.js let’s add the route.</p><pre>       &lt;Route exact path=&quot;/login&quot;&gt;<br>          &lt;LoginPage /&gt;<br>        &lt;/Route&gt;</pre><p>Let’s create the LoginPage component inside the components &gt; pages folder, and index.jsx and styles.css</p><p>We also need to install react-hook-form. <a href="https://react-hook-form.com/">https://react-hook-form.com/</a> It will help us with form submission and validation.</p><pre>npm install react-hook-form</pre><p>Then we can begin building out our form. The component will have a signup and login state, and display each individual form depending on which one.</p><pre>const [mode, setMode] = useState(&quot;login&quot;);</pre><p>We will follow the react-hook-form syntax. If you have trouble following along please read my <a href="https://jujuontheweb.medium.com/how-to-use-react-hook-form-with-your-custom-form-components-a86a1a77cf3c">article</a> now.</p><pre>import { useHistory } from &quot;react-router-dom&quot;;<br>import { useForm } from &quot;react-hook-form&quot;;</pre><pre>import { useState } from &quot;react&quot;;</pre><pre>import &quot;./styles.css&quot;;</pre><pre>export const LoginPage = () =&gt; {<br>  const [mode, setMode] = useState(&quot;login&quot;);</pre><pre>  const { register, handleSubmit } = useForm();</pre><pre>  const history = useHistory();</pre><pre>  return (<br>    &lt;div className=&quot;pets-page&quot;&gt;<br>      {mode === &quot;login&quot; &amp;&amp; (<br>        &lt;form className=&quot;form-layout&quot; onSubmit={handleSubmit(loginUser)}&gt;<br>          &lt;h2&gt;Welcome back! Please log in. &lt;/h2&gt;<br>          &lt;br /&gt;</pre><pre>&lt;label htmlFor=&quot;user&quot;&gt; Email &lt;/label&gt;<br>          &lt;input {...register(&quot;user&quot;)} name=&quot;user&quot; required type=&quot;email&quot; /&gt;<br>          &lt;label htmlFor=&quot;password&quot;&gt; Password &lt;/label&gt;<br>          &lt;input<br>            {...register(&quot;password&quot;)}<br>            name=&quot;password&quot;<br>            type=&quot;password&quot;<br>            required<br>          /&gt;<br>          &lt;input type=&quot;submit&quot; value=&quot;Login&quot; /&gt;<br>          &lt;br /&gt;<br>          &lt;p&gt;<br>            Don&#39;t have an account yet? Create a new account with your email and<br>            password.{&quot; &quot;}<br>          &lt;/p&gt;<br>          &lt;button onClick={() =&gt; setMode(&quot;signup&quot;)}&gt; Sign Up &lt;/button&gt;<br>        &lt;/form&gt;<br>      )}</pre><pre>{mode === &quot;signup&quot; &amp;&amp; (<br>        &lt;form className=&quot;form-layout&quot; onSubmit={handleSubmit(signUpUser)}&gt;<br>          &lt;h2&gt;Create a new account &lt;/h2&gt;<br>          &lt;br /&gt;</pre><pre>&lt;label htmlFor=&quot;user&quot;&gt; Email &lt;/label&gt;<br>          &lt;input {...register(&quot;user&quot;)} name=&quot;user&quot; required type=&quot;email&quot; /&gt;<br>          &lt;label htmlFor=&quot;password&quot;&gt; Password &lt;/label&gt;<br>          &lt;input<br>            {...register(&quot;password&quot;)}<br>            name=&quot;password&quot;<br>            type=&quot;password&quot;<br>            required<br>          /&gt;<br>          &lt;label htmlFor=&quot;password&quot;&gt; Confirm Password &lt;/label&gt;<br>          &lt;input<br>            {...register(&quot;passwordConfirm&quot;)}<br>            name=&quot;passwordConfirm&quot;<br>            type=&quot;password&quot;<br>            required<br>          /&gt;<br>          &lt;input type=&quot;submit&quot; value=&quot;Sign Up&quot; /&gt;<br>          &lt;br /&gt;<br>          &lt;p&gt;Have an account already? &lt;/p&gt;</pre><pre>&lt;button onClick={() =&gt; setMode(&quot;login&quot;)}&gt; Login &lt;/button&gt;<br>        &lt;/form&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tk4GRxu6ntfnC4DhpjBLow.png" /></figure><p>This won’t work yet, because we need to define the functions that are triggered when submitting the form.</p><p>We should then import the methods we need to use from Firebase, at the top of our component.</p><pre>import {<br>  getAuth,<br>  createUserWithEmailAndPassword,<br>  signInWithEmailAndPassword,<br>} from &quot;firebase/auth&quot;;</pre><p>Then inside our component, we can add our functions inside.</p><pre>const loginUser = async (formVals) =&gt; {<br>    console.log(formVals);<br>    const auth = getAuth();<br>    try {<br>      const user = await signInWithEmailAndPassword(<br>        auth,<br>        formVals.user,<br>        formVals.password<br>      );<br>      console.log(&quot;User logged in&quot;, user);<br>      history.push(&quot;/&quot;);<br>    } catch (error) {<br>      const errorCode = error.code;<br>      console.log(&quot;Error&quot;, errorCode);<br>    }<br>  };</pre><pre>const signUpUser = async (formVals) =&gt; {<br>    console.log(formVals);<br>    if (formVals.password !== formVals.passwordConfirm) {<br>      console.log(&quot;Passwords don&#39;t match&quot;);<br>      return;<br>    }<br>    const auth = getAuth();<br>    try {<br>      const user = await createUserWithEmailAndPassword(<br>        auth,<br>        formVals.user,<br>        formVals.password<br>      );<br>      console.log(&quot;New user created&quot;, user);<br>      history.push(&quot;/&quot;);<br>    } catch (error) {<br>      const errorCode = error.code;<br>      console.log(&quot;Error&quot;, errorCode);<br>    }<br>  };</pre><p>Don’t forget to add some styles for the form..</p><pre>.form-layout {<br>    display: flex;<br>    flex-direction: column;<br>    justify-content: center;<br>    width: 400px;<br>    margin: 0 auto;<br>    margin-top: 50px;<br>    <br>}</pre><pre>input {<br>    height: 50px;<br>    font-size: 1.5rem;<br>    width: 400px;<br>    margin-bottom: 10px;<br>}</pre><pre>input[type=submit] {<br>    background: black;<br>    border: none;<br>    color: white;<br>    cursor: pointer;<br>}</pre><pre>button {<br>    height: 50px;<br>    font-size: 1.4rem;<br>    background: transparent;<br>    cursor: pointer;<br>    border: 1px solid gray;<br>    cursor: pointer;<br>}</pre><p>Then we can also create a<strong> logout component,</strong> to sign the user out when they click on it. It will only displayed when a user is currently logged in..</p><p>We can create a logout component in the components folder, index.jsx and styles.css</p><pre>import { getAuth, signOut, onAuthStateChanged } from &quot;firebase/auth&quot;;<br>import { useEffect, useState } from &quot;react&quot;;<br>import { useHistory } from &#39;react-router-dom&#39;;</pre><pre>import &#39;./styles.css&#39;<br>export const Logout = () =&gt; {<br>    const history = useHistory();<br>    const [user, setUser] = useState(null);</pre><pre>    useEffect(<br>        () =&gt; {<br>            const auth = getAuth();<br>            onAuthStateChanged(auth, (user) =&gt; {<br>                if (user) {<br>                    setUser(auth.currentUser)<br>                } else {<br>                    setUser(null)<br>                }<br>            });<br>              <br>        }, []<br>    )</pre><pre>   const logoutUser = async () =&gt; {<br>        const auth = getAuth();<br>        try {<br>            await signOut(auth);<br>            history.push(&#39;/login&#39;)<br>        } catch (error) {<br>            console.log (error)<br>        }<br>    }</pre><pre>  return (<br>        user &amp;&amp; &lt;button className=&quot;logout-btn&quot; onClick={logoutUser}&gt; Logout &lt;/button&gt;<br>    )<br>}</pre><p>Inside styles.css</p><pre>.logout-btn {<br>    background: transparent;<br>    font-size: 1.5rem;<br>    border: none;<br>}</pre><pre>.logout-btn:hover {<br>    opacity: 0.7;<br>    cursor: pointer;<br>}</pre><p>Then we can import it into your navbar component to display it on the top navbar..</p><pre>import { Logout } from “../Logout”;</pre><p>..</p><pre><br>export const Navbar = () =&gt; {<br>    return (<br>        &lt;nav className=&quot;navbar&quot;&gt;<br>            &lt;ul className=&quot;navbar-list&quot;&gt;<br>                &lt;li&gt;<br>                    &lt;NavLink exact={true} activeClassName=&quot;nav-selected&quot; to=&quot;/&quot;&gt;Pets&lt;/NavLink&gt;<br>                &lt;/li&gt;<br>                &lt;li&gt;<br>                    &lt;NavLink activeClassName=&quot;nav-selected&quot; to=&quot;/cart&quot;&gt; My Cart&lt;/NavLink&gt;<br>                &lt;/li&gt;<br><strong>                &lt;li&gt;<br>                    &lt;Logout /&gt;<br>                &lt;/li&gt;</strong><br>            &lt;/ul&gt;<br>        &lt;/nav&gt;<br>    )<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mWaqdsPFLMXD4rS8HAAcOg.png" /></figure><p>Now we need to <strong>protect our shopping cart page and home page from unauthenticated users.</strong></p><p>We can use onAuthStateChanged, from Firebase. We also use the useHistory hook to push a new route.</p><pre><strong>import { getAuth, onAuthStateChanged } from &quot;firebase/auth&quot;;</strong><br><strong>import { useHistory } from &#39;react-router-dom&#39;;</strong></pre><pre>import &quot;./styles.css&quot;;</pre><pre>export const ShoppingCartPage = () =&gt; {</pre><pre><strong>const history = useHistory();</strong></pre><pre>const [order, setOrder ] = useState([]);</pre><pre>const orderContext = useContext(PetsOrderContext);</pre><pre>useEffect ( () =&gt; {<br>    setOrder(orderContext.order);<br>  }, [orderContext])</pre><pre><strong>useEffect(<br>    () =&gt; {<br>        const auth = getAuth();<br>        onAuthStateChanged(auth, (user) =&gt; {<br>            if (user) {<br>              // ...<br>            } else {<br>                history.push(&#39;/login&#39;)</strong></pre><pre><strong>            }<br>        }); <br>     }, []<br>)</strong></pre><p>And likewise to the home page. And any other pages we have.</p><p>We check for the authenticated user, if there isn’t one, we route them to the login page.</p><h3>~~~~~~~~~~~ Part 4— Adding your own Firebase db/api and posting to it.</h3><p>Start by creating a free, google account. Then open the following link to create a new Google Firebase project. The account will be under Google’s Spark plan which is 100% free.</p><p>Click get started. <a href="https://firebase.google.com/">https://firebase.google.com/</a>. Follow the steps. You need to be signed in to your google account. This project will be created under your google account (gmail).</p><h4>Firebase Set Up</h4><p>If you already have a project you can re-use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MnwOOB1wSB4a2KZzN8Dq8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tksv3uzknl7YeeIfV1gO2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TDnxi6X-E4AN2e-2dFGMLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9iP_5mRwE6lQuidxSSnqng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MElYDhs175GyMZXybJQjIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kDUYovnxZUYhwmt8DnIS0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*FizEZOChLB_8VGJ3VlGWCg.png" /></figure><p>After you are done going through the wizard to create a new project. Y</p><p><strong>You will need to add “Firebase firestore” database to the project.</strong> Firestore is a scalable noSQL database on the cloud. Since Firebase has a ton of other features like authentication, you can add a Database, Cloud Storage, etc. But for now, only add the Firestore Database.</p><p>Click create database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZaumixakxYvS0aZyun0-Pw.png" /></figure><p>Follow the instructions. Select<strong> test mode</strong> for now. Then choose a location, anything in north america will be fine for our purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7bEQhrCMKzPlRxrndL5tFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmy_ZlNK_v1WkZjiDpI47A.png" /></figure><p>Once ready, you can now create a table, or a collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxbQP0RtwHotxkEBV4HCtA.png" /></figure><p>Click start collection, and enter the name of your data, for example pets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d2mrRH9lLxnMxCfKA_BVMQ.png" /></figure><p>Click auto id, to auto generate an ID. This will be non repeatable and completely unique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*92H3hvMGxjowFadHGa9-dw.png" /></figure><p>Then start by adding your first pet. They are called documents. Choose your data, and their data types.</p><ul><li>column name</li><li>type: number, string, boolean ..etc</li><li>value: ..</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-PvTh-HftUc1kgAWGZv01w.png" /></figure><p>Please make sure to add <strong>ALL these fields.</strong></p><ul><li>age, breed, id, image, isAdopted, name, petType</li><li>If you forget any it will break the react app, as it is expecting all of these values.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bfvjHlvEJMvsDcM2GzeYfQ.png" /></figure><p>To add more, click add Document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*r7UqGITZNNHyHX193KWH0g.png" /></figure><p>To edit existing documents, you can select them by clicking on them, and click the add field button.</p><p>You can also edit values using the pencil icon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSc-VYW0kx-dYtGyX6PS9w.png" /></figure><h4><strong>Getting the free automatic API from the firestore database</strong></h4><p>The firestore database automatically can give you a FREE simple API to use. Since your data is in test mode, it is public.</p><p>All you need is your project id. You can grab that from the project settings.</p><p>ex. pet-store-a6611</p><p>Then plop it into this default API url:</p><p><a href="https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/">https://firestore.googleapis.com/v1/projects/<strong>PROJECTID</strong>/databases/(default)/documents/pets/</a></p><p>Ex.</p><p><a href="https://firestore.googleapis.com/v1/projects/pet-store-a6611/databases/(default)/documents/pets/">https://firestore.googleapis.com/v1/projects/<strong>pet-store-a6611</strong>/databases/(default)/documents/pets/</a></p><p>And that will give us a list of all our documents..we can use this JSON object inside our react app!</p><h4>Using it in our react app</h4><p>Let’s replace the current API with our own. Inside PetsHomePage update the fetch statement with our url we just obtained from the prev step:</p><pre>const getPets = async() =&gt; {<br>    try {<br>      const response = await fetch(&#39;<a href="https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/&#39;);"><strong>https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/</strong>&#39;);</a></pre><p>Now our data should be displayed.</p><h4>Adding a new pet form to submit data to the API.</h4><h4>Creating the submission form</h4><p>We create a new folder in the pages folder NewPetPage. And we create index.js and styles.css.</p><p>Here we will make a form for submitting a new pet item using react-hook form. We register all the inputs, and add a submit button.</p><pre>import { useForm } from &quot;react-hook-form&quot;;<br>  <br>import &quot;./styles.css&quot;;<br>import { useState } from &quot;react&quot;;<br>export const NewPetPage = () =&gt; {<br>  <br>   const { register, handleSubmit } = useForm();</pre><pre>   return (<br>      &lt;div className=&quot;pets-page&quot;&gt;<br>          &lt;form className=&quot;form-layout&quot; onSubmit={handleSubmit(submitPet)}&gt;<br>            &lt;h2&gt;Submit a new pet: &lt;/h2&gt;<br>            &lt;br /&gt;<br>  <br>            &lt;label htmlFor=&quot;petType&quot;&gt; Pet Type &lt;/label&gt;<br>            &lt;input<br>              {...register(&quot;petType&quot;)}<br>              name=&quot;petType&quot;<br>              required<br>            /&gt;</pre><pre>&lt;label htmlFor=&quot;name&quot;&gt; Name &lt;/label&gt;<br>            &lt;input {...register(&quot;name&quot;)} name=&quot;name&quot; required type=&quot;text&quot; /&gt;<br>            &lt;label htmlFor=&quot;breed&quot;&gt; Breed &lt;/label&gt;<br>            &lt;input<br>              {...register(&quot;breed&quot;)}<br>              name=&quot;breed&quot;<br>              required<br>            /&gt;<br>            &lt;label htmlFor=&quot;image&quot;&gt; Image Url &lt;/label&gt;<br>            &lt;input<br>              {...register(&quot;image&quot;)}<br>              name=&quot;image&quot;<br>              required<br>            /&gt;</pre><pre>&lt;label htmlFor=&quot;age&quot;&gt; Age &lt;/label&gt;<br>            &lt;input<br>              {...register(&quot;age&quot;)}<br>              name=&quot;age&quot;<br>              required<br>            /&gt;</pre><pre>&lt;label htmlFor=&quot;id&quot;&gt; Unique ID &lt;/label&gt;<br>            &lt;input<br>              {...register(&quot;id&quot;)}<br>              name=&quot;id&quot;<br>              required<br>            /&gt;</pre><pre>&lt;input type=&quot;submit&quot; value=&quot;Submit Pet&quot; /&gt;</pre><pre>&lt;br /&gt;<br>          &lt;/form&gt;<br>        )<br>      &lt;/div&gt;<br>    );<br>  };</pre><h4>Creating the submit function to the API</h4><p>Then we add the <strong>submitPet</strong> function. We must format our data from the form to fit Google Firebase API requirements. The body of the request must follow a special syntax, fields.. string value.</p><p>Then we use fetch to send a POST request to our API.</p><pre>const submitPet = async (formVals) =&gt; {</pre><pre>      const formattedData = {<br>            fields: {<br>                id: {<br>                    stringValue: formVals.id<br>                },<br>                breed: {<br>                    stringValue: formVals.breed<br>                },<br>                age: {<br>                    stringValue: formVals.age<br>                },<br>                name: {<br>                    stringValue: formVals.name<br>                },<br>                petType: {<br>                    stringValue: formVals.petType<br>                },<br>                image: {<br>                    stringValue: formVals.image<br>                },<br>                isAdopted: {<br>                    booleanValue: false<br>                },</pre><pre>      }<br>            }<br>      console.log(formVals, formattedData);<br>      try {<br>        const response = await fetch(&#39;<a href="https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/&#39;,"><strong>your-api</strong>&#39;,</a><br>        {<br>            headers: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;<br>            },<br>            method: &quot;POST&quot;,<br>            body: JSON.stringify(formattedData)<br>        })<br>      } catch (error) {<br>        console.log(&quot;Error&quot;, error);<br>      }<br>    };</pre><p>Then we can route the user back to the home page when they finish this form, we import</p><pre>import { useHistory } from &quot;react-router-dom&quot;;</pre><p>We use the hook to grab a hold of our page history.</p><pre>export const NewPetPage = () =&gt; {<br>  <br>    const { register, handleSubmit } = useForm();<br><strong>    const history = useHistory();</strong></pre><p>Then inside of the request once it passes we route them to “/”</p><pre>try {<br>        const response = await fetch(&#39;<a href="https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/&#39;,">https://firestore.googleapis.com/v1/projects/pets-api-40916/databases/(default)/documents/pets/&#39;,</a><br>        {<br>            headers: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;<br>            },<br>            method: &quot;POST&quot;,<br>            body: JSON.stringify(formattedData)<br>        })<br><strong>        history.push(&#39;/&#39;);<br></strong>      } catch (error) {</pre><h4>Add the route to the router and navbar</h4><p><strong>Let’s add this new route and page to our App.js inside our router.</strong></p><p>We should import it at the top.</p><pre>import { NewPetPage } from &#39;./components/pages/NewPetPage&#39;;</pre><p>Then we add the new route, ‘/new’</p><pre>       &lt;Route exact path=&quot;/new&quot;&gt;<br>          &lt;NewPetPage /&gt;<br>        &lt;/Route&gt;</pre><p>Then we need to add a link in our navigation menu to this page. Inside navbar, index.jsx, we add a new link to the ‘/new’ page.</p><pre>import {<br>    NavLink<br>} from &quot;react-router-dom&quot;;</pre><pre>import { FaStore, FaShoppingCart} from &#39;react-icons/fa&#39;;</pre><pre>import &quot;./styles.css&quot;<br>import { Logout } from &quot;../Logout&quot;;<br>export const Navbar = () =&gt; {<br>    return (<br>        &lt;nav className=&quot;navbar&quot;&gt;<br>            &lt;ul className=&quot;navbar-list&quot;&gt;<br>                &lt;li&gt;<br>                    &lt;NavLink exact={true} activeClassName=&quot;nav-selected&quot; to=&quot;/&quot;&gt;Pets&lt;/NavLink&gt;<br>                &lt;/li&gt;<br>                &lt;li&gt;<br>                    &lt;NavLink activeClassName=&quot;nav-selected&quot; to=&quot;/cart&quot;&gt; My Cart&lt;/NavLink&gt;<br>                &lt;/li&gt;<br><strong>                &lt;li&gt;<br>                    &lt;NavLink activeClassName=&quot;nav-selected&quot; to=&quot;/new&quot;&gt; Add new pet&lt;/NavLink&gt;<br>                &lt;/li&gt;</strong><br>                &lt;li&gt;<br>                    &lt;Logout /&gt;<br>                &lt;/li&gt;<br>            &lt;/ul&gt;<br>        &lt;/nav&gt;<br>    )<br>}</pre><p>Click this link should take you to the form. When you submit a new pet, it should display on your home page!</p><h3>~~~~~~~~~~~ Part 5..</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4d9354c95dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React useContext hook to make an alert / notification system for your entire application]]></title>
            <link>https://jujuontheweb.medium.com/react-usecontext-hook-to-make-an-alert-notification-system-for-your-entire-application-721b4c6b7d0f?source=rss-f8e8ba70a756------2</link>
            <guid isPermaLink="false">https://medium.com/p/721b4c6b7d0f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[usecontext]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[alerts]]></category>
            <dc:creator><![CDATA[Jumanah Al Asadi]]></dc:creator>
            <pubDate>Thu, 14 Oct 2021 17:52:03 GMT</pubDate>
            <atom:updated>2021-10-22T16:31:14.465Z</atom:updated>
            <content:encoded><![CDATA[<p>Need a way to trigger alerts from anywhere in your React or Nextjs app? A great way to utilize, useContext. 🆒</p><p>We will use <strong>React</strong> <strong>context</strong> to store a global state for an app wide notification / alert, which can be updated at anytime, from any component.</p><p><strong>Let’s start off by creating a new context using React</strong>, in the context folder (create one if you don’t have it already), we can call it notificationContext.js</p><p><em>context /notificationContext.js</em></p><ul><li>Import React</li><li>Create a context using <strong>React.createContext({})</strong> pass it empty values or the shape for what your global state should look like, as well as your own methods to update it. Here we include the global state variables and the methods to update the global state.</li></ul><pre>import React, { useState } from &#39;react&#39;;</pre><pre>const NotificationContext = React.createContext({<br>  notification: null,<br>  notificationText: null,<br>  success: () =&gt; {},<br>  error: () =&gt; {},<br>});</pre><p>We can also define our alert states, as constants, in this file. This is optional, but good to do. (optional) 🚦</p><pre>const STATES = {<br>  SUCCESS: &#39;success&#39;,<br>  ERROR: &#39;error&#39;,<br>};</pre><p><strong>Then we create a NotificationProvider component</strong> from the React context we created earlier. This Context provider component is used as a wrapper, to wrap around our entire application, so that the app is nested inside it. It will give all our application access to set the notification state and to clear it with the functions we defined up above.</p><p>This component will have the actual implementation of the state and the methods to update it.</p><p>The state variables will be:</p><ul><li>notification: which stores the type (“success”, “error”)</li><li>notificationText: which stores the custom message to display</li></ul><p>The function to update the state will be:</p><ul><li>success (text): called with a text to display a green success message ✅</li><li>error (text): called with a text to display a red error message 🔴</li><li>clear: called to clear the alert / notification</li></ul><pre>const NotificationProvider = (props) =&gt; {<br>  const [notification, setNotification] = useState(null);<br>  const [notificationText, setNotificationText] = useState(null);</pre><pre>const success = (text) =&gt; {<br>    window.scroll(0, 0);<br>    setNotificationText(text);<br>    setNotification(STATES.SUCCESS);<br>  };</pre><pre>const error = (text) =&gt; {<br>    window.scroll(0, 0);<br>    setNotificationText(text);<br>    setNotification(STATES.ERROR);<br>  };</pre><pre>const clear = () =&gt; {<br>    setNotificationText(null);<br>    setNotification(null);<br>  };</pre><pre>return (<br>    &lt;NotificationContext.Provider<br>      value={{<br>        success, error, clear, notification, notificationText,<br>      }}<br>    &gt;<br>      {props.children}<br>    &lt;/NotificationContext.Provider&gt;<br>  );<br>};</pre><p>Then we export both the context and the provider at the end of the file. We need to import them later to actually use them.</p><pre>export { NotificationProvider };<br>export default NotificationContext;</pre><p>We need to allow our components to have access to this globalstate and these functions to update it<strong>. To do this, let’s wrap the Notification provider component around our entire application, </strong>we can do this wherever our main app lives. This can be app.js or index.js. We used props.children so anything nested inside this wrapper component will be displayed as before.</p><p><em>app.js</em></p><pre>import { NotificationProvider } from &#39;context/notificationContext&#39;;</pre><pre>function App() {<br> <br>...</pre><pre>return (<br>        &lt;NotificationProvider&gt;<br>          &lt;Router&gt;<br>           ...<br>          &lt;/Router&gt;<br>        &lt;/NotificationProvider&gt;<br>  );<br>}</pre><p>After we wrap the provider around our app, it is now available for use, with the useContext hook!</p><p>Something else we still need to also create an Alert or Notification component to display this notification which exists inside context.</p><p>Inside components, <strong>create a component called</strong> <strong>Notification.</strong></p><p>This component will always be displayed at the top of your application. It might not always render, if the notification is set to null. It will only display if a notification is present in the global state or context.</p><p>It will take from the context the <strong>notification</strong> state to style the component accordingly (please add your styles), and the <strong>notificationText</strong> state to display the correct message. This is a simplified version of the notification alert component.</p><ul><li>Import useContext hook from React</li><li>Pass it your context</li><li>Now you can reference your context.</li></ul><p><em>components/Notification/index.js</em></p><pre>import React from &#39;react&#39;;<br>import { useContext } from &#39;react&#39;;</pre><pre>import NotificationContext from &#39;context/notificationContext&#39;;</pre><pre>const NotificationBar = () =&gt; {<br> <strong> const notificationCtx = useContext(NotificationContext);</strong></pre><pre>return (<br>    notificationCtx.notification !== null &amp;&amp; (<br>       &lt;div className={notificationCtx.notification}&gt;</pre><pre>         &lt;p&gt; notificationCtx.notificationText &lt;/p&gt;</pre><pre>       &lt;/div&gt;<br>    )<br>  );<br>};</pre><pre>export default NotificationBar;</pre><p><strong>Then we will need to display this component, somewhere. Preferably, in app.js, </strong>because it should be rendered / overlaying, for the entire app. Note: Make sure to put it within the notification provider wrapper component, because it also needs access to the context as well!</p><p><em>app.js</em></p><pre>import { NotificationProvider } from &#39;context/notificationContext&#39;;<br>import NotificationBar from &#39;components/Notification&#39;;</pre><pre>function App() {<br> <br>...<br>return (<br>        &lt;NotificationProvider&gt;<br><strong>          &lt;NotificationBar /&gt;</strong></pre><pre>          &lt;Router&gt;<br>           ...<br>          &lt;/Router&gt;<br>        &lt;/NotificationProvider&gt;<br>  );<br>}</pre><p>Ok great — but now we have no alert or notification because we still haven’t called a success or error alert yet to set the notification state.</p><p>So anywhere we want to trigger an alert or notification we need to call the context functions.</p><ul><li>We import the context we created and useContext hook from React</li><li>We call the methods, success or error with the text we want to display.</li></ul><p>So in any random component or page in your application. Do the same..</p><p><em>components/Project/index.js</em></p><p>Note: In the below example, we are fetching a project from an API, and when it fails we display an error notification.</p><pre>import { useState, useEffect, <strong>useContext</strong> } from &#39;react&#39;;<br><strong>import NotificationContext from &#39;context/notificationContext&#39;;<br></strong>const axios = require(&#39;axios&#39;);</pre><pre>const Project = () =&gt; {</pre><pre><strong>  const notificationCtx = useContext(NotificationContext);  </strong></pre><pre><strong>  </strong>useEffect(() =&gt; {<br>    fetchProject();<br>  }, []);</pre><pre>  const fetchProject = async () =&gt; {</pre><pre>try {<br>      const response = await axios.get(`${process.env.apiServer}/${projectId}`);<br><strong>      notificationCtx.success(&#39;Success: Project was fetched!&#39;);</strong></pre><pre>    } catch (err) {<br>      console.log(err);<br><strong>      notificationCtx.error(&#39;Technical Error: Error fetching data&#39;);<br></strong>     }<br> }</pre><pre> return ( .. ) <br>};</pre><pre>export default Project</pre><p>That’s all you need! 🆒 🆒 🆒</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=721b4c6b7d0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use React hook form with your custom form components!]]></title>
            <link>https://jujuontheweb.medium.com/how-to-use-react-hook-form-with-your-custom-form-components-a86a1a77cf3c?source=rss-f8e8ba70a756------2</link>
            <guid isPermaLink="false">https://medium.com/p/a86a1a77cf3c</guid>
            <category><![CDATA[react-hook-form]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Jumanah Al Asadi]]></dc:creator>
            <pubDate>Thu, 14 Oct 2021 03:35:23 GMT</pubDate>
            <atom:updated>2021-10-14T18:05:39.863Z</atom:updated>
            <content:encoded><![CDATA[<p>How to get this working with a simple validation schema and a custom input component!</p><p><a href="https://react-hook-form.com/">React Hook Form</a></p><ul><li>A newer way to handle form submission and form validation-</li><li>A little easier to use than Formik</li></ul><p>Install it into your project using npm:</p><pre>npm install react-hook-form</pre><h3>Set up needed in the main form</h3><p>In our <strong>Form component</strong>, you can declare the <strong>useForm</strong> hook from react-hook-form, and import all the properties we need.</p><p>The <strong>register</strong> method helps you register an input field into the React Hook Form so that it is available for the validation and its value can be tracked for changes. We pass this as a prop, to all our input fields.</p><p>The <strong>reset </strong>method allows us to reset all our form values after we submit or if we click a reset button. We just call it whenever we need it. Optional!</p><p>The <strong>handleSubmit </strong>method, is called as soon as the user submits the form and it is valid. It will allow us to call our own submit function and pass the values to it.</p><p>The <strong>formState / errors </strong>allows us to grab our errors and messages. We will use the errors array to display errors under form fields or at the top of page.</p><pre>import &quot;./styles.css&quot;;<br>import { useForm } from &quot;react-hook-form&quot;;<br>import Input from &quot;../input-field&quot;;<br></pre><pre>export const NewTodoForm = (props) =&gt; {</pre><pre>const {<br>    register,<br>    handleSubmit,<br>    reset,<br>    formState: { errors },<br>  } = useForm();</pre><pre>const onSubmit = (data) =&gt; {<br>    console.log (data);<br>    reset();<br>  };</pre><pre>return (<br>    &lt;form onSubmit={handleSubmit(onSubmit)}&gt;<br>      &lt;h1 className=&quot;form-title&quot;&gt;Create a new Todo&lt;/h1&gt;</pre><pre>      &lt;Input<br>        type=&quot;text&quot;<br>        name=&quot;title&quot;<br>        label=&quot;Todo (e.g do laundry)&quot;<br>        errors={errors}<br>        register={register}<br>        validationSchema={{ <br>          required: &quot;Todo text is required&quot;,<br>          minLength: {<br>            value: 3,<br>            message: &quot;Please enter a minimum of 3 characters&quot;<br>          }<br>        }}<br>        required<br>      /&gt;</pre><pre>      &lt;Input<br>        type=&quot;date&quot;<br>        name=&quot;date&quot;<br>        label=&quot;Due Date&quot;<br>        errors={errors}<br>        register={register}<br>        validationSchema={{ <br>          required: &quot;Todo deadline is required&quot;<br>        }}<br>        required<br>       /&gt;</pre><pre>      &lt;input type=&quot;submit&quot; /&gt;<br>    &lt;/form&gt;<br>  );<br>};</pre><p>It is important to note, that for validation we pass a validationSchema prop to our custom input component which just follows the syntax</p><pre>validationSchema={{ <br>          required: &quot;Todo text is required&quot;,<br>          minLength: {<br>            value: 3,<br>            message: &quot;Please enter a minimum of 3 characters&quot;<br>          }<br>     }}</pre><p>So we could also add other things in our validationSchema like:</p><ul><li><strong>required: </strong>Indicates if the field is required or not. If this property is set to true then the field cannot be empty. (already shown in the above example ✅)</li><li><strong>minlength</strong> and <strong>maxlength:</strong> sets the minimum and maximum length for a string input value.</li><li><strong>type: </strong>Indicates the type of the input field; it can be email, number, text, or any other standard HTML input types.</li><li><strong>pattern: </strong>Defines a pattern for the input value using a regular expression.</li></ul><h3>Set up needed in the Custom Input component</h3><ul><li>Whenever we make forms, we usually create a reusable input component</li><li>Since all input components will have a label, input field, error messages, validation, etc..</li><li>We can define this all once and re-use it for all our input fields</li></ul><p>So we pass all these as props..</p><p>Regarding react-hook-form, we pass the <strong>register</strong> function, and we call it inside the HTML input itself.</p><p><strong>{…register(name, validationSchema)}</strong></p><p>As you can see below we pass it an object of <strong>validationSchema</strong> object obtained from the main form as a prop. We also pass it the name of the input field to register it properly to the react-hook-form. This way it can validate it correctly.</p><p>We also pass the <strong>errors</strong> array from the react-hook-form which has a list of all the errors, for the entire form. These errors names all correspond to the validationSchema we defined and passed earlier from the form itself. They will fall under the name of input field, and the type of error (required, minLength, maxLength, pattern ..etc)</p><pre>import &quot;./styles.css&quot;;</pre><pre>const Input = ({ name, label, register, errors, required, type, validationSchema }) =&gt; (</pre><pre>  &lt;div className=&quot;form-control-input&quot;&gt;<br>    &lt;label htmlFor={name}&gt;<br>      {label}<br>      {required &amp;&amp; &quot;*&quot;}<br>    &lt;/label&gt;<br>    &lt;input<br>      id={name}<br>      name={name}<br>      type={type}<br>      {...register(name, validationSchema)}<br>    /&gt;<br>    {errors &amp;&amp; errors[name]?.type === &quot;required&quot; &amp;&amp; (<br>      &lt;span className=&quot;error&quot;&gt;{errors[name]?.message}&lt;/span&gt;<br>    )}<br>    {errors &amp;&amp; errors[name]?.type === &quot;minLength&quot; &amp;&amp; (<br>      &lt;span className=&quot;error&quot;&gt;{errors[name]?.message}&lt;/span&gt;<br>    )}<br>  &lt;/div&gt;</pre><pre>);</pre><pre>export default Input;</pre><h3>That’s it!</h3><p>If your form was validated correctly, you can submit your data to an API or something alternative to save it, as the values will be passed to your handleSubmit function</p><pre>const onSubmit = (data) =&gt; {<br>    console.log (data);<br>    reset();<br>  };<br>return (<br>    &lt;form onSubmit={handleSubmit(onSubmit)}&gt;</pre><pre>  ...</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a86a1a77cf3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Amazon DynamoDB locally]]></title>
            <link>https://jujuontheweb.medium.com/running-amazon-dynamodb-locally-a417504ef227?source=rss-f8e8ba70a756------2</link>
            <guid isPermaLink="false">https://medium.com/p/a417504ef227</guid>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[dynamodb-local]]></category>
            <dc:creator><![CDATA[Jumanah Al Asadi]]></dc:creator>
            <pubDate>Thu, 07 Oct 2021 16:09:50 GMT</pubDate>
            <atom:updated>2021-10-07T16:09:50.367Z</atom:updated>
            <content:encoded><![CDATA[<p>Since DynamoDB is a cloud no sql DB, there are limited ways to run it locally on premise. In this article, we will discuss using a local dynamoDB instance so you do not incur unnecessary costs on the cloud. This can be used for running tests or local development.</p><h3>Running DynamoDB Locally</h3><p>AWS DynamoDB is a serverless no sql cloud database. It is a little different to use offline, so one simple way to create an offline instance of it, is to use the DynamoDB Docker image available by Amazon on Docker Hub. This way we will not incur costs on the cloud when we are running our tests.</p><p>The quickest way to do this is to install Docker Desktop on your computer, <a href="https://docs.docker.com/get-docker/">https://docs.docker.com/get-docker/</a></p><p>Then once it is installed, and running. Pull the Amazon DynamoDB docker image from Docker hub: <a href="https://hub.docker.com/r/amazon/dynamodb-local">https://hub.docker.com/r/amazon/dynamodb-local</a></p><pre>docker pull amazon/dynamodb-local</pre><p>Then you can run this docker image at any time using the docker run command. It will be available on localhost:8000. <strong>Make sure the docker container is running when accessing it.</strong></p><pre>docker run -p 8000:8000 amazon/dynamodb-local</pre><h3>Accessing a local DynamoDB from Node.js: Setup using AWS-SDK</h3><p>Assuming you already have a node.js already project set up. You should also already have an AWS Account and be familiar with the AWS-SDK.</p><ul><li>Environment variables containing AWS access keys, and secret access keys, region, port, Database Table names, etc</li></ul><p>Now you would like to connect to the local instance of DynamoDB instead of the cloud one, for local testing.</p><p>To do this you need to install the Amazon SDK in your node project. You might already have it installed if you were using the cloud database or any other AWS services.</p><p><a href="https://www.npmjs.com/package/aws-sdk">https://www.npmjs.com/package/aws-sdk</a></p><pre>npm i aws-sdk</pre><p>You’ll also need to create a file for your AWS Configuration, it can be named as:</p><pre>aws-config.js</pre><p>Inside this file, you can include the table name, and your access keys.</p><pre>module.exports = {<br>    aws_table_name: process.env.DYNAMODB_TABLENAME,<br>    aws_local_config: {<br>      //Provide details for local configuration<br>    },<br>    aws_remote_config: {<br>      accessKeyId: process.env.AWS_ACCESS_KEY_ID,<br>      secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,<br>      region: process.env.AWS_DEFAULT_REGION,<br>    }<br>};</pre><p>Inside your environment variables file, you should add the following:</p><pre>DYNAMODB_LOCAL_ADDRESS=<a href="http://localhost:8000/">http://localhost:8000</a><br>DYNAMODB_TABLENAME=</pre><p>Once that is all done, we are ready to set up a connection to the local DB and feed it some data, create some tables. etc.</p><p>Every time we stop and start the docker container, it will lose all its data, so we need to call this function to set up the tables every time the server starts. Please do not save any important information in this table as it will not be persisted.</p><p>Let’s create a file to set up a local db, so can import it into our main index.js</p><pre>local-db.js</pre><p>Inside this file we just created we will add the following:</p><ul><li>require the aws-sdk</li><li>import some mock data to insert into our table (optional)</li><li>define a table using the DynamoDB schema, passing it the table name and the primary key (id)</li></ul><pre>const AWS = require(&#39;aws-sdk&#39;);<br>const awsConfig = require(&#39;./aws-config&#39;);<br>const data = require(&#39;../tests/mockData/data.json&#39;);</pre><pre>const table = {<br>    TableName : process.env.DYNAMODB_TABLENAME,<br>    KeySchema: [<br>        { AttributeName: &quot;id&quot;, KeyType: &quot;HASH&quot;},<br>    ],<br>    AttributeDefinitions: [<br>        { AttributeName: &quot;id&quot;, AttributeType: &quot;S&quot; },<br>    ],<br>    ProvisionedThroughput: {<br>        ReadCapacityUnits: 5,<br>        WriteCapacityUnits: 5<br>    }<br>};</pre><ul><li>define a function to create this table and insert some data into it</li><li>We will perform async operations, therefore this function will need to be labelled as async</li><li>We use the dynamodb.<strong>createTable</strong> function</li><li>If the tables already exist, we do not create them again</li><li>(Optional) We also feed in dummy data if we need it, using the dynamodb<strong>.put — </strong>Using a loop here to insert multiple records.</li></ul><pre>const createDynamoDBLocal = async() =&gt; {<br>    (&quot;Setting up local dynamo db.. make sure docker container is running.&quot;)<br>    AWS.config.update({<br>        region: process.env.AWS_DEFAULT_REGION,<br>        endpoint: process.env.DYNAMODB_LOCAL_ADDRESS,<br>      });</pre><pre><br>// create table    <br>    const dynamodb = new AWS.DynamoDB();<br>try {<br>        const data = await dynamodb.listTables({Limit: 10}).promise();<br>if (data.TableNames.length &gt;= 1) {<br>            console.log (&quot;Existing docker container already running.&quot;)<br>} else {<br>            await dynamodb.createTable(table).promise();</pre><pre><br>// optional to add dummy data </pre><pre>const client = new AWS.DynamoDB.DocumentClient();<br>const params = {<br>            TableName: process.env.DYNAMODB_TABLENAME,<br>            Item: data<br>        };<br>await client.put(params).promise();<br>params.TableName = process.env.DYNAMODB_TABLENAME;<br>        <br>   data.forEach( async(item) =&gt; {<br>            params.TableName = process.env.DYNAMODB_TABLENAME;<br>            params.Item = item;<br>            await client.put(params).promise();<br>        });<br>    } catch (err) {<br>        console.log (err)<br>    }<br>}</pre><ul><li>Then we will create another function in this file which just returns an instance of the DynamoDB client, so we can use it in our app. The DocumentClient makes it easier to interact with our DB.</li></ul><pre>const getDynamoDBLocal = () =&gt; {<br>    AWS.config.update({<br>        region: process.env.AWS_DEFAULT_REGION,<br>        endpoint: process.env.DYNAMODB_LOCAL_ADDRESS,<br>    });</pre><pre>const dynamoClient = new AWS.DynamoDB.DocumentClient();     <br>    return dynamoClient; <br>}</pre><ul><li>At the end of this file we export both functions so we can use them in our application:</li></ul><pre>module.exports = {<br>    createDynamoDBLocal,<br>    getDynamoDBLocal<br>};</pre><h3>Accessing a local DynamoDB from Node.js: Using it in your app</h3><p>Inside <strong>index</strong>.<strong>js</strong> or your main app, app.js (the entry point to your application)</p><p>If you are an a test or development environment, you can initialize the local database with tables and dummy data, otherwise you can just use the cloud db. We can call this as soon as our server starts.</p><p>In my situation, I am using it when running tests, so when my NODE_ENV is set to test. When this is the case, first I will await the tables and dummy data to be inserted.</p><pre>if (process.env.NODE_ENV == &quot;test&quot;) {<br>    console.log(&quot;Creating tables for local DynamoDB docker container&quot;)<br>    const localDb = async () =&gt; {<br>        await createDynamoDBLocal();<br>    }<br>    localDb();<br>}</pre><p>In your controllers, routes or endpoints, you can refer to the local-db file to grab this local instance and make updates to it directly. <strong>Make sure your docker and docker container is running! If you stop and start the container, you will need to re-run the server to run the function that creates the tables.</strong></p><p>Add this to the top of the file, above all your endpoints.</p><pre>const { getDynamoDBLocal} = require(&#39;../aws/local-db&#39;);</pre><pre>let dynamoDB = &#39;&#39;;</pre><pre>if (process.env.NODE_ENV == &quot;test&quot;) {        <br>    <strong>dynamoDB</strong> = getDynamoDBLocal();<br>} else {<br>    // connect to the cloud dynamo db<br>}</pre><p>For example, here is a request to delete a record, and we will use the dynamoDB reference we created up above at the top of the file.</p><pre>const deleteRecord = async (req, res) =&gt; {<br>    try {<br>        const id = req.params.id;<br>        <br>        const params = {<br>            TableName: process.env.DYNAMODB_TABLENAME,<br>            Key:{<br>                &quot;id&quot;: id,<br>            }<br>        };<br>        <br>        const result = await <strong>dynamoDB</strong>.delete(params).promise();</pre><pre>        res.send({<br>            success: true,<br>        });</pre><pre>} catch (error) {<br>        console.log(error)<br>        res.status(400).send({<br>            success: false,<br>            message: error<br>        });<br>    }<br>}</pre><p>Hope this helps :)</p><p>Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a417504ef227" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting an Excel file to JSON in Node: Beginner-Friendly Introduction to Node.js + NPM]]></title>
            <link>https://javascript.plainenglish.io/converting-an-excel-file-to-json-in-node-beginner-friendly-introduction-to-node-js-npm-2b994b7bca1e?source=rss-f8e8ba70a756------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b994b7bca1e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[excel]]></category>
            <dc:creator><![CDATA[Jumanah Al Asadi]]></dc:creator>
            <pubDate>Mon, 19 Jul 2021 18:25:46 GMT</pubDate>
            <atom:updated>2021-07-20T15:50:28.688Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting started with Node.js by parsing an excel file and learning about NPM and XLSX in the process.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xT-r5vqQ8NcbyBzs" /><figcaption>Photo by <a href="https://unsplash.com/@goumbik?utm_source=medium&amp;utm_medium=referral">Lukas Blazek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Node.js?</h3><p>When we think JavaScript, we think browser, websites, web pages, interactivity, event listeners, onclick, etc. These are all related to the browser.</p><p>In fact, the browser used to be the only runtime environment for JavaScript. So whenever we wrote javascript we would only really see it in action once we open a web page on the browser.</p><p>This limited JavaScript from being used outside of the browser. But now, we can run JavaScript code almost anywhere…how? By installing the one they call, <strong>node</strong>. Node is a new environment for JavaScript.</p><p>Now there are<strong> two ways to run JavaScript:</strong></p><ol><li>On a browser environment</li><li>On a Node.js environment</li></ol><p>So to summarize what Node.js is:</p><ul><li>Node is a new(ish) runtime environment for JavaScript.</li><li>Node can be installed on any server, it&#39;s open-source and free</li><li>Node allows us to run JavaScript outside the browser, on a server for example</li><li>Node allows us to write backend or server code in javascript! Before this was not possible, you had to use Java or PHP for instance.</li></ul><h3>Now that you have heard of the great almighty Node, it’s time to install Node.js on your local computer</h3><p>Please follow the instructions on the official website: <a href="https://nodejs.org/en/download/">https://nodejs.org/en/download/</a></p><p>To check node is properly installed run this command in your terminal:</p><pre>node --version</pre><h3>What about NPM? Node’s equally cool best friend!</h3><p>So node also has this really cool thing that comes with it called <strong>NPM</strong>. You don’t need to install it separately, it will be there after you install node.</p><p>It stands for: <strong>node package manager.</strong></p><p>Because node is open source, and developers are nice people (usually), developers can expose their projects for other developers to use. This way other developers can benefit and they don’t need to write code from scratch.</p><p>All these nice developers need to do is turn their code into a module and, they can publish it on npm as a <strong>package</strong>.</p><p>NPM acts as an online marketplace for packages that anybody can use for free to help them out with their project.</p><p>For example, to do complex excel processing in our project, we can install a third-party npm package and use it instead of building that logic from scratch. That way we can reduce our development time and focus on our own features.</p><p>To use npm, simply go and look for the package you desire (if one exists) on the npm website. In this article, we will use a package I discovered called <strong>XLSX</strong></p><ul><li><a href="https://www.npmjs.com/package/xlsx">https://www.npmjs.com/package/xlsx</a></li></ul><p>To choose the right package from several other packages that do the same thing, you look for the following key considerations:</p><ul><li>check out the weekly downloads = more popular = better package</li><li>make sure it was updated recently = good support</li><li>read and make sure it has good documentation = easy to use</li></ul><p>To install a package, you need to use a command with npm. You need to be in your project folder and run this:</p><pre>npm install package_name</pre><p>When you install a third-party package in your project, you are thereby creating a dependency. This means your project depends on another project. This can get messy right? Luckily, npm will manage your dependencies in your project for you.. more on that later! (Hint: package.json)</p><p>So anytime somebody wants to run your app npm will look for dependencies and grab the depending code from npm and download it into your local project.</p><h3>Learn by example! Let’s start a node project from scratch!</h3><p>Let’s make an application to parse an excel file from our file system and convert it into a json file. Notice how we are going to use javascript to do this, and we don’t even need the browser to do anything.</p><p>Alrighty, so to get started, make a folder for your project. Create an<strong> index.js file</strong>, this will be where our code will be.</p><p>Then run the command npm init to create an official node project:</p><pre>npm init</pre><ul><li>Say yes to all the default options</li></ul><p>Ok interesting, so you will see a new file <strong>package.json </strong>that just came about, lets go check it out. Seems like it has some data about our project, okay cool! We will come back to it later..</p><p>Alright with that file there, we can do an npm install on a package we chose. Let’s install the excel package from before, <strong>xslx. </strong>This package will allow us to parse our excel and convert it into JSON!</p><pre>npm install xlsx</pre><p>OK now let’s go back into our<strong> package.json</strong> and see what happened!</p><p>We can see a new object of<strong> dependencies</strong> { } in our file. In here, there is “xlsx” and the version number. NPM automatically adds our packages in here whenever we do an npm install. NPM keeps track of all the dependencies we install so that when people are running the project for the first time, npm knows what dependencies we need to install to get this project fully working!</p><p>Ahh, something else changed too, what is this package-lock.json that appeared?!</p><p>NPM will also auto-generate a<strong> package-lock.json</strong>, you don’t need to manage this or edit it at all. It’s like a snapshot of package.json. So don’t worry too much about it. You shouldn’t push or publish this to your git repo either. It’s just used locally by npm.</p><p>The last thing that we see that also got created was the<strong> node_modules</strong> folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cu3OM535zkqZ1OQA4UOycw.png" /></figure><p>Hold on a second… where did all of these folders come from, I only recognize XLSX, the one that I installed. Okay, so let&#39;s open the XLSX folder, and we will see all the code for this package that we can use in our app, so that’s good. Seems like a nice developer made this all ready to use for us. Cool cool cool!</p><p>Just like any other node project, the XLSX project will also have its own package.json and its own dependencies. Let’s open up that package.json and take a look at the dependencies.</p><pre>&quot;dependencies&quot;: {<br>&quot;adler-32&quot;: &quot;~1.2.0&quot;,<br>&quot;cfb&quot;: &quot;¹.1.4&quot;,<br>&quot;codepage&quot;: &quot;~1.14.0&quot;,<br>&quot;commander&quot;: &quot;~2.17.1&quot;,<br>&quot;crc-32&quot;: &quot;~1.2.0&quot;,<br>&quot;exit-on-epipe&quot;: &quot;~1.0.1&quot;,<br>&quot;fflate&quot;: &quot;⁰.3.8&quot;,<br>&quot;ssf&quot;: &quot;~0.11.2&quot;,<br>&quot;wmf&quot;: &quot;~1.0.1&quot;,<br>&quot;word&quot;: &quot;~0.3.0&quot;<br>},</pre><p>Ahhuhhh so that’s where all those other folders in our <strong>node_modules </strong>came from. XLSX has its own dependencies.</p><p>So as you can see npm is really useful because it allows us to run any project with dependencies just by doing npm install, it will know to install all of those dependencies for us and place them in the node modules folder.<strong> It will also install the dependencies, of the dependencies! :-)</strong></p><p>So node_modules has all the code of our dependencies. As such it can be large in size.</p><p>In fact, since we have that package.json file that tells us exactly what we need to download and install, we don’t need to publish the entire node_modules folder since the code can be downloaded at any time using the package.json. That is the whole point of the package.json file. ^_^</p><p>So anytime you download a node project, the first thing you do is run NPM INSTALL, this will look at all the package.json(s) and download all the code from npm and place it in <strong>node_modules.</strong></p><pre>npm install</pre><h4><strong>Best practice:</strong> In order to not push this large folder, what we typically do is add this in the <strong>.gitignore</strong> file</h4><pre>node_modules/</pre><p>And this will not publish the node_modules/ folder to your repo. Saving you time and space! :)</p><h4>Using an npm package</h4><p>OK the fun part, — now it&#39;s time to actually code haha *finally*, so let&#39;s go back into our index.js file. This is a javascript file! Coding in Node is just like javascript really, so if you know javascript you will be fine! You just need to know the extra features node gives you such as access to your server’s file system!</p><p>The first thing we need to do is bring in the package we installed as a dependency, so this is done with the <strong>require </strong>syntax<strong>. </strong>This will look in the node_modules folder for that package and if it’s there it will give you access to the functionality.</p><pre>const xlsx = <strong>require</strong>(‘xlsx’);</pre><p>This is the syntax. You can name the variable what you like but the correct syntax is require(‘package name’);</p><p>So the app we are going to build today is going to take data from an excel file and convert it to JSON and save it as a JSON file on your server.</p><p>As I said, we are going to need a third-party open-source package called <strong>xlsx.</strong></p><p>We will also need access to the file system. This is built-in with node so you don’t need to npm install this. But you do need to require it.</p><pre>var <strong>fs</strong> = <strong>require</strong>(‘fs’);</pre><p>Alright so let&#39;s just bring in an excel file to this project in the root directory. Please make a note of the name of the file. For this article, I create an Excel file named Data.xlsx and I added it to my project folder.</p><p>So let&#39;s write our function to convert an excel file to JSON. We will make use of <strong>xlsx.readFile() and xlsx.utils.sheet_to_json(). </strong>Without these functions, we would have to create these functions ourselves.</p><ul><li>xlsx.readFile(filePath) — accepts a file name / path</li><li>xlsx.utils.sheet_to_json(sheet) — converts a single sheet into JSON</li></ul><pre>function convertExcelFileToJsonUsingXlsx() {</pre><pre>    // Read the file using pathname<br>    const file = xlsx.readFile(&#39;./Data.xlsx&#39;);</pre><pre>    // Grab the sheet info from the file<br>    const sheetNames = file.SheetNames;<br>    const totalSheets = sheetNames.length;</pre><pre>    // Variable to store our data <br>    let parsedData = [];</pre><pre>    // Loop through sheets<br>    for (let i = 0; i &lt; totalSheets; i++) {</pre><pre>        // Convert to json using xlsx<br>        const tempData = xlsx.utils.sheet_to_json(file.Sheets[sheetNames[i]]);</pre><pre>        // Skip header row which is the colum names<br>        tempData.shift();</pre><pre>        // Add the sheet&#39;s json to our data array<br>        parsedData.push(...tempData);<br>    }</pre><pre> // call a function to save the data in a json file</pre><pre> generateJSONFile(parsedData);<br>}</pre><p>Let&#39;s now write another function to store our excel data in a JSON file on our server. Let&#39;s make a new function for that to separate our logic.</p><p>As you can see below we use the built-in node <strong>fs.writeFileSync </strong>method which accepts a file path/file name and the data we are writing to that file. We wrap it in a try-catch in case it fails.</p><ul><li><strong>writeFileSync() —</strong></li></ul><pre>function generateJSONFile(data) {<br>    try {<br>        fs.writeFileSync(&#39;data.json&#39;, JSON.stringify(data))<br>    } catch (err) {<br>        console.error(err)<br>    }<br>}</pre><p>Let’s call our function at the top of the file.</p><pre>convertExcelFileToJsonUsingXlsx();</pre><p>This is the first function that will run once we execute this file. It will convert the excel file to JSON and then call the second function to save the data into a JSON file.</p><h3>Speaking of running it…how do we run this node project?</h3><p>So we don’t need to run our code on the browser anymore! We just run it with node. We can run it anywhere a node environment exists. With that said, the simplest way to run our code is simply using just the following command:</p><pre>node index.js</pre><p>After we run this command, node will run all the contents of index.js, just like any other javascript file, it will execute code line by line. You can see the output is indeed a JSON file of all our data! This means our code works! Yay!</p><p>Another way to run our code is with <strong>npm start. </strong>To make this work, you must go to the package.json file and update the <strong>scripts</strong> object. We add a new start script, so that we are able to call npm <strong>start</strong>. Notice how it is set to <strong>node index.js</strong> which is an equivalent command. Note: in the scripts object you can define other commands like npm test to run your tests.</p><pre>“scripts”: {</pre><pre>  “test”: “echo \”Error: no test specified\” &amp;&amp; exit 1&quot;,</pre><pre>  “start”: “node index.js”</pre><pre>},</pre><p>So now we can use the command <strong>npm start</strong> instead of node index.js to start our application. This is more normal and what people are used to when running a project.</p><p>Ta-da! Congrats on trying out your first NPM package and running your first node project.</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b994b7bca1e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/converting-an-excel-file-to-json-in-node-beginner-friendly-introduction-to-node-js-npm-2b994b7bca1e">Converting an Excel file to JSON in Node: Beginner-Friendly Introduction to Node.js + NPM</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>