<?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 Samah Gaber on Medium]]></title>
        <description><![CDATA[Stories by Samah Gaber on Medium]]></description>
        <link>https://medium.com/@samah-gaber?source=rss-2496237c8aa5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*adFrcFqBLwnn46MV.jpg</url>
            <title>Stories by Samah Gaber on Medium</title>
            <link>https://medium.com/@samah-gaber?source=rss-2496237c8aa5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 23:31:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samah-gaber/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[CSS Animations]]></title>
            <link>https://samah-gaber.medium.com/css-animations-2e65ca47c1ea?source=rss-2496237c8aa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e65ca47c1ea</guid>
            <category><![CDATA[css3]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[css-animation]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Samah Gaber]]></dc:creator>
            <pubDate>Thu, 18 Feb 2021 13:21:58 GMT</pubDate>
            <atom:updated>2021-02-18T13:21:58.140Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction to css animations and transitions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*FHirJFcDU0PZb3kCCULfXw.png" /></figure><p>Have you ever wondered about how animations on websites actually work ? Do you wish to design a similarly elegant and interactive website for your business too? <br>If yes, then look no further.</p><p>In this article I’ll try to cover the basics of CSS animations to make you comfortable with creating your own CSS animations from scratch!</p><h3>So, why animate?</h3><p>To improve usability and general user experience, as animations assist in providing improved visual feedback and helps in making interactions with the website striking. But that doesn’t mean animation should be everywhere in your sites. There’s a time and a place for them to avoid ending up creating a page that is more distracting than interactive.</p><h3><strong>CSS animations have 3 significant aspects to it:</strong></h3><ul><li><strong>Transform</strong></li><li><strong>Transition</strong></li><li><strong>Keyframes</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*tufZo5KKXSBkPNQuBdPjmA.jpeg" /></figure><h3>A) TRANSFORM:</h3><p>Transform helps to change your web elements in all kinds of ways, from moving the element to re-sizing it, from rotating the element to tilting it.</p><p>There are four significant aspects of transforms:</p><ol><li>Translate</li><li>Scale</li><li>Rotate</li><li>Skew</li></ol><p>Let’s undertand each one of them.</p><h3>1. Translate</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*_PkMpalFQd1a66dRWLU1vw.gif" /></figure><p>Translate changes the coordinates of the element. It is used to change the appearance of the component on a 2D plane.</p><p>Translate means to simply move the element from one position to another on the webpage. You can translate an object on X-axis, Y-axis or both.</p><pre>transform: translateX(100px);    <br>// Moves the element on the X-axis<br></pre><pre>transform: translateY(100px);    <br>// Moves the element on the Y-axis<br></pre><pre>transform: translate(100px, 100px);  <br>// Moves the element on the X-axis and Y-axis respectively<br></pre><pre>transform: translate(100px); <br>// Moves the element on the X-axis ONLY</pre><h3>2. Scale</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Do3L2ZAlkI3IMoV5iCb12Q.gif" /></figure><p>Scale can change the size of the image, along with both the X-axis and Y-axis. Scaling distorts the shape of the element and can degrade the quality of the element. A number greater than 1 will increase the size and a decimal less than 1 will decrease the size.</p><pre>transform: scaleX(3); <br>// Scaling along the X-axis<br></pre><pre>transform: scaleY(0.5); <br>// Scaling along the Y-axis<br></pre><pre>transform: scale(3 , 0.5); <br>transform: scale(3);<br>// Scaling along both the X-axis and Y-axis</pre><h3>3. Rotate</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*3Qe1969dFsKux-m8ZRibVA.gif" /></figure><p>You can rotate the element either clockwise or counter-clockwise. The unit of measurement used is <strong>degrees</strong>. A positive value will rotate the element clockwise, and vice versa for the negative element. This rotation would also happen along X, Y and Z axis.</p><pre>transform: rotateX(45deg);<br>// The elements will be rotating into the page along X-axis.<br></pre><pre>transform: rotateY(45deg);<br>// The elements will be rotating into the page along Y-axis.<br></pre><pre>transform: rotateZ(45deg)<br>// The elements will be rotating into the page along Z-axis.</pre><h3>4. Skew</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*dBPwXPqexJY2_3bNYqDiBg.gif" /></figure><p>Skewing an element means tilting the component. It has both positive and negative values, and like rotation, it is measured in <strong>degrees</strong> <strong>(deg)</strong> too.</p><p>Positive X value bends the element to the left, and vice versa for the negative X. Likewise, a positive Y value dips the element downwards, and vice versa. By default, if X or Y aren’t stated in the transform, it will shift the element with respect to the X-axis.</p><pre>transform: skewX(45deg); or skew(45deg);<br>// Along X-axis</pre><pre>transform: skewY(80deg);<br>// Along Y-axis</pre><h3>Combining transforms</h3><p>You can also apply multiple transforms into a single transform statement. The order does matter as the second transform will apply on the first transform and the third will apply on the result of the first two transforms.</p><pre>transform: translateX(100px) rotateX(45deg) scaleY(1.5) skewX(45deg)</pre><h3>Adding transforms to events</h3><p>All of these transforms can take effect on some user event like hover, click, focus, active, etc.</p><pre>.element-to-animate:hover {<br>    transform: translateX(100px) rotateX(45deg) scaleY(1.5);<br>}</pre><h3>B) TRANSITION:</h3><p>Transitions help in making the animation fluid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ctorTzo3XECojpZjnTaIEg.gif" /></figure><p>You can control the transitions with the help of the following properties:</p><ol><li>Transition-property</li></ol><p>2. Transition-duration</p><p>3. Transition-timing-function</p><p>4. Transition-delay</p><p>Let’s undertand each one of them.</p><h3>1. Transition-property:</h3><p>These are the CSS properties that one can use transitions on. This ranges from playing with margins and paddings to background and borders. You can either apply a transition to a specific feature or to a complete list. A complete list of all of these properties can be found <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties"><strong>here.</strong></a></p><pre>transition-property: background-color;<br>// Applying transition property to a specific CSS property<br></pre><pre>transition-property: all;<br>// Applying a transition to the entire list of CSS properties</pre><h3>2. Transition-duration:</h3><p>The time duration for which the animation will be in play. This can easily be measured in seconds (s) or milliseconds (ms).</p><pre>transition-duration: 0.5s;</pre><h3>3. Transition-timing-function:</h3><p>Speed is something that can make or break the user experience with your animation; therefore it is advisable to control it by using transition-timing-function.<br>There is some in-built values for speed, like ease, ease-in, ease-in-out. <a href="https://matthewlein.com/tools/ceaser"><strong>Try it out</strong></a>.<br>You also can possess total command over the speed by using Bezier Curves. <a href="https://cubic-bezier.com/#.17,.67,.83,.67"><strong>Try it out</strong></a>.</p><pre>transition-timing-function: ease;</pre><pre>transition-timing-function: cubic-bezier(0.25, 0.1, 0.25, 1);</pre><h3>4. Transition-delay:</h3><p>This helps in creating a pause or delay between the event getting fired that starts the animation and the actual start of the animation. It is measured in seconds (s) or milliseconds (ms).</p><pre>transition-delay: 0.5s;</pre><h3>Combining transitions</h3><pre>transition: (property) (duration) (transition-timing-function) (transition-delay);</pre><h3>C) KEYFRAMES:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*dZKcq5VaekGUpKsutKlCoQ.gif" /></figure><p>The keyframes help in changing the animation from one to another at certain times.<br>You can play with keyframes in two ways:</p><ol><li>From — To approach</li><li>Percentage Approach</li></ol><h3>1. From-To approach</h3><p>In this approach, there are only 2 states during the animation — start state and end state.</p><pre>@keyframes animation_name {<br>            from { }<br>            to { }<br>}</pre><p>To animate an element (e.g., a Circle) to move horizontally from its initial position:</p><pre>@keyframes move {<br>   from {<br>           transform: translateX(-200);<br>        }<br>   to   {<br>           transform: translateX(1000px);<br>        }<br>}</pre><pre>.circle {<br>   animation-name: move;<br>   animation-duration: 3s;<br>   animation-fill-mode: forwards;<br>   animation-delay: 2s;<br>   animation-iteration-count: infinite;<br>   animation-timing-function: ease-in;<br>   animation-direction: normal;<br>}</pre><h3>2. Percentage approach</h3><p>We cannot use from-to in @keyframes as there is more than 1 state now. The percentage approach breaks down the animation into various intermediate states including a start and end state. The start state is indicated by 0%, and the end state is indicated by 100%. There can be as many intermediate states you want, but it is advised to keep the segregation of states uniform throughout.</p><p>Example:<strong> 0% — 25% — 50% — 75% — 100%</strong></p><pre>@keyframes jump {<br>     0% { transform: translateY(-50px) }<br>     50% { transform: translateY(-100px) }<br>     100% { transform: translateY(-50px) }<br>}</pre><h3>• Animation shorthand</h3><p>One can also use this concise format to write the animations:</p><p><strong>animation: (animation-name) (animation-duration) (animation-fill-mode) (animation-timing-function) (animation-iteration-count) (animation-direction) (animation-delay);</strong></p><p><strong>Note:</strong> The animation-delay will always come AFTER animation-duration. Apart from them, time-oriented functions and the order of other properties in shorthand doesn’t matter.</p><pre>.circle {<br>   animation-name: move;<br>   animation-duration: 3s;<br>   animation-fill-mode: forwards;<br>   animation-delay: 2s;<br>   animation-iteration-count: infinite;<br>   animation-timing-function: ease-in;<br>   animation-direction: normal;<br>}</pre><pre><strong>// </strong>Can be re-written as<br>.circle {<br>   animation: move 3s ease-in infinite normal 2s;<br>}</pre><p>We now have two animations — <strong>move and jump</strong>, which we wish to add on the “circle” element. We can do this through a single line code by using, “Chaining Animations.”</p><h3>• Chaining Animations?</h3><p>Playing with multiple animations is a breeze with CSS. Comma separation technique can be used to chain the animation and run one animation after the other.</p><pre>.circle {<br>    animation: move 3s ease-in infinite normal 2s, <br>               jump 2s ease 4 alternate reverse;<br>}</pre><h3>Classifications of Animation Properties:</h3><p><strong>animation-name:</strong> Name of the animation which is indicated by the keyword after @keyframes</p><p><strong>animation-fill-mode:</strong> Tells what to do with the element being animated outside the animation window.</p><p><strong>animation-iteration-count</strong>: It helps to repeat the animation. It can either have a number value or if you want the animation to play continuously, then use “infinite.”</p><p><strong>animation-direction:</strong> You don’t need to write a separate animation all together just to reverse the animation. You can apply this to play with the current animation, and it’s direction.</p><p><strong>animation-timing-function:</strong> helps to control the speed with which the animation starts, behaves and ends. There are some in-built values like ease, ease-in and you can write your own using the cubic-bezier(n,n,n,n).</p><p><strong>animation-delay:</strong> will start the animation few seconds/milliseconds after the event gets fired.</p><p>That’s it for today. It could be a bit complicated to get used to CSS animation tricks at first. But once you get used you’ll realize that CSS Animations and Transitions are simply marvelous.</p><blockquote>Thanks for reading! Any comments or feedback are more than welcomed 😊</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e65ca47c1ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recursion in Javascript]]></title>
            <link>https://samah-gaber.medium.com/recursion-in-javascript-52e2a3a59627?source=rss-2496237c8aa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/52e2a3a59627</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Samah Gaber]]></dc:creator>
            <pubDate>Wed, 21 Oct 2020 18:33:39 GMT</pubDate>
            <atom:updated>2020-10-21T18:33:39.828Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*KFaNxAaRC-ky2NaLk1F_2g.jpeg" /></figure><blockquote>The function calls itself until someone stops it. If no one stops it then it’ll <strong>recurse</strong> (call itself) forever.</blockquote><p>Recursion can feel difficult to new developers. Perhaps that’s because many resources teach it using algorithmic examples like Fibonacci, linked-lists, etc. In this article I’ll try to demonstrate some simple examples to help you understand Recursion better.</p><h3>What is Recursion Good For?</h3><p>Recursive functions let you perform a unit of work multiple times. This is exactly what for/while loops let us accomplish! Sometimes, however, recursive solutions are a more elegant approach to solving a problem.</p><p><strong>Some reasons that recursion is favored in functional programming languages is that:</strong></p><ul><li>It allows for the construction of code that doesn’t require setting and maintaining state with local variables.</li><li>Recursive functions are also naturally easy to test because they are easy to write in a pure manner, with a specific and consistent return value for any given input, and no side effects on external variable states.</li></ul><h3>Let’s see our first example:</h3><p>We’ll create a countDownFrom function that takes a number parameter and countdown till 1.</p><pre>countDownFrom(5);<br>// 5<br>// 4<br>// 3<br>// 2<br>// 1</pre><p><strong>First, we’ll implement it using ( for loop )</strong></p><pre>function countDownFrom(number) {<br>	for (let i = number; i &gt; 0; i--) {<br>		console.log(i);<br>	}	<br>}<br><br>countDownFrom(5);<br>// 5<br>// 4<br>// 3<br>// 2<br>// 1</pre><p><strong>Now let’s try using recursive approach</strong></p><pre>function countDownFrom(number) {<br>	if (number === 0) {<br>		return;<br>	}<br><br>    console.log(number);    <br>    countDownFrom(number - 1);<br>}<br><br>countDownFrom(5);<br>// 5<br>// 4<br>// 3<br>// 2<br>// 1</pre><p>It seems that both approaches gives the same results. But actually they do the same job in 2 different ways.</p><p>In the for loop approach we can see that it uses extra variable i, changing it’s value repeatedly untill it stop when i is no longer greater than 0 ( i &gt; 0 ).</p><p>On the other hand; the recursive version doesn’t need extra variables to track its progress. That’s because each call to countDownFrom feeds it number - 1. By doing this we&#39;re passing along an updated parameter number each time. No extra state needed!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*2riFd_XFIYuawRwUOJ2NtQ.jpeg" /></figure><h3>Infinite Loops</h3><p>In your practice, you may have been warned about the dreaded infinite loop.</p><p>Since they’d theoretically run forever, an infinite loop will halt your program and possibly crash your browser. You can prevent them by always coding a <em>stopping condition</em>.</p><pre>// THIS RUNS FOREVER, BE WARNED<br>while (true) { console.log(&#39;WHY DID YOU RUN THIS?!&#39; }<br></pre><pre>// THIS DOES NOT RUN FOREVER<br>x = 0;<br>while (x &lt; 3) { <br>      console.log(x); <br>      x++; <br>}</pre><h3>Infinite Recursion</h3><p>Recursion also presents the same danger. It’s not hard to write a self-referencing function that’ll crash your browser.</p><pre>// THIS RUNS FOREVER, BE WARNED<br>function run() {<br>    console.log(&#39;running&#39;);<br>    run();<br>}<br><br>run();<br>// running<br>// running<br>// ...<br></pre><pre>// THIS DOES NOT RUN FOREVER<br>function run(x) {<br>    if (x === 3) return;<br>    <br>    console.log(&#39;running&#39;);<br>    run(x + 1);<br>}<br><br>run(0);<br>// running<br>// running<br>// running<br><br>// x is 3 now, we&#39;re done.</pre><p>Without a stopping condition, run will forever call itself. We fixed that with an if statement.</p><h3>Ready for another example ?</h3><p>This example is one of the most famous recursion example. It returns the factorial of a supplied integer:</p><pre>function factorial(x) {<br>  if (x &lt; 0) return;<br>  if (x === 0) return 1;<br>  return x * factorial(x - 1);<br>}</pre><pre>factorial(3);<br>// 6</pre><p><strong>Before we go deep into this one, let’s understand what are factorials:</strong></p><p>To get the factorial of a number you multiply that number by itself minus one until you reach the number one.</p><p><strong>Example 1:</strong> The factorial of <strong>4</strong> is <em>4 * 3 * 2 * 1</em>, or <strong>24</strong>.</p><p><strong>Example 2:</strong> The factorial of <strong>2</strong> is just <em>2 * 1</em>, or <strong>2</strong>.</p><p><strong>Now can you get what’s happening with our function here.</strong></p><p>It starts with a number and then it returns that number multiplied by itself -1, till it reaches 0 and in this case it returns 1 ending the recursion.</p><h3><strong>Now to sum up the three key features of recursion</strong></h3><h4>1) A Termination Condition:</h4><p>The Termination Condition is our recursion fail-safe. To prevent running the recursion in case of wrong or bad parameters.</p><p>if(something bad happened){ STOP };</p><p>In our factorial function it’s the if (x &lt; 0) return; as it’s not possible to factorial a negative number. So we don’t even bother to run the function in this case.</p><h4>2) A Base Case</h4><p>The Base Case is similar to our termination condition in that it also stops our recursion. But it’s different in that it is the goal of our recursive function.</p><p>In the factorial example, if (x === 0) return 1; is our base case. We know that once we’ve gotten x down to zero, we’ve reached our goal and can determine the factorial successfully.</p><h4>3) The Recursion</h4><p>It’s simply our function calling itself.</p><p>In the factorial example, return x * factorial(x — 1); is where the recursion actually happens. We’re returning the value of the number x multiplied by the value of whatever factorial(x-1) evaluates to.</p><p><strong>All Three Together</strong></p><pre>function factorial(x) {<br>  <strong>// TERMINATION</strong><br>  if (x &lt; 0) return;  </pre><pre><strong>  // BASE</strong><br>  if (x === 0) return 1;  </pre><pre><strong>  // RECURSION</strong><br>  return x * factorial(x - 1);<br>}</pre><pre>factorial(3);<br>// 6</pre><h3>Conclusion</h3><ul><li>Recursion is when a function calls itself until someone stops it.</li><li>It can be used instead of a loop.</li><li>If no one stops it, it’ll recurse forever and crash your program.</li><li>A <strong>termination condition</strong> and a <strong>base case</strong> are conditions that stop the recursion. Don’t forget to add them!</li><li>Loops use extra state variables for tracking and counting, while recursion only uses the provided parameters.</li></ul><blockquote>Thanks for reading! Hopefully you’re now able to follow recursive functions in JavaScript and understand how they work.</blockquote><blockquote>Any comments or feedback are more than welcome 😊</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52e2a3a59627" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-invoking functions in Javascript]]></title>
            <link>https://samah-gaber.medium.com/self-invoking-functions-in-javascript-ea6ee39ba4d8?source=rss-2496237c8aa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea6ee39ba4d8</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[js]]></category>
            <dc:creator><![CDATA[Samah Gaber]]></dc:creator>
            <pubDate>Sun, 18 Oct 2020 16:33:58 GMT</pubDate>
            <atom:updated>2020-10-18T17:00:17.409Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>IIFE — IMMEDIATELY INVOKED FUNCTION EXPRESSION</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wf2CgvXhfvdVb6YS" /><figcaption>Photo by <a href="https://unsplash.com/@synkevych?utm_source=medium&amp;utm_medium=referral">Roman Synkevych</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In JavaScript, it’s common to hear lots of strange terminology without a lot of description around what it is or what it does. I want to try and explain what a self invoking function is and why you should consider them.</p><p>In JavaScript, functions are usually declared like this:</p><pre>function myFunctionName (parameters) {<br>   //some code that does something.<br>}</pre><p>This is called a declared function. Declared functions are not executed immediately. Basically, declared functions are saved for you to use them somewhere else so this means it’s not called upon or “invoked” until you call it like this:</p><pre>myFunctionName (&quot;Function parameters&quot;);</pre><p>A self-invoking function is a nameless (anonymous) function that is invoked immediately after its definition.</p><p>An anonymous function is enclosed inside a set of parentheses followed by another set of parentheses (), which does the execution.</p><pre>(function(){<br>    console.log(&quot;This function is called immediately&quot;);<br>})();</pre><p>Self-invoking functions are useful for initialization tasks. For example, if we have a web page in which we want to attach event listeners to DOM elements and other initialization work, self-invoking functions would be the best tool for the job!</p><p>The primary benefit of self-invoking functions is that they execute only once and won’t fill the global namespace with all sorts of crud that lasts for the lifetime of the page.</p><p>It doesn’t seem like adding a few things to the global namespace would be a problm until you start getting into thousands of lines of javascript and having collisions between functions or variables.</p><h3>How they actually work ?</h3><p>Since the function is defined anonymously, there are neither global nor even local variables except, of course, the variables declared inside the function’s body. We do not keep reference to the function, not even to its return value. After the function has been initialized, it is being immediately invoked and it’s executed only once as after the execution we’ll lose the reference to the function.</p><h3>How to write them ?</h3><p>There is a few small (but important) syntax variations. Douglas Crockford’s JSLint offers the correct declaration for self-invoking functions as:</p><pre>(function () {<br>  // body<br>}());</pre><p>An alternative syntax, which Crockford calls “dog balls”, is as follows:</p><pre>(function () {<br>  // body<br>})();</pre><p>I personally find the second variant to be more clear.</p><p>You can also pass parameters to the self-invoking functions. It is a commonly used practice to pass references to global objects:</p><pre>(function (w, d, $) {<br>  // body<br>}(window, document, jQuery));</pre><p>A self-invoking function can have variables and methods but they cannot be accessed from outside of it. To access them, the global window object has to be passed as a parameter.</p><p>Consider a self-invoking function below, containing the variable pi and the function e(). A global window object is passed and both pi and e() are assigned to the global variables window.pi and window.e respectively</p><pre>(function(window){<br>    var pi = 3.141;<br>    function e() {<br>	return Math.E;<br>    }<br>    <br>    window.pi = pi;<br>    window.e = e;<br>})(window);</pre><p>In the browser console, the command pi will return 3.141 and the command e() will return 2.718281828459045.</p><pre>&gt; pi; // 3.141<br>&gt; e(); // 2.718281828459045</pre><h4>Important note:</h4><p>In programming we usually call functions which invoke themselves recursive functions. That is the reason Ben Alman gave self-invoking functions a new name: <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/">Immediately Invoked Function Expression (IIFE).</a> It is recommended to use the term IIFE since it’s semantically correct and more clear.</p><h3>Conclusion</h3><p>The purpose of wrapping the function is for the namespace and controling the visibility of member functions. It wraps the code inside a function scope and decreases clashing with other libraries. And it’s useful for initialization tasks.</p><blockquote>Thank you for your time. Any comments and feedback are most welcomed 😊</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea6ee39ba4d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vonage Video API Integration with React]]></title>
            <link>https://samah-gaber.medium.com/vonage-video-api-integration-with-react-9608c1bc6f7f?source=rss-2496237c8aa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9608c1bc6f7f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Samah Gaber]]></dc:creator>
            <pubDate>Thu, 04 Jun 2020 16:44:45 GMT</pubDate>
            <atom:updated>2020-06-04T16:44:45.165Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FKgrhGxmu65w15PF" /><figcaption>Photo by <a href="https://unsplash.com/@jakobowens1?utm_source=medium&amp;utm_medium=referral">Jakob Owens</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Vonage Video API ?</h3><p>The Vonage Video API (formerly TokBox OpenTok) makes it easy to embed high-quality interactive video, voice, messaging, and screen sharing into web and mobile apps.</p><p>The platform comprises an easy-to-use self-service API (available in JavaScript or Flash AS3) and a cloud infrastructure that provides routing, messaging and signal processing support.</p><p>The developer uses the API to write an app. TokBox runs the cloud infrastructure that makes it all happen.</p><h3>Why Vonage Video API ?</h3><ul><li>OpenTok allows developers to weave live, group video chat directly into their web experience application</li><li>OpenTok gives the developer complete control over chat and user experience.</li><li>The publish/subscribe model lets developers implement 1–1, group, 1:many, random pairings, many:1, and even more types of chat.</li><li>Having individual control over the layout, sizing and animation of each individual video stream allows the video chat to be a native, fully-integrated part of the web experience.</li><li>It takes the complexity of operating and running a real-time video chat infrastructure off the developers’ plate</li></ul><h3>Setting up the project structure</h3><p>All OpenTok applications require both a <strong>client</strong> and a <strong>server</strong> component.</p><p><strong>The client-side code</strong> is what loads in an end-user’s browser and handles the majority of OpenTok functionality, including connecting to the session, publishing audio-video streams to the session, and subscribing to other client’s streams.</p><p><strong>The server code </strong>is what<strong> </strong>creates sessions in the OpenTok cloud, Generates tokens for clients, and sends session IDs and tokens to clients.</p><h3>Now let’s set up a Basic Web Client</h3><p><strong>Pre-requisites: </strong>NodeJS , NPM and React installed on your machine</p><p>LEt’s start by creating a react app:</p><pre>npx create-react-app my-app</pre><pre>cd my-app</pre><pre>npm start</pre><p>Then install OpenTok plugin</p><pre>npm i --save @opentok/client</pre><h4><strong>Creating the project files</strong></h4><p>In your project create a file VideoComponent.js on the same level with the App.js</p><p>Require the installed plugin:</p><pre>const OT = require(“@opentok/client”);</pre><p>Return 2 div, one for the publisher and another for the subscriber.</p><pre>&lt;div id=”videos”&gt;<br>  <br>  &lt;div id=”publisher”&gt;&lt;/div&gt;</pre><pre>  &lt;div id=”subscriber”&gt;&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><h4>Setting up authentication</h4><p>In order to connect to an OpenTok session, the client will need access to some authentication credentials: <strong>API Key, Session ID, and Token </strong>.</p><p>In a production application, these credentials should be generated by a server, but to speed things up we will just hard code the values for now.</p><pre>// replace these values with those generated in your TokBox Account</pre><pre>const apiKey = “YOUR_API_KEY” ;</pre><pre>const sessionId = “YOUR_SESSION_ID” ;</pre><pre>const token = “YOUR_TOKEN” ;</pre><ul><li><strong>apiKey</strong> is generated to single OpenTok account.</li><li><strong>sessionId</strong> is generated to a single chat session ( it can be used for several users ).</li><li><strong>token</strong> is generated to a single user and it uses the sessionId itself ( to allow the access to the session to only users with the related tokens ).</li></ul><p>** You’ll need to adjust the above code with your values which can be generated from the created OpenTokAPI project.</p><p><strong>To do this:</strong> log into your TokBox Account, either create a new OpenTok API project or use an existing OpenTok API project, then go to your project page and scroll down to the Project Tools section — from there, you can generate a Session ID and Token manually.</p><p>** You can continue to get the keys from your account during development and testing, but before production you must set up a server.</p><h4>Connecting to sessions</h4><p><strong>What is a session ?</strong></p><ul><li>Every OpenTok video chat occurs within a session.</li><li>You can think of a session as a “room” where clients can interact with one another in real-time.</li><li>Sessions are hosted on the OpenTok cloud and manage user connections, audio-video streams, and user events (such as a new user joining).</li><li>Each session is associated with a unique session ID.</li><li>To allow multiple clients to chat with one another, you would simply have them connect to the same session (using the same session ID).</li></ul><p>Still in our VideoComponent.js file:</p><pre>let session, publisher, subcriber;</pre><pre>export const initializaSession = () =&gt; {</pre><pre> session = OT.initSession(apiKey, sessionId);</pre><pre> // create a publisher</pre><pre> publisher = OT.initPublisher(</pre><pre>    &quot;publisher&quot;,</pre><pre>    {</pre><pre>       insertMode: &quot;append&quot;,  </pre><pre>       width: &quot;100%&quot;,</pre><pre>       height: &quot;100%&quot;</pre><pre>    },</pre><pre>    handleError</pre><pre> );</pre><pre> // subscribe to newly created stream</pre><pre> session.on(&quot;streamCreated&quot;, function (event) {</pre><pre>     subscriber = session.subscribe(</pre><pre>         event.stream,</pre><pre>         &quot;Subscriber&quot;,</pre><pre>         {</pre><pre>            insertMode: &quot;append&quot;,</pre><pre>            width: &quot;100%&quot;,</pre><pre>            height: &quot;100%&quot;,</pre><pre>         },</pre><pre>         handleError</pre><pre>    );</pre><pre> });</pre><pre><br> // connect to the session</pre><pre> session.connect(token, function (error) {</pre><pre>   // If the connection is successful, publish to the session</pre><pre>   if (error) {</pre><pre>       handleError(error);</pre><pre>   } else {</pre><pre>       session.publish(publisher, handleError);</pre><pre>   }</pre><pre> });</pre><pre> // do some action upon destroying the created stream</pre><pre> session.on(&quot;streamDestroyed&quot;, function (event) {</pre><pre>     console.log(&quot;The Video chat has ended&quot;);</pre><pre> });</pre><pre>}</pre><p>Now we have created our files, added the code we need to start a stream, create a publisher, connect to the stream and subscribe to it,</p><p>Now everything is set and you can call <strong>initializeSession()</strong></p><p>This method initializes a session object and then connects to the session.</p><p>You can add stop publishing stream by calling unpublish method on session object</p><pre>session.unpublish(publisher);</pre><p>Till This step you’ll have a fully functioning vide chat application. The following section is for extra customization of the user experience</p><h3><strong>Functionality customization</strong></h3><h4><strong>Publisher:</strong></h4><p>By default, a Publisher object is initialized to publish to audio and video, if they are available.</p><ul><li>Publishing audio or video only:</li></ul><pre>const pubOptions = {<br>      publishAudio: true, <br>      publishVideo: false<br>};</pre><pre>publisher = OT.initPublisher(“publisher”, pubOptions);</pre><ul><li>You can also toggle audio and video on and off</li></ul><pre>publisher.publishVideo(state);</pre><pre>publisher.publishAudio(state);</pre><ul><li>You can switch the video input device (camera) used as the video source for a Publisher</li></ul><pre>publisher.cycleVideo();</pre><h4><strong>Subscriber:</strong></h4><p>By default, a Subscriber object is initialized to subscribe to audio and video, if they are available.</p><ul><li>Subscribing to audio or video only</li></ul><pre>const subsOptions = {<br>     subscribeToAudio: true, <br>     subscribeToVideo: false<br>};</pre><pre>subscriber = session.subscribe( stream,”Subscriber”,subsOptions );</pre><ul><li>You can toggle audio and video on and off</li></ul><pre>subscriber.subscribeToVideo(state);</pre><pre>subscriber.subscribeToAudio(state);</pre><ul><li>You can change audio level for subscriber</li></ul><pre>const subsOptions = {audioVolume: true}; // set it initially</pre><pre>subscriber.setAudioVolume(7); // set it after subscribtion</pre><h3>UI customization</h3><h4>Displaying publisher name:</h4><p>When you create a Publisher, you can (optionally) specify a name to be displayed in the video:</p><pre>publisher = OT.initPublisher(<br>     “publisher”,<br>      { <br>        name: “John”, <br>        style: { nameDisplayMode: “on” } <br>      }<br>);</pre><p>The <strong>style.nameDisplayMode</strong> property can be set to one of three values:</p><ul><li><strong>auto:</strong> The name is displayed when the stream is first displayed and when the user mouses over the video (the default).</li><li><strong>off:</strong> The name is not displayed.</li><li><strong>on:</strong> The name is displayed.</li></ul><p>Once you have created the Publisher, you can change the name display mode</p><pre>publisher.setStyle({ nameDisplayMode: “off” });</pre><p>When you subscribe to a stream, you can specify whether the name is displayed in the Subscriber video</p><pre>subscriber = session.subscribe(<br>     Stream,<br>     “Subscriber”,<br>     { <br>       style: { nameDisplayMode: “on” } <br>     }<br>);</pre><p>Once you have created the Subscriber, you can change the name display mode</p><pre>subscriber.setStyle({ nameDisplayMode: “off” });</pre><h4>Displaying video controls:</h4><p>By default, the user interface for a Publisher or a Subscriber includes a mute audio button. For a Publisher, the user can click to toggle the mic on and off. For a Subscriber, the user can click to toggle the speaker on and off.</p><ul><li>When you publish a stream, you can specify whether the mute button is displayed</li></ul><pre>publisher = OT.initPublisher(<br>   “publisher”,<br>   { <br>      style: { buttonDisplayMode: “off” } <br>   }<br>);</pre><pre>subscriber = session.subscribe(<br>   stream,<br>   “subscriber”,<br>   { <br>      style: { buttonDisplayMode: “off” } <br>   }<br>);</pre><p>** You can remove the default controls and add your own customized ones.</p><h3>Conclusion</h3><p>OpenTok blows up the traditional video conferencing model by allowing developers to weave live, group video chat directly into their web experience in whatever manner makes most sense to their web application.</p><h3>References</h3><ul><li>Vonage Video APIs:</li></ul><p><a href="https://www.vonage.com/communications-apis/video/">Video API</a></p><p>Video API basics:</p><p><a href="https://tokbox.com/developer/guides/basics/">Video API Basics</a></p><p>Setup a basic web client:</p><p><a href="https://tokbox.com/developer/tutorials/web/basic-video-chat/">Set up a simple web client</a></p><p>Customizing functionality:</p><p><a href="https://tokbox.com/developer/guides/audio-video/js/">Adjusting audio and video - OpenTok docs</a></p><p>Customizing the ui:</p><p><a href="https://tokbox.com/developer/guides/customize-ui/js/">Customizing the UI - JavaScript - OpenTok docs</a></p><p>You may also want to check my simple React video chat application in the following link:</p><p><a href="https://github.com/samah-gaber/vonage-video-chat-application">samah-gaber/vonage-video-chat-application</a></p><blockquote><em>Thank you for your time. Any comments and feedback are most welcomed</em> 😊</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9608c1bc6f7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with Redux: Redux with React]]></title>
            <link>https://samah-gaber.medium.com/getting-started-with-redux-redux-with-react-be6f9ac60d12?source=rss-2496237c8aa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/be6f9ac60d12</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react-redux]]></category>
            <dc:creator><![CDATA[Samah Gaber]]></dc:creator>
            <pubDate>Thu, 17 Oct 2019 09:03:07 GMT</pubDate>
            <atom:updated>2019-10-17T09:03:07.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*uMdftbRuIYt5Wd5-88tliA.png" /></figure><p>We <strong>have a series of articles about Getting started with Redux the links at the end.</strong></p><h4><strong>Why using Redux in React ?</strong></h4><p>In React, each component had its own state. It worked just fine within that component, but then we faced some issues with this approach.</p><ol><li>The state was enclosed inside of that component and can’t be reached from outside of it :</li></ol><ul><li>If we needed to pass that state to another component we could only pass it along as props from parent to child component.</li><li>If we needed to pass the state between siblings or unrelated components, we would have had to lift the state up the component tree to a higher component so that we can pass it down to both of the desired components.</li></ul><p>2. If we needed to alter the state from outside of the component then child components can receive callback functions in the props from their parent component. These functions can be used to alter the local state of the parent component.</p><p>3. Even if we could pass the state to children they don’t know that these props represent the state of their parents. They only receive the values and handle callback functions without knowing their source.</p><p>So with Redux we could separete the state in a global container or storage so that it would be accessible by any component in the app.</p><h4><strong>Instaling Redux and React-Redux :</strong></h4><p>As we know Redux wasn’t designed to work only with React. That’s why we are using React-Redux library as it contains many functions to facilitate the communication between Redux and React.</p><p>Together we’re going to create a very simple app that fetches a list of posts and renders them on the screen.</p><p>Open up your terminal and let’s start by creating a new React app:</p><pre>create-react-app react-redux-app</pre><p>Now change directory to your project folder :</p><pre>cd react-redux-app</pre><p>Next, install both redux and react-redux library:</p><pre>npm install --save redux react-redux</pre><p>Now you can start your application:</p><pre>npm start</pre><p>In your src/ directory delete all of the boilerplate files that come with create-react-app. And we are going to add our own files.</p><pre>cd src<br>rm logo.svg App.js App.test.js App.css</pre><p>now create the following folders and files so that the app folders structure would look like this:</p><pre>-src/</pre><pre>--app/</pre><pre>---App.js</pre><pre>--components/</pre><pre>---Button.js</pre><pre>---PostsList.js</pre><pre>---SinglePost.js</pre><pre>--redux/</pre><pre>---actions/</pre><pre>----index.js</pre><pre>---reducers/</pre><pre>----index.js</pre><pre>----postsReducer.js</pre><pre>---actionTypes.js</pre><pre>--store/</pre><pre>---index.js</pre><pre>--index.js</pre><pre>--postsList.js</pre><h4><strong>React-Redux structure :</strong></h4><p>Before we can go on coding, let me explain the structure of our app upon using Redux.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/0*kTV02rXeqrSiJJ98" /></figure><p>In the above diagram we can see that React-Redux library provides 2 components; <strong>Provider </strong>and <strong>Connect</strong>. We are not going to create them as they are already implemented by React-Redux.</p><p>We learned previously that after combining reducers we create what’s so called Redux Store that contains all of the reducers and the state of the application. We are going to take that store and pass it as a prop to the Provider which will be rendered at the top of our component tree, wrapping our App component.</p><p>The Provider can be considered as a reference to the Redux Store and it’s the only component that has direct access to the state. Other components can’t deal with the Redux Store nor the Provider directly. Components can only deal with the Provider through the Connect component.</p><p>Now enough talking and let’s see some code to get a clearer picture</p><p>In your index.js:</p><pre>import React from &#39;react&#39;;</pre><pre>import ReactDOM from &#39;react-dom&#39;;</pre><pre>import { Provider } from &#39;react-redux&#39;;</pre><pre>import App from &#39;./app/App&#39;;</pre><pre>import Store from &#39;./store&#39;;<br></pre><pre>ReactDOM.render(</pre><pre>     &lt;Provider store={Store}&gt;</pre><pre>         &lt;App /&gt;</pre><pre>     &lt;/Provider&gt;,</pre><pre>     document.getElementById(&#39;root&#39;)</pre><pre>);</pre><p>As you can see we imported Provider from react-redux, used it to wrap our app component and we passed it the Store we are going to create next.</p><h4><strong>Create Redux Store:</strong></h4><p>In src/store/index.js</p><pre>import { createStore, compose } from &#39;redux&#39;;</pre><pre>import reducers from &#39;../redux/reducers&#39;;<br></pre><pre>const Store = createStore( reducers );</pre><pre>export default Store;</pre><p>Here we have imported our combined reducers from redux/reducers/index.js and then created our Redux Store and passed it the combined reducers.</p><h4><strong>Creating Reducers:</strong></h4><p>In src/redux/reducers/postsReducer.js you can create your first reducer</p><pre>export default ( state = {}, action) =&gt; {</pre><pre>      switch( action.type ) {</pre><pre>            case &#39;FETCH_POSTS_LIST&#39;:</pre><pre>                  return { ...state, postsList: action.payload };</pre><pre>            default:</pre><pre>                  return state;</pre><pre>       };</pre><pre>};</pre><p>It’s a very simple reducer that checks on the action.type and returns state with the new posts list. You must return the state in the default otherwise it will give you an error.</p><p>As you can see we have used the action.type as a string but it’s recommended that we store all of our action types used all over the app as variables in one file instead of the strings to eliminate any risk of spelling mistakes.</p><p>So in you src/redux/actionTypes.js</p><pre>export const FETCH_POSTS_LIST = &#39;FETCH_POSTS_LIST&#39;;</pre><p>So now you can replace the string in your reducer with our new variable</p><pre>import { FETCH_POSTS_LIST } from &#39;../actionTypes&#39;;</pre><pre><br>export default ( state = {}, action) =&gt; {</pre><pre>    switch( action.type ) {</pre><pre>       case FETCH_POSTS_LIST:</pre><pre>           return { ...state, postsList: action.payload };</pre><pre>       default:</pre><pre>           return state;</pre><pre>    };</pre><pre>};</pre><p>To combine the reducers in your src/redux/reducers/index.js :</p><pre>import { combineReducers } from &#39;redux&#39;;</pre><pre>import PostsReducer from &#39;./postsReducer&#39;;</pre><pre>export default combineReducers({</pre><pre>      postsList: PostsReducer</pre><pre>});</pre><h4><strong>Creating Actions:</strong></h4><p>In src/redux/actions/index.js create the first action</p><pre>import { FETCH_POSTS_LIST } from &#39;../actionTypes&#39;;</pre><pre>export const fetchPosts = payload =&gt; ({</pre><pre>   type: FETCH_POSTS_LIST,</pre><pre>   payload</pre><pre>});</pre><h4><strong>Building our app:</strong></h4><p>Now let’s build up our app.</p><ol><li><strong>App component</strong>.</li></ol><p>In src/app/App.js:</p><pre>import React from &#39;react&#39;;</pre><pre>import Button from &#39;../components/Button&#39;;</pre><pre>import PostsList from &#39;../components/PostsList&#39;;</pre><pre>const App = () =&gt; {</pre><pre>     return(</pre><pre>         &lt;div&gt;</pre><pre>            &lt;Button /&gt;</pre><pre>            &lt;PostsList /&gt;</pre><pre>         &lt;/div&gt;</pre><pre>     );</pre><pre>};</pre><pre>export default App;</pre><p><strong>2. Button component ( mapDispatchToProps )</strong></p><p>In src/components/Button.js</p><pre>import React from &#39;react&#39;;</pre><pre>import { connect } from &#39;react-redux&#39;;</pre><pre>import { fetchPosts } from &#39;../redux/actions&#39;;</pre><pre>import { postsList } from &#39;../postsList&#39;;<br></pre><pre>class Button extends React.Component {</pre><pre>      onClickFetchPosts = () =&gt; {</pre><pre>          this.props.onFetchPosts(postsList);</pre><pre>      };</pre><pre>      render() {</pre><pre>         return(</pre><pre>              &lt;button onClick={this.onClickFetchPosts}&gt;<br>                    Get Posts<br>              &lt;/button&gt;</pre><pre>         );</pre><pre>      };</pre><pre>};</pre><pre>const mapDispatchToProps = dispatch =&gt; ({</pre><pre>     onFetchPosts: postsList =&gt; dispatch(fetchPosts(postsList))</pre><pre>});</pre><pre>export default connect(null, mapDispatchToProps)(Button);</pre><p>Let’s pause for a second to explain what we have done in this component.</p><p>Like we have said before that we use Connect to connect components to the Store. And that’s exactly what we have done here. we imported connect (with lowercase c) from react-redux and wrapped the button with it.</p><p>Then we passed to connect a method called <strong>mapDispatchToProps</strong> that gives access to the dispatch method of the Redux store. It takes dispatch function as a parameter and returns an object with key (custom name of your choice) and the value is a callback function that dispatches our action.</p><p>So now to call our action creator in the component we can say this.props.keyName().</p><p>There is another way instead of using mapDispatchToProps which is by passing the action creator directly in an object to connect like the following:</p><pre>export default connect(null, { fetchPosts })(Button);</pre><p>And then we call it directly in our methods like this:</p><pre>onClickFetchPosts = () =&gt; {</pre><pre>   this.props.fetchPosts(postsList);</pre><pre>};</pre><p>The two ways are absolutely correct and use whichever you like of them.</p><p>P.S. We passed the action creator a fake postsList that we created instead of calling a real api and fetching real data.</p><p>In src/postsList.js</p><pre>export const postsList = [</pre><pre>{</pre><pre>   &quot;userId&quot;: 1,</pre><pre>   &quot;id&quot;: 1,</pre><pre>   &quot;title&quot;: &quot;excepturi&quot;,</pre><pre>   &quot;body&quot;: &quot;nostrum rerum est autem sunt rem eveniet architecto&quot;</pre><pre>},</pre><pre>{</pre><pre>   &quot;userId&quot;: 1,</pre><pre>   &quot;id&quot;: 2,</pre><pre>   &quot;title&quot;: &quot;esse&quot;,</pre><pre>   &quot;body&quot;: &quot;qui aperiam non debitis possimus qui neque nisi nulla&quot;</pre><pre>},</pre><pre>{</pre><pre>   &quot;userId&quot;: 1,</pre><pre>   &quot;id&quot;: 3,</pre><pre>   &quot;title&quot;: &quot;exercitationem&quot;,</pre><pre>   &quot;body&quot;: &quot;molestiae porro eius odio et labore et velit aut&quot;</pre><pre>},</pre><pre>{</pre><pre>   &quot;userId&quot;: 1,</pre><pre>   &quot;id&quot;: 4,</pre><pre>   &quot;title&quot;: &quot;occaecati&quot;,</pre><pre>   &quot;body&quot;: &quot;quis sunt voluptatem rerum illo velit&quot;</pre><pre>},</pre><pre>{</pre><pre>   &quot;userId&quot;: 1,</pre><pre>   &quot;id&quot;: 5,</pre><pre>   &quot;title&quot;: &quot;nesciunt&quot;,</pre><pre>   &quot;body&quot;: &quot;est aut tenetur dolor neque&quot;</pre><pre>}]</pre><p><strong>3. PostsList component ( mapStateToProps )</strong></p><p>In src/components/PostsList.js</p><pre>import React from &#39;react&#39;;</pre><pre>import { connect } from &#39;react-redux&#39;;</pre><pre>import SinglePost from &#39;./SinglePost&#39;;</pre><pre>class PostsList extends React.Component {</pre><pre>   render() {</pre><pre>      const { postsList } = this.props;</pre><pre>      return(</pre><pre>         &lt;div&gt;</pre><pre>            { postsList &amp;&amp; postsList.length &gt; 0 ? postsList.map(</pre><pre>                   singlePost =&gt; <br>                        &lt;SinglePost <br>                            post={singlePost} <br>                            key={singlePost.id}/&gt;</pre><pre>               ) : &lt;p&gt;Loading posts ... &lt;/p&gt; }</pre><pre>         &lt;/div&gt;</pre><pre>      )</pre><pre>   }</pre><pre>};</pre><pre>const mapStateToProps = state =&gt; ({</pre><pre>      postsList : state.postsList.postsList</pre><pre>});</pre><pre>export default connect(mapStateToProps)(PostsList);</pre><p>Like in Button where we used connect to dispatch our action, we’re using it here to fetch some data from the Store.</p><p>We passed to connect another method called <strong>mapStateToProps </strong>which gives the component the access to the Store and get whatever data in state it needs through its props. It takes the state as a parameter and returns an object with custom key name and a value of the desired state keys.</p><p>If you added console.log(state) inside mapStateToProps you would see the actual state with the keys we created in combined reducers and with the postsList that we dispatched in our action.</p><p>So now we can access this data through this.props.keyName.</p><p>P.S. if there isn’t mapStateToProps in the component we pass “null” to the connect like we’ve done in the Button component.</p><p>Now we can say that we are finished with the full Redux cycle inside our React app. The last part is only about rendering the posts more nicely.</p><p><strong>4. SinglePost component</strong></p><p>In src/components/SinglePost.js</p><pre>import React from &#39;react&#39;;</pre><pre>const SinglePost = props =&gt; {</pre><pre>   const { title, body } = props.post;</pre><pre>   return(</pre><pre>      &lt;div&gt;</pre><pre>         &lt;h3&gt;{title}&lt;/h3&gt;</pre><pre>         &lt;p&gt;{body}&lt;/p&gt;</pre><pre>         &lt;hr/&gt;</pre><pre>      &lt;/div&gt;</pre><pre>   )</pre><pre>};</pre><pre>export default SinglePost;</pre><h3><strong>Summary</strong></h3><ol><li>Why use Redux with React?</li><li>Installing redux and react-redux libraries.</li><li>Using Provider and connect.</li><li>Building Redux store, reducers and action creators.</li><li>Using mapDispatchToProps and mapStateToProps.</li></ol><h4><strong>We have a series of articles about Redux:</strong></h4><ul><li><a href="https://medium.com/p/5300ce12dc95/edit">Getting started with Redux: what is Redux</a></li><li>Getting started with Redux: Redux with React</li><li><a href="https://medium.com/@dina.elghndour/5c36e4ccee6f">Getting started with Redux: Redux-saga with React</a></li></ul><p>That’s it for now. Hope the article was helpful for you 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be6f9ac60d12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating React with Redux]]></title>
            <link>https://samah-gaber.medium.com/integrating-react-with-redux-1c089afaef98?source=rss-2496237c8aa5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c089afaef98</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-redux]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[frontend-developer]]></category>
            <category><![CDATA[front-end-developer]]></category>
            <dc:creator><![CDATA[Samah Gaber]]></dc:creator>
            <pubDate>Thu, 12 Sep 2019 20:10:52 GMT</pubDate>
            <atom:updated>2019-09-12T20:10:52.485Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WQmEMupvE1EkSGhI" /><figcaption>Photo by <a href="https://unsplash.com/@beautyoftechnology?utm_source=medium&amp;utm_medium=referral">Nikolay Tarashchenko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We have a series of articles about react and how it works with redux:<br>-<a href="https://medium.com/@alaadawabah/redux-without-react-be9dbc3d7b2">Redux without React</a></p><p>-<a href="https://medium.com/@amiraarafa7/react-cooperating-with-redux-4d7fa921adaf">React cooperating with Redux</a></p><p><strong>-Integrating React with Redux</strong></p><p>-<a href="https://medium.com/@amiraarafa7/react-cooperating-with-redux-4d7fa921adaf">Redux Middleware</a></p><p>-<a href="https://medium.com/@db9d94ce97b5/4f0defbddc80?sk=">Redux-Form</a></p><p>By now, you should have known how Redux works on its own, what are actions, action creators and reducers, and how to start integrating Redux with React.</p><p>Let’s continue our talk about how React-Redux handles actions, action creators, reducers, redux-store, how to fetch data from state and how to call our action creators.</p><blockquote><strong>Combine Reducers and create Store:</strong></blockquote><p>We learned previously that after we combine our reducers we create what’s so called <strong>Redux-Store</strong> that contains all of our reducers and the global state of our application.</p><p>src/reducers/index.js =&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EvyYaXbHwGGrYn38" /></figure><blockquote><strong>Provider and Connect:</strong></blockquote><p>We are going to take that store and pass it as a prop to the <strong>Provider </strong>which will be rendered at the top of our component tree, wrapping our App component.</p><p>src/index.js =&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/0*iVorOgPP11TccswG" /></figure><p>The <strong>Provider</strong> can be considered as a reference to the Store and it’s the only component that can access the state and alter it directly. Other components also can’t deal with Provider directly. Components can only deal with the <strong>Connect</strong> component which in turn communicates with the Provider with a system of communication inside of React called the context system.</p><p>Whenever a component needs to access the data stored in the store then we are going to use Connect. We wrap that component by Connect and then it’s called connected component which means it’s now connected to the state store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/0*nRkqSU1EbqWzTCe0" /></figure><p>Simply at any point of time a component needs to render some data from the state we tell the Connect which in turn reaches back to the Provider to get the needed data from the redux-store and sends it back to the Connect that passes this data as props to the component.</p><p>But to alter the state we need action creators which are not stored in the redux-store.</p><p>When we used Redux alone we used to call action creators to return an action that we send to the store through dispatch function. Now using React-Redux we are going to deal with action creators in a different way. We tell Connect that we need to call a specific action creator from within our component. Then Connect passes this action creator to our component also as a prop. And after the call, Connect passes the action to the dispatch function in the redux-store.</p><p>In the previous part we installed React-Redux and configured Provider in the index.js and Connect in desired components. But you might think about how to structure your folders and where to put all of the actions and reducers.</p><p>Well, it’s totally up to you but the best way is to get all of the actions in a separate folder same as the reducers. Each in its own folder inside your src folder.</p><p>Now enough talking and let’s see some code to get a clearer picture.</p><blockquote><strong>Starting with reducers:</strong></blockquote><p>Here’s an example of a reducer that adds a new record to the state.</p><p>P.S. You can separate each action type in its own reducer or join them together using switch case like the example.</p><p>src/reducers/reducer.js =&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hSe1hGMIKOSPXfQd" /></figure><p>You can write as many reducers as you want and at the end call <strong>combineReducers</strong> in the same file or in a different one but of course in that case, don’t forget to export the reducers.</p><p>src/reducers/index.js =&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wYNy_B2iA0lq9cbJ" /></figure><p>Now we have seen reducers and in the previous part we learned how to create store out of the combined reducers and how to configure Provider component, let’s move on to action creators.</p><blockquote><strong>Setting action creators:</strong></blockquote><p>src/actions/index.js =&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/0*QxxkNACvKHuaJG3g" /></figure><p>Here’s an example of a simple action creator that returns action with type and payload properties. It can’t be more simple.</p><p>Before, I’ve mentioned that components don’t communicate with Provider directly, instead they use Connect to do all the communication for them. And we have learned how to wire up the Connect to our components.</p><p>Now let’s see how components actually uses Connect to access the state.</p><blockquote><strong>First: Fetching data from state:</strong></blockquote><p>Components can fetch data from state using <strong>mapStateToProps</strong> function. Before explaining what is that function and what does it do let’s see the next code.</p><p>src/components/component.js =&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/0*5eaiHtHay0wkYsIh" /></figure><p>First of all, mapStateToProps function can be called by any other name, but by convention we call it like that. And from this name we can guess what it does. It does map our state to props which means we use it to extract some data from state and turn it into props so that the component can deal with it. And when we pass it to Connect we actually tell Connect to go fetch the state from the store and then pass it to mapStateToProps function which returns an object containing our new prop holding values from the global state. And then as shown above we can access this data just like any other props by using props.records syntax.</p><p>Whenever the state is updated, mapStateToProps is called causing component to rerender.</p><p>P.S. If you want to use connect but you don’t need mapStateToProps, you can simply write null instead of mapStateToProps but you can’t leave it empty.</p><blockquote><strong>Second: Calling action creators:</strong></blockquote><p>Just like we used mapStateToProps to access state, for actions there is <strong>mapDispatchToProps</strong> function. Let’s have a look on it.</p><p>src/components/component.js =&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UEmiOoJ6hpoyvSOI" /></figure><p>As you can see, it’s the same component. But here we use mapDispatchToProps function which is just like mapStateToProps but instead of accessing the state, mapDispatchToProps access the dispatch method of the redux store. It also returns an Obj with key of prop name and the value of dispatching the action creator.</p><p>We pass it to Connect but it must be passed after mapStateToProps. And after that we can use it in events -as made in the above code- or in whatever action in which we want to call on the action creator. We access it also through props obj.</p><p>There is another way to use mapDispatchToProps without actually writing it in the code which is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/0*-HU37wWN_NKnDa4P" /></figure><p>As you can see, we didn’t use mapDispatchToProps, instead we passed the final obj to Connect directly and this way we can use props.addNewRecord just like the other syntax.</p><p>You may ask why causing our selves all of this headache of passing the action creators to Connect then call it through props instead of just calling it directly in the component.</p><p>The answer is that Redux is no magic !! It can’t detect by itself anytime we call action creator or that a function in my component returns an action obj and that it must use it to update our state. So for Redux action creators at the end are just functions that return objects and nothing more and they won’t have any impact on the state. So if we wanted an action to really update the state we have to dispatch it. And that is what happens with Connect and mapDispatchToProps.</p><blockquote><strong>So to sum up the React-Redux cycle</strong></blockquote><p>-We create our reducers and action creators.</p><p>-We combine our reducers and create the redux store.</p><p>-We wrap our application with Provider and pass it the created store.</p><p>-We use Connect in any component and use with it:</p><p>mapStateToProps, if we wanted to fetch data from state.</p><p>mapDispatchToProps, if we wanted to call on some action creators.</p><blockquote><strong>References:</strong></blockquote><p><a href="https://www.robinwieruch.de/react-redux-tutorial?fbclid=IwAR3wbGvYAevOLggmo608FIqn0cg9zNwjvtjj5LDK4ZGU65s2lf27h_1hBWw">https://www.robinwieruch.de/react-redux-tutorial?fbclid=IwAR3wbGvYAevOLggmo608FIqn0cg9zNwjvtjj5LDK4ZGU65s2lf27h_1hBWw</a></p><p><a href="https://www.udemy.com/react-redux/">https://www.udemy.com/react-redux/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c089afaef98" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>