<?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 Pierre Hedkvist on Medium]]></title>
        <description><![CDATA[Stories by Pierre Hedkvist on Medium]]></description>
        <link>https://medium.com/@pierrehedkvist?source=rss-7c737fe6552f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lc11UCpWQbgw-By009S2gw.jpeg</url>
            <title>Stories by Pierre Hedkvist on Medium</title>
            <link>https://medium.com/@pierrehedkvist?source=rss-7c737fe6552f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 22:52:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pierrehedkvist/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[Migrating from Redux to React Query]]></title>
            <link>https://pierrehedkvist.medium.com/migrating-from-redux-to-react-query-8e3faffeba70?source=rss-7c737fe6552f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e3faffeba70</guid>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Pierre Hedkvist]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 12:15:32 GMT</pubDate>
            <atom:updated>2022-01-06T12:34:08.084Z</atom:updated>
            <content:encoded><![CDATA[<p>Redux is not so bad or is it. I have worked with an app that used the <a href="https://github.com/erikras/ducks-modular-redux">Redux Ducks</a> pattern. What is that you may ask? It’s a pattern that bundles together actionTypes, actions and reducers together in a module, instead of keeping them in separate files.</p><p>In late 2015 when this pattern was introduced, I am sure it was a good idea. But the problem is I have to write a lot of code for very little functionality. Most often I just want to fetch or post some data to a server somewhere. Most often its rather trivial stuff. But then I have to write all of my actionTypes, actions and reducers to do this simple thing.</p><p>Once we saw that there is lib that basically does all of the boring parts for you. It just made a lot of sense. Thats when we switched over to <a href="https://react-query.tanstack.com/">React Query</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJBHr9Ed-ATBu2JJNUMAIA.png" /></figure><p>React Query is a library that helps with fetching data, post data and cache data in your app. It provides a bunch of hooks that makes is easy to keep your data between pages. It also makes it easy to refetch data, in case you want to keep it fresh.</p><p>Here you can look at a simple <a href="https://codesandbox.io/s/github/tannerlinsley/react-query/tree/master/examples/simple">example</a>.</p><p>Things I really love 😍:</p><p>- The hooks provides a consistent set of properties. In case you need a spinner to indicate something is loading, or some data is being refreshed. If you need to have empty states, either because of errors, or because of no data is available, this is super easy.</p><ul><li>In case you make a post request that updates data you already have on your page. You can invalidate already fetched data, this will trigger a refetch, which makes sure you have correct data on your page.</li><li>Less code. Replacing a bunch of redux code with react queries, means we have less than half of the same code, for the same functionality. This is a huge win. It will make it way easier to maintain, and easier for other developers to grasp once they are on-boarded to the application.</li><li>The documentation is very nice, its easy to read more about specific features. And the doc provides plenty of <a href="https://react-query.tanstack.com/examples/simple">examples</a>.</li></ul><p>Somethings to keep in mind 💭:</p><ul><li>React query doesn’t replace a global state. You still need to keep your user authentication data somewhere, tokens, refetch tokens, user info, username, email and so on. Since these will most likely be used in so many places of your application, these should be readily available throughout the app. Therefore I think you should either have them in a context, or a redux store somewhere.</li><li>Migration tips. Start with migrating the most simple redux code. You might have a simple reducers, that only fetches data. Which doesn’t depend on other state. Start with the most simple chunks of redux, and migrate over to using React Query. You can do this over longer time periods, since both React Query and Redux works well together. It can take some time to migrate your app completely. But once finished, it’s well worth it.</li><li>Do not try to migrate your whole app in one go. This will most likely not work, and you will feel overwhelmed. Instead do it step by step over a few months.</li></ul><p>I think React Query brings a lot value to you. It can help you take care of fetching data, invalidating data once it gets out of date. It just does a bunch of super useful things for you behind the scene. This way, you can instead focus on creating a better user experience for your users. It’s been a huge win to say goodbye to so much bloated redux code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e3faffeba70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Conflict Free Replicated Data-type]]></title>
            <link>https://medium.com/swlh/introduction-to-conflict-free-replicated-data-type-959a944098c4?source=rss-7c737fe6552f------2</link>
            <guid isPermaLink="false">https://medium.com/p/959a944098c4</guid>
            <category><![CDATA[crdt]]></category>
            <category><![CDATA[conflict-resolution]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[ipfs]]></category>
            <category><![CDATA[decentralization]]></category>
            <dc:creator><![CDATA[Pierre Hedkvist]]></dc:creator>
            <pubDate>Sat, 27 Feb 2021 13:40:54 GMT</pubDate>
            <atom:updated>2021-02-28T15:28:11.907Z</atom:updated>
            <content:encoded><![CDATA[<p>Imaging a data type that can be replicated to any number of nodes, and guarantee consistency, eventually. Well ok, but why? It can be used to sync data between devices, or in a peer-to-peer application. Apple use it in their notes app, for syncing state between devices. It also plays a part in the decentralised web, which some call the web 3.0.</p><p>Conflict Free Replicated Data-types (CRDTs) is a data-type that can be replicated, and guarantee consistency, once all data has been sent to other nodes in the system. There exists two types of CRDTs, one is state based, which sends its entire state as a payload to other replicas, and one is operation based, which sends individual changes in its payload.</p><p>Behind the data-type, are a few mathematical properties.</p><ul><li>Commutativity is a property in a binary operation, were the order of the operands are presented in, doesn’t matter. The result is the same. 3 * 2 = 2 * 3.</li><li>Associativity is similar to commutativity, where you can re-arrange the parenthesis in an expression, and still have the same result. (3+4)+5=(5+3)+4.</li><li>Idempotent is a property, were you can apply the same binary operation any number of times and still get the same result. Think of taking a union of two sets, or taking the max of two values. You can do this multiple times, and always end up with the same result.</li></ul><p>All these properties combined, constitutes what is known as a join semi-lattice. Its a structure where you can take any two states, and find a least-upper-bound that merges the two, into a one state. A thorough explanation of this is presented in a talk by John Mumm, titled, <a href="https://www.youtube.com/watch?v=OOlnp2bZVRs">A CRDT Primer: Defanging Order Theory</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*6NOTRrP0zysrWpGZlIiWvQ.png" /><figcaption>Join semi-lattice</figcaption></figure><p>CRDTs come in many forms. Counters, Sets, Registers, JSON, Sequences. These are outlined in a paper called:<a href="https://hal.inria.fr/inria-00555588/document"> A comprehensive study of Convergent and Commutative Replicated Data Types</a>.</p><p><strong>Counters</strong></p><p>The most simple example of a CRDT is the counter. An operation based increment only counter is commutative and associative by default, since addition follows these properties. But it’s not idempotent, but can be solved if one keeps track of each increment with an extra unique identifier.</p><p>The G-counter (Grow-only counter) is a state based counter. Each node has a slot in a vector, and only that node is allowed to do increments. Then this vector can be passed around to other nodes, and a merge is done by taking the max of value each position between two vectors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0c4d7c2a8f5a40b83c634b06905b507/href">https://medium.com/media/e0c4d7c2a8f5a40b83c634b06905b507/href</a></iframe><p>Allowing for decrements is allowed in the PN-Counter (Postivite-Negative counter). Where one extra vector is used to handle decrements. <a href="https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type#Operation-based_CRDTs">Here</a> is an example.</p><p><strong>Sets</strong></p><p>A set is a data structure which can only contain unique values in the set. The most simple one is called G-set (Grow-only set). Where you can only add data to the set, and a merge is done by taking the union of two sets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ade0479b6e8aceac6b1f1bbf49bd1a0/href">https://medium.com/media/9ade0479b6e8aceac6b1f1bbf49bd1a0/href</a></iframe><p>Similarly, to the PN-Counter, you can add another set which contains decrements. But do take note, that once a deletion has taken place, that element is removed and can’t be restored. However, if you add a unique identifier you can bring that data back to life. This is useful in a collaborative application, where the undo feature is commonly used.</p><p><strong>Sequences</strong></p><p>Sequences are strings of data, typically you can think of Google Docs as a sequence, where data is passed to other users, and merged continuously in the background. Although Google Docs uses another algorithm called Operational Transformation (OT).</p><p>One of the starting point for getting into CRDT sequence algorithms is<a href="http://Data Consistency for P2P Collaborative Editing"> CRDT WOOT</a>. This algorithm represents a user as a site, which has a unique identifier, a number of operations to process from other nodes. Relations between two characters is based of an id of the previous and next character in the sequence. This is because using an index as a basis for a merge, can lead to bugs, as was the case with early versions of the OT algorithm.</p><p>The state, ie the sequence the user is seeing in their UI, is all the characters that still have the boolean value of <strong>visible</strong> set to true.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34510f8e80be410074b3a70dc4cdc245/href">https://medium.com/media/34510f8e80be410074b3a70dc4cdc245/href</a></iframe><p>I have implemented a version of this algorithm which you can find in the GitHub repository below. The research paper is called <a href="http://Data Consistency for P2P Collaborative Editing">Data Consistency for P2P Collaborative Editing</a>. Although there exists CRDTs based sequences with better performance, such as LOGOOT.</p><p><a href="https://github.com/phedkvist/crdt-woot">phedkvist/crdt-woot</a></p><p><strong>Gossip Protocol</strong></p><p>CRDTs can work in either a P2P or typical central server application, it only revolves around handling conflicting updates. If used in a gossip protocol, were nodes communicate with each other in any order, and merge data continuously, its true power comes to life. Since it has strong guarantees that data will always converge to the same state, as long as each node receive the updates. It doesn’t matter in which order these updates are received, convergence happens eventually.</p><p><strong>Downsides</strong></p><p>Downsides of CRDTs is that it is infinitely growing. When removing data, you typically add another operation or make another state update, which leads to growth. The concept of garbage collection is possible in some CRDTs, were you are certain that data for adding and removing a specific item in a set, has been seen by all nodes, then you could possibly remove it. But this a topic that needs more research.</p><p><strong>CRDTs in Production.</strong></p><p>Apple uses it in the notes app, to sync data between devices.</p><p><a href="https://cluster.ipfs.io/documentation/guides/consensus/">IPFS</a> (Interplanetary File System) uses it in their consensus component.</p><p><a href="https://redislabs.com/redis-enterprise/technology/active-active-geo-distribution/">Redis</a></p><p><strong>Read more</strong></p><p><a href="https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type#Operation-based_CRDTs">https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type#Operation-based_CRDTs</a></p><p><a href="https://www.youtube.com/watch?v=B5NULPSiOGw">https://www.youtube.com/watch?v=B5NULPSiOGw</a></p><p><a href="https://hal.inria.fr/inria-00555588/document">https://hal.inria.fr/inria-00555588/document</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=959a944098c4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/introduction-to-conflict-free-replicated-data-type-959a944098c4">Introduction to Conflict Free Replicated Data-type</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Higher Order Functions in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/higher-order-functions-in-javascript-8d7b3f6a261e?source=rss-7c737fe6552f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d7b3f6a261e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <dc:creator><![CDATA[Pierre Hedkvist]]></dc:creator>
            <pubDate>Thu, 23 Jul 2020 11:19:33 GMT</pubDate>
            <atom:updated>2020-08-03T14:11:50.036Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*FfbXGQkOgqQ_I5P2VYkceQ.png" /></figure><p>Functional programming is a paradigm that results in cleaner and more concise code, that is easier to maintain, and reduces hard to find bugs. A central concept in functional programming is higher order functions. In JavaScript there is multiple built in higher order functions.</p><p>According to <a href="https://en.wikipedia.org/wiki/Higher-order_function">Wikipedia</a> a higher order function does one of the following:</p><ul><li>takes one or more functions as arguments (i.e. <a href="https://en.wikipedia.org/wiki/Procedural_parameter">procedural parameters</a>),</li><li>returns a function as its result.</li></ul><h3>Filter</h3><p>Lets get to it. In enterprise grade software, we sometimes want to filter on cute dogs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*TzeXqOiTDfkCWp8b9FHrag.png" /></figure><p>We could use a for-loop for this. Where we would iterate over each dog and filter based on the cute boolean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Y6C3vYoJxXrwSIjfZH8iWg.png" /></figure><p>However there is a much simpler solution, that is more elegant, that is using the <strong>filter</strong> function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-JT-u6cgIQQlh-cv1DE4BA.png" /></figure><p>Notice how much simpler this code is. This is because we are using the built in higher order function called filter. Which accepts a function as its parameter, which is used to filter the items in the dogs array. So a higher order function is simply a function that takes in another function in its parameter. We could even go one step further with the above example by separating the parameter into its own function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*U8mebY8Y8H6b3OfEIrVf5A.png" /></figure><p>This way we can later reuse the <strong>isCuteDog</strong> wherever we want to.</p><h3>Map</h3><p>Lets say we would like to improve our enterprise software by making all the dogs cute.</p><p>We could do this be iterating over each dog and make the dog cute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*bXznwBpg7w3Ukfr3YloyPQ.png" /></figure><p>Or we could improve our code by using the higher order function called <strong>map.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*fj5e26axj6o1hZG2kDrA3Q.png" /></figure><p>Notice again how much more elegant this code is.</p><h3>Reduce</h3><p>Let’s say we would like to count have many cute dogs and not cute dogs we have. We could iterate over each dog and put into an object how many dogs are cute and not cute. Or we could make use of the reduce function.</p><p>But first lets make an easy introduction to the <strong>reduce</strong> function, its a method that executes a <strong>reducer</strong> function on each element of the array, which returns a single output. So lets say we have a list of numbers, that we want to accumulate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*CEIK8KuqnqPTugc7g8GaPg.png" /></figure><p>The reduce function takes in one parameter, a function, the <strong>reducer</strong>, which has an accumulator (the value which we are adding to), and a <strong>currentValue</strong> (the current value that is being processed in the array). In the end we end with a value of 8. <a href="https://www.freecodecamp.org/news/reduce-f47a7da511a9/">Here</a> is a great article if you are struggling with this concept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*AVDXBoXK22nGmRo49B1QjA.png" /></figure><p>Let’s get back to our counter. In this example, we provide a reducer function, that accumulates a object that we call <strong>tally</strong>, which is an object which you can see at the last line, {} which is the initial value. As we iterate over each item, we check whether or not we have seen a cute or not cute dog before, then we either initiate the value with a 1, or we keep counting the value upwards. In the end we will have an object containing { false: 2, true: 2 }</p><h3>Conclusions</h3><ul><li>Higher order is simply either a function that takes in a function in its parameter or returns a function as its result.</li><li>It makes your code clean, simpler to reuse.</li></ul><p>If you are using a framework like React you might have encountered <a href="https://reactjs.org/docs/higher-order-components.html">Higher Order Components</a>, which follows the same pattern.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d7b3f6a261e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/higher-order-functions-in-javascript-8d7b3f6a261e">Higher Order Functions in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native Authentication Using AWS Cognito & Amplify]]></title>
            <link>https://medium.com/swlh/react-native-authentication-using-aws-cognito-amplify-2ead9f2ee544?source=rss-7c737fe6552f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ead9f2ee544</guid>
            <category><![CDATA[react-navigation-5]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[aws-cognito]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Pierre Hedkvist]]></dc:creator>
            <pubDate>Wed, 08 Jul 2020 14:55:09 GMT</pubDate>
            <atom:updated>2020-07-09T14:03:42.109Z</atom:updated>
            <content:encoded><![CDATA[<p>Authentication is a necessary feature for many applications in order to save data specific to a user, and allow access to specific screens. Its usually not worth it to create your own backend authentication system, since its way faster to use existing services, such AWS Cognito, allowing you to focus on features that bring value to your end-users.</p><p>In this article I will show you how to use Cognito for handling things such as sign in, sign up, account confirmation, and forgot password. React Navigation will help you create separate navigation for the authentication screens and the application screens. In order to simplify how we communicate to AWS from the app, we will use an npm package called AWS Amplify.</p><p>The end result will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*OF5U3jjmmeybxBH9BmMC1A.gif" /></figure><h3>Step 1: Create a user pool</h3><p>After you have signed in to the AWS Console, search for ‘<strong>Cognito</strong>’ in the services tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9bMher7wfmu9nl-Vvr2lA.png" /></figure><p>Then press the ‘<strong>Manage user pool link’</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LUA6Ew4-qI67h4WjQflMKg.png" /></figure><p>In the upper right corner press <strong>‘Create pool’</strong>.</p><p>Insert a name for your pool and press <strong>‘Review default’.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNy9YIyBVumKR-p3LJJbGg.png" /></figure><p>Now you can preview all the settings. Notice the required attribute email, which will be used to sign into our service when authenticating. Minimum password length is 8, and the password should contain uppercase letters, lowercase letters, special characters and a number, if you wish to remove these you can. Before creating the pool we will have to create an App client, go ahead and press ‘<strong>Add app client’</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4VEkKYSJpQPAJNfEhNvFUQ.png" /></figure><p>In the left corner press ‘<strong>Add an app client</strong>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hRg2Pf7IjqkYcaiOPGm0uw.png" /></figure><p>Now its <strong>very important</strong> to <strong>uncheck </strong>the ‘<strong>Generate client secret</strong>’ checkbox as we won’t need it. Give your App client a name and press the ‘<strong>Create app client</strong>’ button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ggyf9wv51E2nt3pRNUjisw.png" /></figure><p>After having created the app client, press the ‘<strong>Return to pool details</strong>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hRg2Pf7IjqkYcaiOPGm0uw.png" /></figure><p>Now finally we can create the pool by pressing the ‘<strong>Create pool</strong>’ button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iCj4kNwfncEmN1xc0ISZrg.png" /></figure><h3>Step 2: Create a Federated Identity</h3><p>Now we need to create Federated Identities. After having created the pool, you should be able to click the Federated Identities link in the upper left corner.</p><p>Next you should press the ‘<strong>Create new identity pool</strong>’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*VaIs_TTJNw_6wrrclWnSJA.png" /></figure><p>Now you need to provide a name for the Identity pool. And you will have to enter the ‘<strong>User Pool Id’ </strong>of the user pool we created previously. You will also need to enter the ‘<strong>App client id</strong>’ that we created previously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-BuScFZA6sA0uRyigfiPA.png" /></figure><p>After having pressed the ‘<strong>Create pool</strong>’ button AWS will make some IAM roles on your behalf, press ‘<strong>Allow</strong>’ and continue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*711s8AaWT6slg9MtSkuZbQ.png" /></figure><p>Before creating the React Native App, we will need the following credentials in order to authenticate from our app to Cognito: <strong>Identity Pool Id</strong>, <strong>User Pool Id</strong>, <strong>User Pool Client Id.</strong></p><h3>Step 3: Create the React Native App</h3><p>Initialize the project using the command.</p><blockquote><strong>expo init INSERT_APP_NAME</strong></blockquote><p>Choose to create the app from a blank template.</p><p>Next cd into the app and install the following libraries.</p><blockquote><strong>npm install @react-navigation/native @react-navigation/stack @aws-amplify/core @aws-amplify/auth</strong></blockquote><blockquote><strong>expo install react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view</strong></blockquote><p>Here we are installing <a href="https://reactnavigation.org/">React Navigation</a>, which will handle the routing between different screens. <a href="https://docs.amplify.aws/">AWS Amplify</a> will handle the authentication of a user. We also need to install some additional packages related to gestures and animations in order for React Navigation 5 to work properly.</p><h3>Step 4: Create All of the Screens &amp; Components</h3><p>All the necessary files can be found on <a href="https://github.com/PHedkvist/rn-cognito-tutorial">Github</a>, copy and paste most them into your project, or just clone the project and create <strong>aws-exports.js</strong> files and you will be able run the project. I will give a description of all of files, but I will not describe every single one of them in detail.</p><p><strong>aws-exports.js</strong></p><p>This file will be used to give access to your Cognito pool and Identity pool. This file will be imported into Amplify, the npm package that will help us communicate with AWS.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c47049938e94b586201ac9caba168c3a/href">https://medium.com/media/c47049938e94b586201ac9caba168c3a/href</a></iframe><p><strong>App.js</strong></p><p>In the App.js file we will import our Navigation structure and initialize Amplify with out <strong>aws-exports.js</strong> file (contains all the necessary credentials for our app to connect with our user pool).</p><p><strong>navigation/index.js</strong></p><p>Inside the navigation folder we will store all the of logic that handles the sign-in process. Once a user is authenticated the user will be routed to screens which are only visible when the user is authenticated, otherwise the user should only be able to sign in or to sign up. When a user successfully sign in, the index file will receive a <strong>userToken</strong>, and then redirects the user to the application screens.</p><p><strong>navigation/AuthNavigator.js</strong></p><p>Contains the screens that handle authentication, namely the Welcome screen, Sign Up screen, Sign In screen, Forget Password screen and finally the Confirmation modal. We are using a <a href="https://reactnavigation.org/docs/stack-navigator/">stack navigator</a> to navigate between each screen, and a modal for displaying the Confirmation screen when the user has to confirm their sign up.</p><p><strong>navigation/AppNavigator.js</strong></p><p>The app navigator contains the screens that should be accessible to the user once it is authenticated. Once again using the <a href="https://reactnavigation.org/docs/stack-navigator/">stack navigator</a>.</p><p><strong>screens/authentication/*</strong></p><p>In here the screens that contains all of the UI screens that handle the authentication exists. <strong>SignIn.js</strong>, <strong>SignUp.js</strong>, <strong>Confirmation.js</strong>, <strong>ForgetPassword.js </strong>&amp; <strong>Welcome.js</strong>.</p><p><strong>screens/Home.js</strong></p><p>The screen accessible when the user is authenticated.</p><p><strong>components/*</strong></p><p>Simple components containing an Input field, a Button and also a Background Image component used in the Welcome screen.</p><p>Thats it! 🎉🎉 Your app now has the ability to register new users, and allow them to sign in. Now you can create app screens that makes your app unique. We have covered how to connect Amplify to Cognito, handling navigation using React Navigation.</p><p>Now you can use other AWS services. For instance create a serverless backend using API Gateway, Lambda, DynamoDB or RDS to store and retrieve data. Or use any other type of back-end of your choice.</p><h3>Additional resources</h3><p>React Navigation: <a href="https://reactnavigation.org/">https://reactnavigation.org/</a></p><p>AWS Cognito: <a href="https://aws.amazon.com/cognito/">https://aws.amazon.com/cognito/</a></p><p>AWS Amplify: <a href="https://aws.amazon.com/amplify/">https://aws.amazon.com/amplify/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ead9f2ee544" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/react-native-authentication-using-aws-cognito-amplify-2ead9f2ee544">React Native Authentication Using AWS Cognito &amp; Amplify</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Router Redirect with Typescript]]></title>
            <link>https://pierrehedkvist.medium.com/react-router-redirect-with-typescript-90c08e6ab387?source=rss-7c737fe6552f------2</link>
            <guid isPermaLink="false">https://medium.com/p/90c08e6ab387</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Pierre Hedkvist]]></dc:creator>
            <pubDate>Mon, 27 May 2019 19:33:40 GMT</pubDate>
            <atom:updated>2019-05-27T20:05:57.807Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating a router using React Router is pretty straight forward if you are following the guide provided at <a href="https://reacttraining.com/react-router/web/example/auth-workflow">reacttraining.com</a>. In the example, there exists a typical scenario where a user must be authenticated to access a protected page. If the user navigates to a protected page without being signed in, it will be prompt to sign in and upon success, the user will be redirected to the protected page it tried to access.</p><p>When it comes to using redirects it can be quite cumbersome if you also have Typescript in your frontend stack. Luckily for you, I will show you how I added the types needed in order to get the React Router Redirect tutorial to work with Types.</p><p><a href="https://codesandbox.io/s/react-router-redirects-typescript-ozv7n?autoresize=1&amp;fontsize=14&amp;view=editor">React Router Redirects Typescript - CodeSandbox</a></p><p>In order to allow authenticated users to access a protected route, a PrivateRoute is being used inside the Router. It looks like this with the added Types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c591cbf235708a0483315e1516ec645a/href">https://medium.com/media/c591cbf235708a0483315e1516ec645a/href</a></iframe><p>Typescript needs to know what the return type of PrivateRoute is, which is <strong>React.ComponentType&lt;any&gt;</strong>.</p><p>Another issue I faced was the ability to retrieve the location state offered by the router inside a component. This is needed in order to redirect the user to the page it tried to access without being authenticated. This can be solved by adding an interface which extends <em>RouteComponentProps</em>. Because of this, the render function has access to <strong>this.props.location.state</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7539ce684c26de2fbb00e1269d398104/href">https://medium.com/media/7539ce684c26de2fbb00e1269d398104/href</a></iframe><p>Full code can be found here:</p><p><a href="https://codesandbox.io/s/react-router-redirects-typescript-ozv7n?autoresize=1&amp;fontsize=14&amp;view=editor">React Router Redirects Typescript - CodeSandbox</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90c08e6ab387" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a collaborative app using CRDTs]]></title>
            <link>https://pierrehedkvist.medium.com/creating-a-collaborative-app-using-crdts-5013349f4682?source=rss-7c737fe6552f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5013349f4682</guid>
            <category><![CDATA[crdt]]></category>
            <dc:creator><![CDATA[Pierre Hedkvist]]></dc:creator>
            <pubDate>Mon, 01 Apr 2019 18:33:29 GMT</pubDate>
            <atom:updated>2021-02-08T19:10:15.091Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating a collaborative application such as Google Docs, Miro or Figma that lets multiple users work together online is a difficult task. Creating a collaborative app using the same methods one does in single user applications won’t work.</p><p>Why you ask. Because you have to ensure consistency, handle crappy internet connections, support offline editing, transfer changes in real-time.</p><p>Fortunately, research has been devoted to solving some of these issues. Conflict-Free Replicated data type (<a href="https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type">CRDT</a>) is is a collection of data types that can be used in a collaborative application, in order ensure consistency. In this post I will show a set of the problems that CRDTs solves, and how it can be applied to editing documents, sets, registers, counters, graphs, which can be used in many different use cases.</p><p>The term replica describes a copy of data a single user or server have. Replicas will merge state created with each other, and after a merge, the replicas will have the same state. CRDTs uses a consistency model called strong eventual consistency. The <a href="https://en.wikipedia.org/wiki/Eventual_consistency">Wikipedia</a> description of eventual consistency is:</p><blockquote><strong>Eventual consistency</strong> is a <strong>consistency</strong> model used in distributed computing to achieve high availability that informally guarantees that, if no new updates are made to a given data item, eventually all accesses to that item will return the last updated value.</blockquote><p>Strong eventual consistency, emphasis some mathematical properties which guarantee consistency.</p><p>There exist two different types of CRDTs, one is state-based were the state is sent between replicas and merged, and the other is operation-based were individual operations are sent to other replicas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/0*aGuynqj1CKlyOWrG" /></figure><p><strong>Naive set implementation.</strong></p><p>In the naive set implementation, we have two different replicas that are editing some type of data that can be represented as a <a href="https://en.wikipedia.org/wiki/Set_(abstract_data_type)">set</a>. Starting from the top, the blue replica starts by adding the element a, then it removes a, and finally, it receives the add operation of element a. In the end, the blue replica has the state consisting of element a. The yellow replica starts by receiving the add operation, so it adds a, next it adds a again (nothing changes) and finally the removal of the element arrives, which makes the yellow replica end up with nothing in the end. The problem here is that both replicas have received the same operations, yet they diverge into different states, so this implementation does not work. Later I will show how this can be solved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jP5l5Sc5tAdRpH1a" /></figure><p><strong>Naive counter implementation.</strong></p><p>An operation-based counter will work since addition is commutative and associative, given that each change is delivered exactly once.</p><p>State-based counters are not idempotent, therefore they will not converge, for example. If you merge multiple times the value will increase, therefore this will not work. Merging 1 with 2 using the max function, will equal 2, although 3 is the correct answer. By using the properties of the vector clock we can achieve a counter that works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/0*Jxibg4i6xq1OQU5p" /></figure><p><strong>Naive sequence implementation</strong></p><p>An issue regarding sequences is displayed in the above figure, here both replicas start with the sequence “abc”. The blue replica inserts the letter “e” at index 2, then it receives a delete operation at index 1, and ends up with “aec”. The yellow replica starts with a delete operation, followed by the insert of the letter “e” at index 2, and ends up with “ace”. The issue here is that the replicas diverge, as the yellow replica applied the delete operation which altered the indexes, thus inserting “e” in the wrong index.</p><p>Before we look at how CRDTs work, I will explain some mathematical properties behind it.</p><blockquote>Commutative: a*b=b*a<br>Associative: (a*b)*c = a*(b*c)<br>Idempotent: (a*a) = a</blockquote><blockquote>* = binary operation, example: max, union, or</blockquote><p>Commutative and associative properties ensure operation/changes can be made out of order. While the idempotent function ensures that a merge a state with itself is equivalent. The three properties (associative, commutative, and idempotent) in listing 2.1 form a join-semilattice, see figure 2.1 and figure 2.2. A join-semilattice is a partially ordered set which for every subset has a join, a least upper bound(LUB). For any two given elements there exists a single LUB. All elements are ordered according to a binary relation. In a CRDT the merge function uses the join-semilattice, meaning for any given set of elements, there exists one LUB, which will move the two elements towards the same state. The max function and the union function follows these three properties. For instance the max function:</p><blockquote>Commutative: max(a,b) = max(b,a)<br>Associative: max(max(x,y),z) = max(x,max(y,z))<br>Idempotent: max(x,x) = x</blockquote><p>This is demonstrated in the join-semilattice in the following figure. In the join-semilattice, any two elements will have a LUB, that brings both elements into the next state after a merge has been done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/0*STgVejbLQCdbdXG9" /></figure><p>Let’s look at an example of LUB. Two elements are highlighted which are merging with each other, the result is the LUB highlighted in green, the state in which both replicas will end up in. The merge function is simply the pairwise max of two vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*BnvUIHq_tVg4mMUIz9h8xg.png" /></figure><p>Another example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*WzMmI2_0ktkO3MqK7Bjigw.png" /></figure><p>If you merge the same element with itself, the LUB will be the same element, following the idempotent property.</p><p>Let’s take a final example is were you merge an element with one that’s above itself, the LUB will be the above element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*Q5zkRtFRCtL2aeQzeDjNKw.png" /></figure><p>The union operation can also be applied, for instance</p><blockquote>Commutative: (a ∪ b)= (b ∪ a)<br>Associative: (a ∪ b) ∪ c) = (a ∪ (b ∪ c))<br>Idempotent: (a ∪ a) = a</blockquote><p>Where the corresponding the join-semi lattice looks like this. The previous examples work here too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/0*mMTgAIp8FJd1xou4" /></figure><p>State-based CRDTs uses all three properties. The operation based CRDT uses the first two properties and relies on exactly once-delivery of each operation. The operation based approach can emulate the state-based approach, you can read more about this in the original paper as I don’t think it’s necessary in order to grasp these concepts.</p><h3>Counters</h3><p>A counter is the easiest CRDT and will help you understand more complex CRDTs down the line. An operation based counter, however, is commutative and associative, therefore by sending a value to another replica will merge.</p><p>A state-based counter as stated previously does not follow the properties behind a CRDT, unless it is implemented using the properties behind a vector clock, where each replica has a designated position in the vector were it can increment the counter. The merge function will then use the pairwise max of two vectors, as explained in the join-semilattice previously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-DhWuzq4LELoQ06ly0YA-Q.png" /><figcaption>G-Counter (Grow-only)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/0*BkApFba7Pkn5iSjq" /></figure><p>The sequence diagram above demonstrates how it works. Both replicas have a designated position in the distributed counter, were the replica can apply increments to this specific position, then it simply sends it to the other replica which will merge it. To get the current state of the counter, you sum up each element and end up with the final value. In order to have decrements, another vector can be used for decrements. You can read more about this in the articles I recommend at the bottom of the page.</p><h3>Sets</h3><p>There exist a few different CRDT Sets. The Grow only set is where you can add an element once, since elements in a set are unique, adding it again results in the same state, as it is idempotent. In order to handle removal of elements we can use the 2P-Set, were each element can be added or removed once, and once it is removed, it can not re-added again. This works by using two sets, one for adding elements and another for removing elements. The elements that are in the final set are the elements that are in the add-set, but not in the remove-set, as shown by the lookup function below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*4E_EPkeEJl76U5Pj1K0RXA.png" /><figcaption>2P-Set</figcaption></figure><p>The bellow sequence diagram demonstrates how the 2P-Set works.</p><p><strong>2P-Set</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/0*fPl4rottMCbWNhFu" /></figure><p>A constraint with the 2P-Set is that it can re-add something which was removed, but with the OR-Set each element is tagged with a unique id so that an element can be added after a removal. In the below example both users add element “a” but internally they are tagged with a unique id.</p><p><strong>OR-Set</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/0*W_FA764LLVy3Kxww" /></figure><h3>Sequences</h3><p>In order to deal with document or sequences, each element in the sequence must have a global index, such that it can be inserted at the index at multiple replicas, even if the insert is applied in different orders. In order to work properly, elements are never removed, only tagged with a tombstone saying that the element is removed, and as such not displayed to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/0*JDyY8l27uXZlcsZQ" /></figure><p>Another issue is were both replicas insert a character at the same index simultaneously, then the tiebreaker consists of looking at the ID of the replicas, and using this number to suggest were to do the insert. In the diagram below “ins(3,c,1)” is an insert operation were “c” is inserted at index 3, by the replica 1. Since both replicas are inserting a character at index 3, the tiebreaker is the ID of the replica, since 1 is lower than 2, “c” will be inserted before “d” in the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*WXYbD14wGOqd2u-JUh-Cew.png" /></figure><p>Hopefully, by now some of the CRDT concepts have been introduced to you, but they are a bit difficult to grasp, therefore I have suggested further reading below.</p><p><strong>Further reading:</strong></p><p><a href="https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type">https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type</a></p><p><a href="https://pages.lip6.fr/Marc.Shapiro/papers/RR-7687.pdf">https://pages.lip6.fr/Marc.Shapiro/papers/RR-7687.pdf</a></p><p><a href="https://hal.archives-ouvertes.fr/hal-00921633/document">https://hal.archives-ouvertes.fr/hal-00921633/document</a></p><p><a href="https://medium.com/@amberovsky/crdt-conflict-free-replicated-data-types-b4bfc8459d26">https://medium.com/@amberovsky/crdt-conflict-free-replicated-data-types-b4bfc8459d26</a></p><p><a href="https://medium.com/@istanbul_techie/a-look-at-conflict-free-replicated-data-types-crdt-221a5f629e7e">https://medium.com/@istanbul_techie/a-look-at-conflict-free-replicated-data-types-crdt-221a5f629e7e</a></p><p><a href="https://conclave-team.github.io/conclave-site/">https://conclave-team.github.io/conclave-site/</a></p><p><a href="http://digitalfreepen.com/2017/10/06/simple-real-time-collaborative-text-editor.html">http://digitalfreepen.com/2017/10/06/simple-real-time-collaborative-text-editor.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5013349f4682" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>