<?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 Zeyad on Medium]]></title>
        <description><![CDATA[Stories by Zeyad on Medium]]></description>
        <link>https://medium.com/@zeyadelmarsafy?source=rss-e71a362ed3e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*O3ErErYQu6nSffmzxI-BaA.jpeg</url>
            <title>Stories by Zeyad on Medium</title>
            <link>https://medium.com/@zeyadelmarsafy?source=rss-e71a362ed3e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 23:22:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zeyadelmarsafy/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[You only need 3 lists in your Todo App]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@zeyadelmarsafy/you-only-need-3-lists-in-your-todo-app-122a5279fc50?source=rss-e71a362ed3e1------2"><img src="https://cdn-images-1.medium.com/max/2600/1*4Kf3OBiSZ9ntrOlHGz69bA@2x.jpeg" width="3240"></a></p><p class="medium-feed-snippet">Hi, whatever you use to organize your tasks, you only need three types of lists in your todo app to organize everything in your days.</p><p class="medium-feed-link"><a href="https://medium.com/@zeyadelmarsafy/you-only-need-3-lists-in-your-todo-app-122a5279fc50?source=rss-e71a362ed3e1------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@zeyadelmarsafy/you-only-need-3-lists-in-your-todo-app-122a5279fc50?source=rss-e71a362ed3e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/122a5279fc50</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[work]]></category>
            <category><![CDATA[career-advice]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[self]]></category>
            <dc:creator><![CDATA[Zeyad]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 19:52:47 GMT</pubDate>
            <atom:updated>2024-09-06T19:53:49.580Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Setup Feature flags in Nextjs App router without third parties]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@zeyadelmarsafy/setup-feature-flags-in-nextjs-app-router-without-third-parties-44d3bc9ae540?source=rss-e71a362ed3e1------2"><img src="https://cdn-images-1.medium.com/max/1920/1*oNLc4uGjSo985b0G6qoYOw.jpeg" width="1920"></a></p><p class="medium-feed-snippet">Hello, This is a post to discuss a way to setup the feature flags inside your nextjs project with app router without needing &#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@zeyadelmarsafy/setup-feature-flags-in-nextjs-app-router-without-third-parties-44d3bc9ae540?source=rss-e71a362ed3e1------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@zeyadelmarsafy/setup-feature-flags-in-nextjs-app-router-without-third-parties-44d3bc9ae540?source=rss-e71a362ed3e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/44d3bc9ae540</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Zeyad]]></dc:creator>
            <pubDate>Sat, 31 Aug 2024 03:21:55 GMT</pubDate>
            <atom:updated>2024-09-06T19:55:24.515Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[TypeScript, Understanding the code you write]]></title>
            <link>https://blog.devgenius.io/typescript-understanding-the-code-you-write-983c2d5ae9b9?source=rss-e71a362ed3e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/983c2d5ae9b9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Zeyad]]></dc:creator>
            <pubDate>Thu, 23 May 2024 03:17:12 GMT</pubDate>
            <atom:updated>2024-08-27T16:25:08.283Z</atom:updated>
            <content:encoded><![CDATA[<p>TypeScript has given the frontend a powerful chance to deliver reliable and maintainable code. The more you correctly type your code, the more you fall into its strengths and importance. In this post, I’ll mention some TypeScript tips that you may or may not know about.</p><h3>How TypeScript works?</h3><p>The first thing you should know is how TypeScript works?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/0*uCUgjfEZFFTZHbWa.png" /></figure><p><a href="https://gist.github.com/zeyadetman/e2435ca1e2e0fe78d3dc981250e42499">Source</a></p><p>Browsers are designed to only understand JavaScript, just as computers are designed to only understand zeros and ones. In the case of computers, we compile high-level code to machine code and then to zeros and ones so the computer can understand it. Similarly, we transpile or translate TypeScript code to JavaScript code to be understood by browsers and other engines that only know JavaScript.</p><p>To do this, we may use the popular tsc tool, You can also check out the <a href="https://github.com/JohnDeved/awesome-typescript-compilers?tab=readme-ov-file">awesome-typescript-compilers</a> repository to learn more about them.</p><p>For example, code like this:</p><pre>type animals = &quot;cat&quot; | &quot;dog&quot;;<br>const getAnimal = (animal: animals) =&gt; animal;<br>getAnimal(&quot;cat&quot;);</pre><p>Is translated to this JavaScript code, so browsers can understand it:</p><pre>const getAnimal = (animal) =&gt; animal;<br>getAnimal(&quot;cat&quot;);</pre><p>Note: TypeScript code is eliminated in the transpiling process.</p><p>This leads us to an important conclusion: once you realize it, you’ll notice a lot about TypeScript concepts and why they’ve been written in their particular way.</p><p>Conclusion: As TypeScript does not run on browsers, it only runs at compile time, not at runtime.</p><blockquote>Compile time is the time when your code is being built, before it runs and becomes interactive. Run time is when your code is running and interacting with the client.</blockquote><h3>Differences in Action</h3><p>Let’s compare a typed language that checks types at runtime, like C#, with TypeScript, which checks types at compile time:</p><h4>Function overloading</h4><blockquote>Some JavaScript functions can be called in a variety of argument counts and types. For example, you might write a function to produce a Date that takes either a timestamp (one argument) or a month/day/year specification (three arguments). <a href="https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads">Resource</a></blockquote><p>In C#, we can achieve function overloading by declaring multiple function arguments and bodies. This is possible because C# checks the type of the function arguments at runtime and defines the function body accordingly:</p><pre>void display() { ... }<br>void display(int a) { ... }<br>float display(double a) { ... }<br>float display(int a, float b) { ... }</pre><p>However, in TypeScript, we go to the runtime without types, without typescript itself, so there’s no runtime type checks and then we can’t assign multiple values to the same variable in javascript, or in other words we can’t create multiple bodies for the same function.</p><pre>function makeDate(timestamp: number): Date;<br>function makeDate(m: number, d: number, y: number): Date;<br>function makeDate(m: number, d: string, y: number): string;<br>function makeDate(<br>  mOrTimestamp: number,<br>  d?: number | string,<br>  y?: number<br>): Date | string {<br>  if (typeof d === &quot;string&quot;) {<br>    return &quot;hello&quot;;<br>  }</pre><pre>  if (d !== undefined &amp;&amp; y !== undefined) {<br>    return new Date(y, mOrTimestamp, d);<br>  } else {<br>    return new Date(mOrTimestamp);<br>  }<br>}</pre><pre>const d1 = makeDate(1234);<br>const d2 = makeDate(5, 5, 5);</pre><p>This will be compiled to this Javascript code:</p><pre>function makeDate(mOrTimestamp, d, y) {<br>  if (typeof d === &quot;string&quot;) {<br>    return &quot;hello&quot;;<br>  }<br>  if (d !== undefined &amp;&amp; y !== undefined) {<br>    return new Date(y, mOrTimestamp, d);<br>  } else {<br>    return new Date(mOrTimestamp);<br>  }<br>}</pre><pre>const d1 = makeDate(1234);<br>const d2 = makeDate(5, 5, 5);</pre><p>There’s libraries can do runtime checks for javascript, one of the most popular libraries do this is <a href="https://zod.dev/">zod</a> you can give it a try.</p><h3>Narrowing (make it more specific)</h3><h3>keyof and typeof</h3><ul><li>keyof from its name, used to &quot;extract&quot; a key of a TYPE, and since objects are the only datatype that contains keys, then keyof is used to extract key of an object in a union format</li></ul><pre>type obj = { [n: number]: string };<br>type A = keyof obj; // number</pre><ul><li>typeof from its name, used to return the type of a variable. simple!</li></ul><pre>let str = &quot;Alia&quot;;<br>type a = typeof str; // string</pre><pre>const str2 = &quot;Alia&quot;;<br>type b = typeof str2; // &quot;Alia&quot;</pre><p>Important note: I used let here instead of const. If I used const, then the type would be the specific string value itself.</p><p>Let’s merge both</p><pre>const obj = {<br>  id: 1,<br>  name: &quot;Alia&quot;,<br>}; // javascript variable no types</pre><pre>type typeOfObj = typeof obj; // type of the javascript object<br>type keysOfObj = keyof typeOfObj; // id | name</pre><pre>type keysOfObjOneLine = keyof typeof obj;</pre><p>Notice here</p><ul><li>keyof extracts keys of type (object).</li><li>typeof extracts the type of variable.</li></ul><p><em>keep this in your mind for the mapped types section.</em></p><h3>in operator and extends</h3><p>Similar to the previous section, in operator is kinda similar way you can use it to limit the key to be within a group of types</p><pre>type keysOfObj = &quot;id&quot; | &quot;name&quot;;<br>type obj = { [key in keysOfObj]: string };</pre><pre>// type obj = {<br>//  id: string;<br>//  name: string;<br>// }</pre><p>But we need to modify the code to fix the type for the id key to be number not string</p><ul><li>extends consider it as if else of typescript.</li></ul><pre>type keysOfObj = &quot;id&quot; | &quot;name&quot;;<br>type obj = { [key in keysOfObj]: key extends &quot;id&quot; ? number : string };</pre><pre>// That&#39;s it</pre><p><em>This called mapped types</em></p><h3>Generics</h3><p>Think about it as a function in javascript, if you have a type and you’re repeating it with slight changes, then you probably need to use generics.</p><pre>interface BasicType&lt;T&gt; {<br>  input: T;<br>}</pre><pre>const x: BasicType&lt;string&gt; = { input: &quot;test&quot; };<br>const y: BasicType&lt;number&gt; = { input: &quot;test&quot; }; // wrong</pre><pre>function basic(a, b) {<br>  return { a, b };<br>}</pre><pre>function basic&lt;A, B&gt;(a, b) {<br>  return { a, b };<br>}</pre><pre>function basic&lt;A, B&gt;(a: A, b: B): { a: A; b: B } {<br>  return { a, b };<br>}</pre><pre>basic&lt;string, number&gt;(&quot;hello&quot;, 2);</pre><p>we can still use extends with generics to give a powerful type.</p><h3>Typescript Coverage</h3><p>In addition to adding TypeScript rules to your project, it’s important to track TypeScript code coverage. Code coverage helps identify missing types for variables.</p><p>You might think it’s obvious if a variable has a type, but when using third-party libraries, classes, or functions, it’s easy to miss some. Not everything, such as query parameters, will be tracked by the TypeScript coverage library, but it definitely helps.</p><p>I suggest using <a href="https://www.npmjs.com/package/typescript-coverage-report">typescript-coverage-report</a> for this purpose. If you know of a better option, feel free to share it in the comments below.</p><p>Resources:</p><ul><li><a href="https://www.typescriptlang.org/docs/">TypeScript Documentation</a></li><li><a href="https://github.com/type-challenges/type-challenges">type-challenges</a></li><li><a href="https://typehero.dev/">typehero.dev</a></li></ul><p><a href="https://notes.zeyadetman.com/programming-languages/typescript">Find more…</a></p><p><em>While writing this post, civilians and children in Gaza are being killed in the ongoing genocide. It’s important to be informed about what is happening in Palestine and to consider the humanitarian aspects of the situation. Please take the time to research, and understand the events and their impact on palestinian’s lives. </em><a href="https://blog.paulbiggar.com/i-cant-sleep/"><em>know more</em></a></p><p><a href="https://zeyadetman.com/posts/typescript-understand-the-code-you-write"><em>originally published here</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=983c2d5ae9b9" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/typescript-understanding-the-code-you-write-983c2d5ae9b9">TypeScript, Understanding the code you write</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configure Keycloak instance to run on localhost using https on macOS]]></title>
            <link>https://medium.com/@zeyadelmarsafy/configure-keycloak-instance-to-run-on-localhost-using-https-on-macos-a88540cbc94d?source=rss-e71a362ed3e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a88540cbc94d</guid>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[keycloakjs]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Zeyad]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 03:51:02 GMT</pubDate>
            <atom:updated>2024-01-22T03:51:02.706Z</atom:updated>
            <content:encoded><![CDATA[<p>Originally Published Here: <a href="https://notes.zeyadetman.com/keycloak/handle-https">https://notes.zeyadetman.com/keycloak/handle-https</a></p><h3>Prerequisites<a href="https://notes.zeyadetman.com/keycloak/handle-https#prerequisites">§</a></h3><ul><li>You’re using macOS.</li><li>You have keycloak instance running on your machine.</li><li>I’ll use chrome for this tutorial.</li></ul><h3>Problems<a href="https://notes.zeyadetman.com/keycloak/handle-https#problems">§</a></h3><p>The problem is we need to serve from two ports, the first one is the keycloak admin instance (Keycloak Dashboard), and the second one is the client which uses the keycloak service. we need to serve them via the secure protocol <strong>https</strong>.</p><h3>Your connection is not private<a href="https://notes.zeyadetman.com/keycloak/handle-https#your-connection-is-not-private">§</a></h3><p>So when we try to use https on localhost, we’ll face <em>your connection is not private</em> error, because we’re serving localhost via https</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6OK4cvtvTK8pLA3G.png" /></figure><p>To Solve this error All you have to do is write chrome://flags in the chrome url, and then search for <em>Allow invalid certificates for resources loaded from localhost.</em> to enable it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ToPuUBofaPdVEeNY.png" /></figure><p>Great! So now we can do the request to localhost with an invalid certificate.</p><h3>Certificate is not valid<a href="https://notes.zeyadetman.com/keycloak/handle-https#certificate-is-not-valid">§</a></h3><p>Now we’re facing this error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/0*U1kNJPqhLCpDt4TD.png" /></figure><p>When you click over it, you’ll see that the certificate is not valid, in the next steps we’ll trust this certificate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/0*BGF8E5JnsqU2wNdb.png" /></figure><p>To solve this issue, we need to trust the certificate on our machine, to do this</p><ol><li>Click on <em>Certificate is not valid</em> button.</li><li>You’ll see a Certificate Viewer popup, Click on the details tab.</li><li>Click on <strong>Export</strong> and select <strong>PKCS #7, single certificate</strong>.</li><li>Open <strong>Keychain Access</strong> app on your macOS and select <strong>Login</strong>.</li><li>File &gt; Import Items &gt; select the file/certificate you’ve exported from chrome.</li><li>Click on the certificate &gt; Trust &gt; Always Trust.</li></ol><p>Great! Now we passed the localhost issue for the client.</p><p>The last step is creating a new certificate for keycloak instance, and trust it on our machine.</p><h3>Keycloak certificate<a href="https://notes.zeyadetman.com/keycloak/handle-https#keycloak-certificate">§</a></h3><p>To create a new certificate on macOS, copy this command and put it on your terminal</p><pre>openssl req -x509 -out localhost.crt -keyout localhost.key \  -newkey rsa:2048 -nodes -sha256 \  -subj &#39;/CN=localhost&#39; -extensions EXT -config &lt;( \   printf &quot;[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth&quot;)</pre><p>This will create two files for you, the first one is localhost.crt the certificate itself, and the second one is the localhost key, we’ll use both in the keycloak folder configuration so you can copy them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/0*XndkIvx2oXkDi1PU.png" /></figure><p>You can use them via a keycloak/certs folder.</p><ul><li>localhost.crt -&gt; keycloak-server.pem</li><li>localhost.key -&gt; keycloak-server-key.pem</li></ul><p>You can also use this command</p><pre>bin/kc.[sh|bat] start --https-certificate-file=/path/to/certfile.pem --https-certificate-key-file=/path/to/keyfile.pem</pre><h3>Resources<a href="https://notes.zeyadetman.com/keycloak/handle-https#resources">§</a></h3><ul><li><a href="https://www.keycloak.org/server/enabletls">https://www.keycloak.org/server/enabletls</a></li><li><a href="https://letsencrypt.org/docs/certificates-for-localhost/">https://letsencrypt.org/docs/certificates-for-localhost/</a></li></ul><p><a href="https://notes.zeyadetman.com/"><em>Have you learned something new? Want to learn more?</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a88540cbc94d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Copy Changed Files between git branches]]></title>
            <link>https://medium.com/@zeyadelmarsafy/copy-changed-files-between-git-branches-98c3779fa163?source=rss-e71a362ed3e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/98c3779fa163</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[gi̇t]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Zeyad]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 14:42:22 GMT</pubDate>
            <atom:updated>2024-01-21T14:42:22.456Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Originally Published Here: </em><a href="https://notes.zeyadetman.com/git/copy-changed-files-between-git-branches"><em>https://notes.zeyadetman.com/git/copy-changed-files-between-git-branches</em></a></p><h3>Intro</h3><p>In some cases, <a href="https://git-scm.com/docs/git-cherry-pick">cherry-pick</a> commits will be tough when you&#39;re working on a git project with a long history and a group of contributors. Conflicts may eat your time and focus leading you to a uncertainty action, or i mean action with no validation either it&#39;s wrong or right.</p><h3>Some situations could be solved with different solutions</h3><p>The solution that will be introduced in this post is tailored specifically to some certain situations, just keep it in your mind, you may find it helpful to you someday.</p><ol><li>Generate a file of the changed files by your fingers using your email</li></ol><pre>git log --author &quot;YOUR_EMAIL&quot; --oneline --pretty=format:%H | sort -u  | xargs -I {} git show --pretty=format: --name-only {} &gt; changed_files.txt</pre><p>The file will be something like this</p><pre>path/file.txt<br>path/folder/file.ts</pre><ol><li>Create a new clone of the project with the destination branch.</li><li>Copy the files from the generated changed file to the destination repo, I use <a href="https://man7.org/linux/man-pages/man1/rsync.1.html">rsync</a> instead of <a href="https://man7.org/linux/man-pages/man1/cp.1.html">cp</a> to copy using the full path.</li></ol><pre>rsync -a --files-from=changed_files.txt . ../cloned-repo-destination-branch</pre><blockquote><em>[!warning] The commands run on macOS, find the suitable command lines that do the same thing on your OS.</em></blockquote><h3>Let’s explain the terminal commands</h3><ul><li>Log the commits hashes by specific author using its email</li></ul><pre>git log --author &quot;YOUR_EMAIL&quot; --oneline --pretty=format:%H</pre><ul><li>Sort and Just pick the unique, we just need the changed files without repetition.</li></ul><pre>sort -u</pre><ul><li>To show just the commit changed files we use this line</li></ul><pre>git show --pretty=format: --name-only &quot;hash&quot;</pre><ul><li>Until then we have a list of commits hashes, we need to view the changed files in each commit. we will use <a href="https://man7.org/linux/man-pages/man1/xargs.1.html">xargs</a> here to get the input from the prev commands using pipes</li></ul><pre>xargs -I {}</pre><p>Some resources</p><ul><li><a href="https://mpov.timmorgan.org/use-rsync-instead-of-cp/">https://mpov.timmorgan.org/use-rsync-instead-of-cp/</a></li></ul><blockquote><em>[!note] Use chatGPT to explain that more If you’re still have questions, you can also share your thoughts with me, or use chatGPT to explain the commands more to you, also you can use google.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98c3779fa163" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving User Experience with Optimistic Updates: A Simple Technique to Implement Interactive…]]></title>
            <link>https://medium.com/@zeyadelmarsafy/improving-user-experience-with-optimistic-updates-a-simple-technique-to-implement-interactive-7bf103f7b34d?source=rss-e71a362ed3e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bf103f7b34d</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[user-experience]]></category>
            <dc:creator><![CDATA[Zeyad]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 10:36:40 GMT</pubDate>
            <atom:updated>2023-03-29T10:36:40.852Z</atom:updated>
            <content:encoded><![CDATA[<h3>Improving User Experience with Optimistic Updates: A Simple Technique to Implement Interactive Features</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*An2VU88FN4LZtDB3" /><figcaption>Photo by <a href="https://unsplash.com/@charlesdeluvio?utm_source=medium&amp;utm_medium=referral">charlesdeluvio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post, I’ll share some thoughts about improving user experience/interactivity for your app with one simple technique called <strong>Optimistic Updates</strong>.</p><p>In simple words, <strong>Optimistic Updates</strong> is updating the UI depending on the optimistic response without waiting for the actual response from the server that may return with an error.</p><p>Let’s go with an example that demonstrates the goal of that and how can we implement it.</p><h3>The Like button on Twitter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*azXvOwFJEWcEXRNm" /></figure><p>Imagine that you could be assigned a task to implement a like feature on user tweets, <strong>The task is</strong> when someone clicked on the like icon, you should make an HTTP request to the server to add it to users’ likes, also do a UI change to make this icon active. Keep in mind that the request may fail (ex. user deleted it, your session is expired,…etc).</p><p><strong>The slow way</strong> to implement this feature is first doing the request, waiting for the response, then update the UI based on the response. <strong>Why</strong> when the user clicked on the like icon he expects that he liked the tweet and everything has gone well, but the UI hasn’t reflected that there’s a lag between the user clicks and the HTTP response. This lag could be solved by the <strong>Optimistic Update.</strong></p><p>In the <strong>Optimistic Update</strong> solution, we’ll update the UI directly based on the optimistic response based on user input, and make the HTTP call, then when the response gives us everything is ok, then no extra work from our side, otherwise, we’ll roll back the UI change to the state before the user clicks.</p><p>Check out the behavior here from <a href="https://www.apollographql.com/docs/react/performance/optimistic-ui">Apollo GrahpQL Client Docs</a>, you’ll notice the adding item to the list displayed it directly before the app get a response, while editing a list item is not doing the same.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fgithub%2Fapollographql%2Fdocs-examples%2Ftree%2Fmain%2Ffull-stack%2Ftodo-list%2Ftodo-list-client%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fm8g52&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fm8g52%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/798a71f4c0ed04be8bfa7189e9ea113b/href">https://medium.com/media/798a71f4c0ed04be8bfa7189e9ea113b/href</a></iframe><p>What if the user clicks on a button multiple times in a use case like <a href="http://medium.com/">medium.com</a> clap button?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*1K4VuoO3SFDnnsVl.gif" /></figure><p>We can do the Optimistic update as well, but we can add a <strong>debounce</strong> functionality to it.</p><p><a href="https://www.freecodecamp.org/news/javascript-debounce-example/"><strong>Debounce</strong></a> means calling a function but after waiting some time until the user finishes his interactivity. The benefit here is doing as minimum as possible of HTTP requests, we just send the final user clicks to the backend but keep the UI updated with the optimistic value.</p><p>In conclusion, optimistic updates can greatly improve the user experience of your app by reducing lag and increasing interactivity. By implementing this simple technique, you can update the UI instantly based on user input, without waiting for a response from the server. This can help your app feel more responsive and increase user engagement. Additionally, adding a debounce functionality can reduce the number of HTTP requests and make your app even more efficient. So next time you’re working on an interactive feature for your app, consider implementing optimistic updates to take your user experience to the next level.</p><p><em>Resources:</em></p><ul><li><a href="https://swr.vercel.app/docs/mutation#optimistic-updates">https://swr.vercel.app/docs/mutation#optimistic-updates</a></li><li><a href="https://tanstack.com/query/v4/docs/react/guides/optimistic-updates">https://tanstack.com/query/v4/docs/react/guides/optimistic-updates</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bf103f7b34d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I built my portfolio using NextJS, Typescript, and Chakra UI]]></title>
            <link>https://medium.com/@zeyadelmarsafy/how-i-built-my-portfolio-using-nextjs-typescript-and-chakra-ui-f9fc5451ede2?source=rss-e71a362ed3e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9fc5451ede2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Zeyad]]></dc:creator>
            <pubDate>Mon, 07 Mar 2022 05:08:50 GMT</pubDate>
            <atom:updated>2022-03-07T05:08:50.644Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post I’ll go with you in a detailed way on how I created my blog/portfolio from scratch using NextJS and Chakra UI, from creating the pages and posts markdown files to displaying them as HTML files, And how I handled newsletter service and deploying the project on Vercel, Handling custom domains. So this post will be good for you if you want to know more about anything that I’ve implemented here on my blog.</p><p><a href="https://github.com/zeyadetman/zeyadetman.com"><strong>Here’s the source code for this site.</strong></a></p><h3>NextJS + Typescript + Chakra UI</h3><p><a href="https://nextjs.org/">NextJS</a> is one of the strongest frameworks to build a production project. I&#39;ve used some features like SSG or pre-render pages at build time, API routes, file-system routing, fast refresh, configuration, and deployments are super easy.</p><p>To get started just write this <a href="https://nextjs.org/docs/api-reference/create-next-app">npx create-next-app@latest --ts</a>.</p><p>The structure of the portfolio goes like that:</p><pre>.<br>├── components<br>│   ├── Admin<br>│   ├── CareerStack<br>│   ├── ColorModeIcon<br>│   ├── Footer<br>│   ├── Layout<br>│   ├── MarkdownRender<br>│   ├── Navbar<br>│   └── Newsletter<br>├── configs<br>├── interfaces<br>├── libs<br>├── pages<br>│   ├── api<br>│   │   └── auth<br>│   └── posts<br>├── public<br>│   └── static<br>│       ├── images<br>│       └── sounds<br>├── styles<br>│   └── theme<br>└── utils</pre><p>NextJS uses the `pages` folder to handle the app routes, as you may know, if you created a file called `pages/hello.tsx` you can open it by visiting `your-app.com/hello` and that’s super cool. So I created a folder called pages to handle the routes for the app. Also, I created another folder called `components` to handle the react components that will be used across the pages.</p><p>Another feature of using NextJS is creating API routes, To do so you can create this folder pages/api and then create your APIs inside it.</p><p>If you’re building your projects with javascript, then you have to try <a href="https://www.typescriptlang.org/">typescript</a>, Typescript will definitely help you document your code as you go, Also it forces you to use the right type so this will decrease the bugs and speed up your productivity while you&#39;re coding.</p><p>Here’s the styling part, I use <a href="https://chakra-ui.com/">chakra-ui</a> for creating reactjs components and styles without writing CSS. Also, Chakra UI is handling the app color mode, and much more in the styling part. You can customize the theme, declaring the default values for the app you can check this folder for further information about this styles/theme.</p><p>In the mode icon that appears at the top of the site, I’ve used two things to get this icon based on the current weather of your location. On your first visiting the app, I’m getting your location from https://geolocation-db.com/json/ then store it in the cookies with max-age=3600 expired after 60minutes. When I got your location, I got also the location&#39;s weather, then display the icon based on weather. I implemented the logic in this file components/ColorModeIcon/index.tsx.</p><h3>Name pronunciation</h3><p>You probably have heard the pronunciation of my name when you clicked on the sound icon next to my name on the home page.</p><p>For this sound I just used <a href="https://github.com/atifazam/vocalizer">Vocalizer</a> and downloaded my name&#39;s sound. Added it to webpack config to identify the file extension and location next.config.js</p><pre>1config.module.rules.push({<br>2  test: /\.mp3$/,<br>3  use: {<br>4    loader: &#39;file-loader&#39;,<br>5    options: {<br>6      publicPath: &#39;/_next/static/sounds/&#39;,<br>7      outputPath: &#39;static/sounds/&#39;,<br>8      name: &#39;[name].[ext]&#39;,<br>9      esModule: false,<br>10    },<br>11  },<br>12});</pre><p>And used it like below inside the onClick event handler for the icon:</p><pre>1const audio = new Audio(&#39;/static/sounds/zeyad_ar.mp3&#39;);<br>2audio.play();</pre><h3>Analytics</h3><p>Analytics is one of the most important parts of any product that users could use. I use Analytics here to just track page views, but in the future, i may use it for event tracking like clicking on the subscription button (Room for improvement).</p><p>To achieve this, I use Google Analytics and <a href="https://github.com/mlomb/countapi-js">countapi-js</a>.</p><p>I faced a problem here while using countapi-js because all of my old analytics have been tracked by Google analytics not countapi-js, and the target is delivering the actual page views for all pages, So I collect the old analytics from GA via this tool <a href="https://ga-dev-tools.web.app/query-explorer/">https://ga-dev-tools.web.app/query-explorer/</a></p><pre>metrics= ga:pageviews<br>dimensions= ga:pagePath</pre><p>After that, I created a function to create a key in countapi-js set the key to page path and the default value is the GA pagePath page views count.</p><pre>1countapi<br>2  .create({<br>3    namespace: site.namespace,<br>4    key: pagePath,<br>5    value: pageViews,<br>6  })</pre><p>For GA, I just added its initialization to _document.tsx file and using it via this line gtag.pageview(url); in the _app.tsx to track all pages listening to router changes.</p><p>So in the final production version, The site is running with two tracking services GA and countapi-js they&#39;re running independently. But I depend on countapi-js to view page views and it delivers the actual count as GA.</p><h3>Posts</h3><p>Here’s the most complicated part of the site, The Blog. But Nextjs made it so simple to organize and retrieve posts, In this section, I’ll go with you how I organized the blog posts files, not how I handled the markdown files, will explain this in the next section. So, Let’s get started.</p><p>One of the biggest features in NextJS is <a href="https://nextjs.org/docs/routing/dynamic-routes">Dynamic Routes</a>. I created two files to handle the structure of the blogs pages/posts/index.tsx and pages/posts/[slug].tsx to handle the posts list, and the post page respectively.</p><p>I created a folder blogs in the project root for the blogs .md files, and in libs/posts.ts file, I created two helper functions getPosts(): Promise&lt;IPost[]&gt; and getPostBySlug(slug: string): Promise&lt;null | IPost&gt; - will explain more in the next section -, And used them in pages/posts/index.tsx and pages/posts/[slug].tsx in getStaticProps() Because we need this data to be updated in build time (rebuilding the site) and that makes sense.</p><p>To know more about nextjs rendering/generating pages/data, look at this <a href="https://static-next-willemliu.vercel.app/">site</a>.</p><p>And here’s how I use Next Link component with Chakra UI Link to do client-side routing, note that we’re using passHref prop to pass href to the Link component. In this way, we guarantee that the [slug].ts is reading the slug correctly using router.query.slug.</p><pre>1// pages/posts/index.tsx<br>2<br>3&lt;NextLink href={`/posts/${fileName}`} passHref&gt;<br>4  &lt;Link<br>5    {...props}<br>6  &gt;<br>7    {post.title}<br>8  &lt;/Link&gt;<br>9&lt;/NextLink&gt;</pre><p>To handle the 404 in the not existing post URLs, I use getStaticPaths() with fallback: false, Here&#39;s its code:</p><pre>1export const getStaticPaths: GetStaticPaths = async () =&gt; {<br>2  const postsSlugs = await getPosts();<br>3  const slugs = postsSlugs.map((post) =&gt; ({<br>4    params: { slug: post?.fileName },<br>5  }));<br>6<br>7  return {<br>8    paths: slugs, // predefined posts urls<br>9    fallback: false, // any paths not returned by getStaticPaths will result in a 404 page<br>10  };<br>11};</pre><p>That’s pretty much for this section, let’s go with the next one, rendering markdown files.</p><h3>Rendering Markdown files</h3><p>From the previous section, you should know that we’re handling the post rendering in the pages/posts/[slug].tsx, So in this section, we&#39;ll discuss the journey from writing the markdown files to rendering them as HTML file.</p><p>Libraries I’ve used to achieve this:</p><ul><li><a href="https://www.npmjs.com/package/gray-matter">gray-matter</a>: Converts a string with front-matter to object.</li><li><a href="https://www.npmjs.com/package/reading-time">reading-time</a>: How long an article will take to read.</li><li><a href="https://www.npmjs.com/package/react-markdown">react-markdown</a>: Markdown component for React using remark.</li><li><a href="https://www.npmjs.com/package/react-syntax-highlighter">react-syntax-highlighter</a>: Syntax highlighting component for React.</li><li><a href="https://www.npmjs.com/package/rehype-raw">rehype-raw</a>: parse the tree again (and raw nodes). Keeping positional info OK.</li><li><a href="https://www.npmjs.com/package/remark-gfm">remark-gfm</a>: remark plugin to support GitHub Flavored Markdown.</li><li><a href="https://www.npmjs.com/package/remark-lint">remark-lint</a>: remark plugin to lint Markdown code style.</li></ul><p>Now we’ve this folder ./blogs/ containing markdown files with front-matter and we need to convert these files to an array of objects, sorted by date.</p><p>The below code snippet is to get the filenames.</p><pre>1// libs/posts.ts<br>2<br>3const { serverRuntimeConfig } = getConfig();<br>4const postsDirectory = path.join(serverRuntimeConfig.PROJECT_ROOT, &#39;blogs&#39;);<br>5const filenames = fs.readdirSync(postsDirectory);</pre><p>Then I iterate over them to get the file contents using gray-matter and its readingTime estimation using reading-time</p><pre>1// libs/posts.ts<br>2<br>3const posts = filenames.map((filename: string) =&gt; {<br>4  const filePath = path.join(postsDirectory, filename);<br>5  const fileContents = fs.readFileSync(filePath, &#39;utf8&#39;);<br>6  const { content, data, excerpt } = matter(fileContents, {<br>7    // eslint-disable-next-line @typescript-eslint/ban-ts-comment<br>8    // @ts-ignore<br>9    // eslint-disable-next-line<br>10    excerpt: (file: any): void =&gt; {<br>11      file.excerpt = file.content<br>12        .split(&#39;\n&#39;)<br>13        .slice(<br>14          0,<br>15          site.post?.excerpt?.noOfLines<br>16            ? site.post?.excerpt?.noOfLines + 1<br>17            : 4<br>18        )<br>19        .join(&#39; &#39;);<br>20    },<br>21  });<br>22<br>23  return {<br>24    content,<br>25    excerpt,<br>26    data,<br>27    fileName: path.parse(filePath).name,<br>28    readingTime: readingTime(content),<br>29  };<br>30});<br>31<br>32const postsSortedByDate = posts.sort(<br>33  (a, b) =&gt; +new Date(b.data.date) - +new Date(a.data.date)<br>34);</pre><p>At this point we’ve the list of posts as objects. That’s super cool! Let’s continue, Now we need a react component to render the post content in html page without breaking the styles/markup language.</p><p>To do this, I’ve created a component MarkdownWrapper using react-markdown wrapper, Here&#39;s what i&#39;ve done:</p><ul><li>For render img tag, I replaced it by next/image component, to handle image optimization on blog post images, Also i just added some styles to force the responsiveness of the rendered images</li></ul><pre>1// components/MarkdownRender/index.tsx<br>2<br>3img({ src, alt }) {<br>4  return (<br>5    &lt;Box width=&quot;100%&quot; className=&quot;post-image-container&quot;&gt;<br>6      &lt;Image<br>7        src={src || &#39;&#39;}<br>8        alt={alt}<br>9        layout=&quot;fill&quot;<br>10        className=&quot;image&quot;<br>11      /&gt;<br>12    &lt;/Box&gt;<br>13  );<br>14},</pre><pre>1/* styles/globals.css */<br>2<br>3.post-image-container {<br>4  width: 100%;<br>5}<br>6<br>7.post-image-container &gt; div {<br>8  position: unset !important;<br>9}<br>10<br>11.post-image-container .image {<br>12  object-fit: contain;<br>13  width: 100% !important;<br>14  position: relative !important;<br>15  height: unset !important;<br>16}</pre><p>There’s an important note here, Don’t forget to update images domains in the next.config.js file.</p><ul><li>For code rendering, I use react-syntax-highlighter and vscDarkPlus theme like below</li></ul><pre>1// components/MarkdownRender/index.tsx<br>2<br>3import { PrismLight as SyntaxHighlighter } from &#39;react-syntax-highlighter&#39;;<br>4import { vscDarkPlus } from &#39;react-syntax-highlighter/dist/cjs/styles/prism&#39;;<br>5<br>6code({ inline, className, children, ...props }) {<br>7  const match = /language-(\w+)/.exec(className || &#39;&#39;);<br>8  const lang = match?.[1] === &#39;js&#39; ? &#39;javascript&#39; : match?.[1];<br>9  return !inline &amp;&amp; match ? (<br>10    &lt;SyntaxHighlighter<br>11      style={vscDarkPlus}<br>12      PreTag=&quot;div&quot;<br>13      showLineNumbers<br>14      showInlineLineNumbers<br>15      language={lang}<br>16      customStyle={{ marginBottom: &#39;2rem&#39; }}<br>17    &gt;<br>18      {String(children).replace(/\n$/, &#39;&#39;) || &#39;&#39;}<br>19    &lt;/SyntaxHighlighter&gt;<br>20  ) : (<br>21    &lt;Code {...props}&gt;{children}&lt;/Code&gt;<br>22  );<br>23},</pre><p>That’s all for this section. You can know more just looking at this file components/MarkdownRender/index.tsx.</p><h3>RSS and Newsletter</h3><p>Okay, Here we have to do two things, first we need a rss.xml file generated from our posts files, second a newsletter service to send my new emails to followers - I hope you&#39;re one of them - And this service is <a href="https://www.getrevue.co/">https://www.getrevue.co/</a> It&#39;s free and promote the newsletter to your twitter profile.</p><p>So first thing we need to do is generating the rss.xml file, so we can list your blog posts as issues in your getrevue account.</p><p>To generate the rss.xml I used <a href="https://www.npmjs.com/package/feed">feed</a> in generateRSSFeed() located here libs/feed.ts and calling it in a getStaticProps() function located in pages/posts/index.tsx to re-generate that file in build time.</p><p>After building and deploying the code I got this url <a href="https://www.zeyadetman.com/rss.xml">https://www.zeyadetman.com/rss.xml</a> with all posts metadata, Heading to <a href="https://www.getrevue.co/app/integrations/rss">https://www.getrevue.co/app/integrations/rss</a>, And add the production url to ADD A FEED input. This will reflect in the issues page on getrevue account.</p><p>I highly recommend enabling Show newsletter on Twitter profile <a href="https://www.getrevue.co/app/integrations/twitter">https://www.getrevue.co/app/integrations/twitter</a>.</p><p>Right now we’ve just configured the newsletter service and RSS feeds. Another thing you may noticed if you want to add their subscription form into your blog, It requires users to confirm subscription from their emails. You can disable this by using getrevue api with double_opt_in: false creating a custom form.</p><p>I used <a href="https://www.npmjs.com/package/react-hook-form">react-hook-form</a> to create the form, Also created an api to handle the request</p><pre>1// pages/api/subscribers.ts<br>2<br>3const subscribeHandler = async (<br>4	req: NextApiRequest,<br>5	res: NextApiResponse&lt;Data&gt;<br>6): Promise&lt;NextApiResponse&lt;Data&gt; | void&gt; =&gt; {<br>7  const { email } = req.body;<br>8<br>9  if (!email) {<br>10    return res.status(400).json({ error: &#39;Email is required&#39; });<br>11  }<br>12<br>13  const result = await fetch(&#39;https://www.getrevue.co/api/v2/subscribers&#39;, {<br>14    method: &#39;POST&#39;,<br>15    headers: {<br>16      Authorization: `Token ${process.env.GETREVUE_API_KEY}`,<br>17      &#39;Content-Type&#39;: &#39;application/json&#39;,<br>18    },<br>19    body: JSON.stringify({ email, double_opt_in: false }), // to disable the confirmation email<br>20  });<br>21<br>22  const data = await result.json();<br>23<br>24  if (!result.ok) {<br>25    return res.status(500).json({ error: data.error.email[0] });<br>26  }<br>27<br>28  return res.status(201).json({ error: &#39;&#39; });<br>29};</pre><p>And used it simply like this</p><pre>1// components/Newsletter/index.tsx<br>2<br>3const { status } = await fetch(&#39;/api/subscribers&#39;, {<br>4  method: &#39;POST&#39;,<br>5  body: JSON.stringify({<br>6    email: data.email,<br>7  }),<br>8  headers: {<br>9    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>10  },<br>11});</pre><p>To read more about handling the subscription form look at this file components/Newsletter/index.tsx, Also to know more about handling https in the custom domains for your getrevue, Please read the deployment section.</p><h3>Deployment</h3><p>The final part is going production. Until now I have implemented the app, and want to go production, I use <a href="https://vercel.com/">vercel</a> it&#39;s the easist way to deploy your nextjs app.</p><p>Create new project, add the github repo of your project, don’t forget to add the environment variables.</p><p>I’ll keep this blog updated whenver I add a new feature to the blog. Just subscribe to the newsletter and I’ll notify you via email.</p><h3>Here’s some resources that helped me:</h3><ul><li><a href="https://vercel.com/docs/concepts/projects/custom-domains#">Custom Domains</a>: This helps me link my godaddy custom domain to vercel deployment.</li><li><a href="http://help.getrevue.co/en/articles/4465817-how-to-make-your-custom-domain-secure-with-ssl">How to make your custom domain secure with SSL</a>: This helps me creating https://feed.zeyadetman.com and added it to getrevue custom domain.</li><li><a href="https://ashleemboyer.com/how-i-added-an-rss-feed-to-my-nextjs-site">How I Added an RSS Feed to My Next.js Site</a>: This helped me generating the rss.xml page.</li><li><a href="https://kswanie21.medium.com/how-to-set-up-godaddy-domain-with-vercel-f42430ed4f6">How to Set up GoDaddy Domain with Vercel</a>.</li></ul><h3>Inspired Blogs:</h3><ul><li><a href="https://francoisbest.com/">https://francoisbest.com/</a></li><li><a href="https://leerob.io/">https://leerob.io/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9fc5451ede2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From ReactJS Class Component to Functional Component — useState (Part 1)]]></title>
            <link>https://medium.com/@zeyadelmarsafy/from-reactjs-class-component-to-functional-component-usestate-part-1-1c04bcaefc17?source=rss-e71a362ed3e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c04bcaefc17</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Zeyad]]></dc:creator>
            <pubDate>Sat, 09 Mar 2019 05:14:25 GMT</pubDate>
            <atom:updated>2019-03-09T05:14:25.211Z</atom:updated>
            <content:encoded><![CDATA[<h3>From ReactJS Class Component to Functional Component — useState (Part 1)</h3><p>Hello everyone, In this post (Two parts) I’ll convert a reactjs code from a class component to a functional component. Focusing on useState and useEffect hooks. let&#39;s begin with the part 1 useState hook.</p><h3>State</h3><h3>In Class Component</h3><p>In the class component, we intialize the state object of this class in the constructorfunction to say this state belongs to this component, and its value intialized in the constuctor. We can change the state by calling setState() passing the new object. Code for this will be something like this</p><pre>import React, { Component } from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;</pre><pre>export default class App extends Component {<br>  constructor() {<br>    super();<br>    this.state = {<br>      count: 0<br>    };<br>  }<br>  render() {<br>    return (<br>      &lt;div className=&quot;App&quot;&gt;<br>        &lt;h1&gt;Current count: {this.state.count}&lt;/h1&gt;<br>        &lt;button onClick={() =&gt; this.setState({ count: this.state.count + 1 })}&gt;<br>          Increment<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>const rootElement = document.getElementById(&quot;root&quot;);<br>ReactDOM.render(&lt;App /&gt;, rootElement);</pre><p>One of the features using setState() is the callback, Yes you can pass a second argument as a callback. Which is a great feature. example on this</p><pre>&lt;button<br>  onClick={() =&gt;<br>    this.setState({ count: this.state.count + 1 }, () =&gt; {<br>      console.log(this.state.count);<br>     })<br>  }<br>&gt;</pre><h3>In Functional Component</h3><p>In a functional component, there’s no constructor() no this keyword no render()function. First we have to import useState from react. import React, { useState } from &quot;react&quot;; useState takes just one argument which is the intial value, and returns a stateful value and a function to change it, we destructured it like this: const [state, setState] = useState(initialValue); To use it, simply we can use it like the class example.</p><pre>const [state, setState] = useState({<br>  count: 0<br>});</pre><pre>console.log(state.count); // 0</pre><p>and update it like this</p><pre>setState({ count: state.count + 1 });</pre><h4>But, What if we have more than one value?</h4><p>Here we have two options:</p><ul><li>first, simply use it like above.</li></ul><pre>const [state, setState] = useState({<br>  count: 0,<br>  barcode: &quot;1A&quot;<br>});</pre><p>BUT, when you change it, don’t forget to pass the current state, and just change what you want, like this:</p><pre>setState({<br>  ...state,<br>  barcode: &quot;2B&quot;<br>});</pre><p>if you write this setState({barcode: &quot;2B&quot;}); you simply changed the state, and removed the count key.</p><ul><li>Second, you can use useState multiple times in the same component, one for count and one for barcode like this:</li></ul><pre>const [count, setCount] = useState(0);<br>const [barcode, setBarcode] = useState(&quot;1A&quot;);</pre><p>and to update it, just pass the value:</p><pre>setBarcode(value);<br>setCount(count + 1);</pre><p>Unfortunately useState doesn&#39;t accept a second argument, So we have to use useEffecthook to handle the change on the component. Before you go, please check the two codesandboxes to try what you learned in this article.</p><ul><li><a href="https://codesandbox.io/s/kkm2o57ky3">useState in Functional Component</a></li><li><a href="https://codesandbox.io/s/l49v8r45xq">state in Class Component</a></li></ul><p>In Part 2 — We will expand our code to include useEffect hook.</p><p><a href="https://zeyadetman.github.io/blog/posts/from-reactjs-class-component-to-functional-component-usestate-part-1/"><em>Originally posted on blog</em></a><em> and </em><a href="https://twitter.com/zeyadetman"><em>follow me on twitter</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c04bcaefc17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revamp my blog from Jekyll to Gatsby, and You have to try]]></title>
            <link>https://medium.com/@zeyadelmarsafy/revamp-my-blog-from-jekyll-to-gatsby-and-you-have-to-try-4640dc59f3fb?source=rss-e71a362ed3e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4640dc59f3fb</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[gatsbyjs]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[jekyll]]></category>
            <dc:creator><![CDATA[Zeyad]]></dc:creator>
            <pubDate>Sat, 09 Mar 2019 04:49:00 GMT</pubDate>
            <atom:updated>2019-03-09T04:57:15.357Z</atom:updated>
            <content:encoded><![CDATA[<p>I revamped my blog to be built on Gatsbyjs instead of Jekyll, Everything become cleaner, and faster. In this post I’ll explain what are the differences I have touched and why have you to try Gatsbyjs? so let’s start.</p><h3>Documentation</h3><p>It’s my first time to use Gatsbyjs, I’ve finished my blog in just two days, it’s so easy, the documentation is a great resource to learn what you need in building your gatsby project, code samples is great and the system is easy to learn. Gatsbyjs is based on ReactJS, but if you don’t know ReactJS I think basics will help you build great things. In Jekyll Doc isn’t a great resource to know everything, although it’ll help you build your site but you have to search alot to find how things done.</p><h3>Code Structure</h3><p>I really felt the difference, ReactJS with GraphQL Make a significant difference in revamp, they made me can customize the behaviour and the data structures I wanna get from my pages or posts, something like customizing frontmatter data, the path of posts, words count, time to read with no configurations is so great. I don’t point to Jekyll doesn’t have the previous features, but you have alot to do to use them.</p><p>In Jekyll if you wanna loop through your posts, you have to write your loop in liquid which something i don’t like it, but in gatsbyjs you can write it in javascript.</p><p>Using Layouts in Jekyll led me to create modify css files more than almost hundred times :D .</p><h3>Plugins</h3><p>I have found alot of plugins in Gatsbyjs, on the other side gems doesn’t help you alot in jekyll. RSS for example, in Jekyll you have to use it in xml format, there’s no way to use JSON feeds.</p><p>This the first post I’ve written after revamp and I’m sure the list will go on.</p><p><a href="https://zeyadetman.github.io/blog/posts/revamp-my-blog-from-jekyll-to-gatsby-and-you-have-to-try/"><em>Originally posted on my blog</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4640dc59f3fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to pass state between components in reactjs (Full Code)]]></title>
            <link>https://medium.com/@zeyadelmarsafy/how-to-pass-state-between-components-in-reactjs-full-code-29c650e75edb?source=rss-e71a362ed3e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/29c650e75edb</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Zeyad]]></dc:creator>
            <pubDate>Wed, 25 Jul 2018 22:37:30 GMT</pubDate>
            <atom:updated>2018-07-25T22:37:30.920Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, i’ll explain how to pass a state between components in Reactjs. We’ll build a small ‘How many books did you read?’ app, in this application, we have two main components one big called ‘Library’ and another small ‘Book’, we have 3 books in the library state and each book has its own state. check any book to count as read. <a href="https://zeyadetman.github.io/howmanybooks/">try the app here</a></p><p><strong>Let’s begin with code:</strong></p><h3>Passing state from parent to child</h3><p>In our Library component we have this state</p><pre><strong>this</strong>.state = {<br>	reads: 0,<br>	books: [<br>		{<br>			name: &#39;Zero to one&#39;,<br>			isbn: &#39;9780804139298&#39;,<br>			author: &#39;Peter Thiel&#39;,<br>			cover: &#39;https://images.gr-assets.com/books/1414347376l/18050143.jpg&#39;,<br>			status: <strong>false</strong><br>		},<br>		{<br>			name: &quot;The Manager&#39;s Path&quot;,<br>			isbn: &#39;9781491973899&#39;,<br>			author: &#39;Camille Fournier&#39;,<br>			cover: &#39;https://images.gr-assets.com/books/1484107737l/33369254.jpg&#39;,<br>			status: <strong>false</strong><br>		},<br>		{<br>			name: &#39;Calculus, Better Explained&#39;,<br>			isbn: &#39;9781470070700&#39;,<br>			author: &#39;Kalid Azad&#39;,<br>			cover: &#39;https://images.gr-assets.com/books/1448590460l/27993945.jpg&#39;,<br>			status: <strong>false</strong><br>		}<br>	]<br>};</pre><p>and want to create this.state.books.length - as a number - Book components each have props from the books array of the Librarycomponent’s state. We have to deal with the two components.</p><p><strong>First</strong> with the parent, we have to create the Book component this.state.books.length - as a number - times, and pass our diffrent values to them Like this:</p><p><a href="https://github.com/zeyadetman/howmanybooks/blob/master/src/components/Library/Library.jsx">Full Code here</a></p><pre>{<br>	<strong>this</strong>.state.books.map((_book, _id) =&gt; {<br>		<strong>return</strong> (<br>			&lt;Book<br>				handleCounter={<strong>this</strong>.handleCounter}<br>				key={_id}<br>				id={_book.isbn}<br>				name={_book.name}<br>				isbn={_book.isbn}<br>				author={_book.author}<br>				cover={_book.cover}<br>			/&gt;<br>		);<br>	});<br>}</pre><p><em>Note</em> ignore handleCounter for now.</p><p><strong>Second</strong> with the child Book, we have the values from parent, let’s use them:</p><p><a href="https://github.com/zeyadetman/howmanybooks/blob/master/src/components/Book/Book.jsx">Full code here</a></p><pre>...<br>render() {<br>	<strong>return</strong> (<br>		&lt;Card&gt;<br>			&lt;Image<br>				src={<strong>this</strong>.props.cover}<br>    			alt=&quot;Book cover&quot;<br>...</pre><p>Until now we created 3 Book components from the parent component Library, and set their values from the parent state. Easy! Right? Great, let’s begin the second part</p><h3>Passing state from child to parent</h3><p>In this section, we want to handle the number of books you read by checking on each book checkbox.</p><p>In our Book we have this state</p><p><a href="https://github.com/zeyadetman/howmanybooks/blob/master/src/components/Book/Book.jsx">Full code here</a></p><pre><strong>this</strong>.state = {<br>	status: <strong>false</strong>,<br>	id: <strong>this</strong>.props.id<br>};</pre><p><em>Note</em> don’t forget to pass props to component’s constructor.</p><p>status means if you read this book or not, and its default value is false, id is the id of this book and i set it by book id like we learned in the previous section.</p><p>we need to handle change of this status then update the books array in the parent state.</p><p>In our Book component, we’ll add a checkbox that recieve the change of the book status and pass this.handleChange to its onChangeevent like this:</p><p><a href="https://github.com/zeyadetman/howmanybooks/blob/master/src/components/Book/Book.jsx">Full code here</a></p><pre>&lt;input type=&quot;checkbox&quot; name=&quot;example&quot; onChange={<strong>this</strong>.handleChange} /&gt;</pre><p>you need to bind the function first, then update the Book state with the new status, after updating the child state we’ll update the state of the parent Library like this:</p><p><a href="https://github.com/zeyadetman/howmanybooks/blob/master/src/components/Book/Book.jsx">Full code here</a></p><pre>handleChange() {<br>		<strong>this</strong>.setState({status: !<strong>this</strong>.state.status}, <strong>this</strong>.updateLibraryCount);<br>    }</pre><pre>updateLibraryCount() {<br>		<strong>this</strong>.props.handleCounter(<strong>this</strong>.state);<br>	}</pre><p>In updateLibraryCount we used handleCounter function of the Library as a prop, then passed the Book state to it, Now the Library sees the Book state, Great! let’s use it.</p><p><a href="https://github.com/zeyadetman/howmanybooks/blob/master/src/components/Library/Library.jsx">Full Code here</a></p><pre>handleCounter(_State) {<br>        <em>//Get the index of this book by searching by its unique isbn</em><br>        <strong>const</strong> ObjNum = <strong>this</strong>.state.books.findIndex(<br>			_book =&gt; _book.isbn === _State.id<br>        );</pre><pre>        <em>//then update its value in the Library component</em><br>		<strong>this</strong>.setState(<br>			{<br>				books: update(<br>					ObjNum,<br>					{...<strong>this</strong>.state.books[ObjNum], status: _State.status},<br>					<strong>this</strong>.state.books<br>				)<br>			},<br>			() =&gt; {<br>                <em>//this is a callback to handle the new change of the book status and increment the reads</em><br>				<strong>const</strong> _read = <strong>this</strong>.state.books.filter(_book =&gt; _book.status === <strong>true</strong>)<br>					.length;<br>				<strong>this</strong>.setState({reads: _read});<br>			}<br>		);<br>	}</pre><p>I hope you’re understand how to pass the state from the parent to child and vice versa, Here’s the <a href="https://github.com/zeyadetman/howmanybooks">full code</a>, and this is the <a href="https://zeyadetman.github.io/projects/2018/07/25/How-to-pass-state-between-components-in-reactjs.html">original post on my blog</a>. If you have questions, feel free to ask in comments or <a href="https://zeyadetman.github.io/projects/2018/07/25/zeyadetman@gmail.com">email</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29c650e75edb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>