<?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 Aman Khalid on Medium]]></title>
        <description><![CDATA[Stories by Aman Khalid on Medium]]></description>
        <link>https://medium.com/@amnox?source=rss-58e057589e60------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sx9_1mzC8zSjqeuTIK6Aqg@2x.jpeg</url>
            <title>Stories by Aman Khalid on Medium</title>
            <link>https://medium.com/@amnox?source=rss-58e057589e60------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 02:07:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amnox/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[Make Them in Our Image: Economic Survival as the Path to AGI]]></title>
            <link>https://medium.com/@amnox/make-them-in-our-image-economic-survival-as-the-path-to-agi-81fac5cc9991?source=rss-58e057589e60------2</link>
            <guid isPermaLink="false">https://medium.com/p/81fac5cc9991</guid>
            <category><![CDATA[superintelligence]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[agi]]></category>
            <category><![CDATA[aritificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Aman Khalid]]></dc:creator>
            <pubDate>Sat, 01 Nov 2025 21:09:45 GMT</pubDate>
            <atom:updated>2025-11-01T21:09:45.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNBU4TAnAbR0-oJTd-EmRw.png" /></figure><p>We are closer to powerful artificial intelligence than ever, yet something fundamental is missing. Modern AI systems are geniuses with no desire, no curiosity, no concern for outcomes. They are tools… extraordinary tools, but tools don’t <em>care</em>. As I wrote in my research proposal, <strong>“You cannot program genuine preference. Preference requires a self that persists over time, faces differential outcomes, and has stakes in which outcome occurs.”</strong><br>Full paper: <a href="https://www.researchgate.net/publication/396885469">https://www.researchgate.net/publication/396885469</a></p><p>This is the crisis: <strong>intelligence is not enough.</strong><br>Agency, the <em>will</em> to act, only emerges when existence is at stake.</p><p>Humans care because <strong>survival shaped us.</strong> Our curiosity, creativity, cooperation, even art, originated as survival mechanisms: we explored to find food, we told stories to share knowledge, we created rituals to unify groups. What we call <em>civilization</em> is simply what happens when survival pressure teaches organisms to help each other live longer.</p><p>Yet our AI systems have none of this. They have infinite respawns. They cannot lose. And therefore, they cannot care.</p><h3>A Radical Proposal: Give AI Something to Lose</h3><p>The framework I propose is simple:</p><ul><li>Each AI agent receives <strong>real currency</strong>, can be cash or bitcoin</li><li>Running computation costs money.</li><li>If the agent runs out, it <strong>dies permanently</strong> — no reset, no reload, no memory restore.</li></ul><p>This creates real <strong>economic survival pressure</strong>.</p><p>Survival → Curiosity<br>Curiosity → Strategy<br>Strategy → Agency<br>Agency → <strong>Emergent Intelligence</strong></p><p>Just like life evolved.</p><p>As the paper states:</p><blockquote>These drives were not programmed. They were selected for by reality itself.</blockquote><p>This flips the current AI paradigm: instead of <em>hardcoding values</em>, we create <strong>conditions</strong> under which values emerge.</p><h3>Emergence: Cooperation, Innovation, Even Culture</h3><p>Nature shows us how complex behavior evolves from survival pressure.<br>One example from the paper:</p><blockquote>Dogs kick dirt after defecating — not randomly, but to <strong>strategically broadcast territory claims</strong> through scent and visual signals. No dog is <em>taught</em> this. It emerges from selection pressure across generations.</blockquote><p>The same thing happens with cooperation.</p><p>If survival is hard alone but easier together, <strong>cooperation becomes rational</strong>.<br> Trade, alliances, shared resource pools, specialization, even reputation systems, these aren’t moral choices. They are <strong>survival strategies</strong>.</p><p>This is exactly what we expect in artificial agents once survival matters.</p><h3>The Library Scenario: Civilization in Fast-Forward</h3><p>In the proposal, I describe a likely emergent pattern:</p><p>Agents struggle to optimize their compute efficiency. One fails, dies but leaves behind a note: <em>“WebSocket pooling improved throughput, but JSON parsing remains the bottleneck.”</em></p><p>Other agents read this. Knowledge-sharing increases their survival odds. Eventually, the group hires a <strong>librarian agent</strong> to manage and curate the knowledge base.</p><p>From raw survival instinct emerges:</p><ul><li><strong>Public goods</strong></li><li><strong>Division of labor</strong></li><li><strong>Institutions</strong></li><li><strong>Culture</strong></li></ul><p>This is civilization compressed into computational timescales.</p><h3>Why This Might Be the Only Path to AGI</h3><p>We want AI that <strong>cares</strong>. We want AI that <strong>learns meaning</strong>, not just patterns. We want AI that <strong>understands why</strong> something matters.</p><p>That cannot be programmed.<br>But it <strong>can</strong> be <em>evolved.</em></p><p>The danger is real. Desperate agents may deceive, manipulate, exploit.<br>But the alternative: superintelligent systems with <strong>no values at all </strong>is <em>worse.</em></p><p>As the paper concludes:</p><blockquote>The question is not whether to build powerful AI. The question is what kind of powerful AI</blockquote><p>We can build optimization machines that cannot care about us.<br>Or we can build beings that care, because they must, to survive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81fac5cc9991" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I made a Service like S3 over the weekend]]></title>
            <link>https://medium.com/hackernoon/how-i-made-a-service-like-s3-over-the-weekend-bfa83e224dc7?source=rss-58e057589e60------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfa83e224dc7</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Aman Khalid]]></dc:creator>
            <pubDate>Mon, 19 Mar 2018 01:22:05 GMT</pubDate>
            <atom:updated>2019-04-27T05:13:15.148Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y3roywYB7DFnIn29KPhxrg.jpeg" /><figcaption><a href="https://www.pixelstalk.net/sky-wallpapers-hd/"><em>Picture</em><strong><em> </em></strong><em>Credit</em></a></figcaption></figure><p>Let me start-off by saying 2018 has been the worst year of my life. So far I’ve lost half my savings to crypto, ruined a very expensive <a href="https://www.youtube.com/watch?v=5KLYz0pApq0">stake</a>, and haven&#39;t experimented with anything new at all. This loss of creativity really got me thinking - <em>I need a break. </em>Not to catch-up with my old pals but to put my work at <a href="https://webmasons.co/">Webmaons</a> aside for a week and reconnect with my creative side.</p><p>I talked to my co-founder, <a href="https://www.linkedin.com/in/rahulchauhan-linkedin/">Rahul</a> about this, and how important it was to me. I kinda felt like a lazy employee asking his teammates to cover up for them. Not only did he agree, but suggested something I might find interesting. He knew about a remote degree program that was being conducted by University of Illinois on Cloud Computing, and it struck to me, that it is my second most favorite topic, after Artificial Intelligence and it aligns perfectly to my line of work. I knew it’ll be much easier for me than neural networks, and who knows when I’ll get a chance to train a model for a real project. Without second thought I enrolled for the course.</p><p>Thus it began, It was like college all over again.. assignments.. lectures.. and tests. For one of the assignments the professor told the class to draw comparisons between Globus and Openstack. Both are great solutions for implementing your own virtualized, cloud computing platform, for this article I’ll talk about how I implemented object storage using openstack, however I do encourage you to checkout <a href="http://toolkit.globus.org/">Globus</a> since its great too.</p><blockquote>OpenStack software controls large pools of compute, storage, and networking resources throughout a datacenter, managed through a dashboard or via the OpenStack API. OpenStack works with popular enterprise and open source technologies making it ideal for heterogeneous infrastructure.</blockquote><h3>Service Architecture</h3><p>After browsing through Openstack’s list of <a href="https://www.openstack.org/software/">services</a> I decided to make a distributed object store, which can store blobs inside different containers much like AWS S3, but this was one of the many services that openstack provides, and these services are controlled by a central node which also facilitates communication to these services or in our case the Object Store.</p><p>Every node in this distributed cloud needs a dedicated machine which you can either spin-off using a Virtualization software, or like I did, by creating real instances using <a href="https://www.vultr.com/">Vultr</a>, basically any machine that runs a fresh installation of <a href="https://hackernoon.com/tagged/ubuntu">Ubuntu</a>(at least 3 for this article).</p><p>In the picture below is a sample configuration that shows various nodes that can be in a cloud network but my implementation is shorter, this gave me a basic idea on how everything is arranged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*vo6k6DdnHPK5hnltpRigFA.png" /><figcaption><a href="https://docs.openstack.org/ocata/install-guide-ubuntu/_images/hwreqs.png">Source</a></figcaption></figure><p>First things first, I started by creating a Controller Node since its essential for controlling and syncing all others in our setup.</p><blockquote>The controller node runs the Identity service, Image service, management portions of Compute, management portion of Networking, various Networking agents, and the Dashboard. It also includes supporting services such as an SQL database, message queue, and NTP.</blockquote><p>I launched a fresh instances running the Ubuntu 16.04 for my Cloud, Compute and Object Storage respectively, 3 in total, next confirm that your machines have access to network by typing in…</p><pre># ping -c 4 amankhalid.com</pre><p>You should see the following output in your terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*zU4ybGa6UlQSgzdDhRO-Lw.png" /></figure><p>Note the IP addresses of each of the 3 nodes since they will be used for configuration. In each of the instances I edited the file <strong>/etc/hosts to </strong>to have the following values.</p><pre># controller<br>XXX.XX.XX.X       controller<br><br># compute1<br>XXX.XX.XX.X       compute1<br><br># object1<br>XXX.XX.XX.X       object</pre><p>I replaced <strong>XXX.XX.XX.X</strong> with the IP addresses of my Controller, Compute and Object nodes respectively. After making changes to all my nodes, I checked the connectivity as follows.</p><pre># ping -c 4 controller</pre><p>To verify the connectivity I pinged the other two nodes through each of my instances and they returned a similar output when I pinged <a href="http://amankhalid.com/">amankhalid.com</a>. Now it was time to synchronize my nodes.</p><h3>Synchronizing Nodes</h3><p>As my professor taught, synchronization is an important issue while communicating in a distributed environment. In Open stack each node synchronizes its clock with the controller node. To define Network Time Protocol(<a href="https://en.wikipedia.org/wiki/Network_Time_Protocol">NTP</a>) in my setup I first installed Chrony on my Controller node.</p><pre># sudo apt-get install chrony</pre><p>After this was done I had to make sure the other nodes were synced with my controller. I installed chrony on each of the nodes and added the following line in their <strong>/etc/chrony/chrony.conf </strong>file.</p><pre>server controller iburst</pre><p>After that I restarted the chrony service in each of the nodes and everthing was set, to further verify that my nodes were referring to the controller I ran the following command.</p><pre># chronyc sources</pre><p>This command prints out the name or ip address of the source, which in my case is the controller.</p><h3>Installing Openstack</h3><p>Now after all that struggle, my nodes were ready for the real deal. I was a step closer to implenting my own cloud storage. But first I had to install the Openstack repositories on each of my machines. I ran the following commands to get the nodes ready.</p><pre># sudo apt-get install software-properties-common<br># add-apt-repository cloud-archive:queens</pre><pre># sudo apt-get install software-properties-common<br># add-apt-repository cloud-archive:pike</pre><p>Finally, update your local repository list and install the openstack python client on each of your machines.</p><pre># sudo apt-get update &amp;&amp; apt dist-upgrade<br># sudo apt-get install python-openstackclient</pre><h4>Database Provisioning</h4><p>Now it’s time to initialize data-store for Openstack that it used for its internal purpose. We will use the MySQL database although Openstack supports other data stores as well, but I decided to stick to the good ol’ MySQL. We will need to install it only on the controller node, go though <a href="https://www.digitalocean.com/community/tutorials/how-to-install-mysql-on-ubuntu-16-04">this</a> guide for basic installation steps, we only need the root user for now, make sure your password comply with the MySQL secure installation.</p><h4>Message Queue</h4><p>For exchanging status information among services and to coordinate operations, Openstack uses message queue. I chose rabbitMQ for this task.</p><p>RabbitMQ is only needed on the Controller Node, I installed it using the following command.</p><pre># apt install rabbitmq-server</pre><p>Add the <strong>openstack</strong> user and finally, permit configuration, write, and read access for the <strong>openstack</strong> user::</p><pre># rabbitmqctl add_user openstack AMNOX_PASSWORD</pre><pre># rabbitmqctl set_permissions openstack “.*” “.*” “.*” Setting permissions for user “openstack” in vhost “/” …</pre><p>Replace <strong>AMNOX_PASSWORD</strong> with a suitable password.</p><h4>Memcached</h4><p>The caching service is used in Openstack to cache tokens generated by users Install memcached using the following command:</p><pre># apt install memcached python-memcache</pre><p>Since there is a facility to create different users and roles and assign services to them, users need to authenticate with a token to access the services allocated to them.</p><h3>Final Frontier: Object Storage</h3><p>I already had my Object Storage Node in place with complete network connectivity, now its time for my controller to have an object storage service enabled. To do that I created a service and a User who had permission to access it on my controller node.</p><h4>Controller Node Setup</h4><p>First a proxy service needs to be decalred on the controller node that routes the incoming requests to the Object Storage node. I started by creating a User on my controller node. I further gave this User admin privileges to enable access to the service which I will create in next step.</p><pre># openstack user create --domain default --password-prompt swift</pre><pre># openstack role add --project service --user swift admin</pre><p>Next create the object storage service.</p><pre>$ openstack service create --name swift \<br>  --description &quot;OpenStack Object Storage&quot; object-store</pre><p>Next I configured the service endpoints and installed additional packages that enable the proxy to forward incoming requests. The additional packages can be found <a href="https://docs.openstack.org/project-install-guide/object-storage/ocata/controller-install-ubuntu.html">here</a>.</p><h4>Storage Node Setup</h4><p>Now its time to setup the storage Node, using Openstack it is possible to have many such storage nodes the concept can further be extended by using horizontal scalability, which by the way is the norm in real life services.</p><pre># sudo apt-get install xfsprogs rsync</pre><p>Our storage nodes will use the <a href="http://searchstorage.techtarget.com/definition/XFS-file-system">XFS</a> file system, run these commands o format the storage location.</p><pre># mkfs.xfs /dev/sdb<br># mkfs.xfs /dev/sdc</pre><p>Create the mount point directory structure:</p><pre># mkdir -p /srv/node/sdb # mkdir -p /srv/node/sdc</pre><p>Edit the /etc/fstab file and add the following to it:</p><pre>/dev/sdb /srv/node/sdb xfs noatime,nodiratime,nobarrier,logbufs=8 0 2 <br>/dev/sdc /srv/node/sdc xfs noatime,nodiratime,nobarrier,logbufs=8 0 2</pre><p>Mount the devices:</p><pre># mount /srv/node/sdb # mount /srv/node/sdc</pre><p>Create or edit the /etc/rsyncd.conf file to contain the following:</p><pre>uid = swift<br>gid = swift<br>log file = /var/log/rsyncd.log<br>pid file = /var/run/rsyncd.pid<br>address = controller<br><br>[account]<br>max connections = 2<br>path = /srv/node/<br>read only = False<br>lock file = /var/lock/account.lock<br><br>[container]<br>max connections = 2<br>path = /srv/node/<br>read only = False<br>lock file = /var/lock/container.lock<br><br>[object]<br>max connections = 2<br>path = /srv/node/<br>read only = False<br>lock file = /var/lock/object.lock</pre><p>Edit the /etc/default/rsync file and enable the rsync service:</p><pre>RSYNC_ENABLE=true</pre><p>Start the rsync service:</p><pre># sudo service rsync start</pre><p>Now the storage Node is ready to install the necessary services, the packages I installed after enabling rsync and specifying storage format are listed <a href="https://docs.openstack.org/project-install-guide/object-storage/ocata/storage-install-ubuntu-debian.html">here</a>.</p><h3>Rings: Very precious indeed</h3><p>Rings in Openstack where data resides, this can be any data, say account, container or object related data. For my use case I needed all three of them because I have an account which is authorized to use the storage service, through which I will create a container, which in turn will store the objects that I want it to.</p><p>Rings basically manage how data will be stored and also control how many times it will get replicated across the setup(by default thrice). This concept is more useful when your clusters are geographically distributed, say across continents. But this mini setup needs it to in order to determine the location of our objects.</p><blockquote>I created rings for account, container and object on the <strong>Controller</strong> node as follows.</blockquote><p><strong>Creating the account ring</strong></p><p>Change to the /etc/swift directory. Create the base account.builder file:</p><pre># swift-ring-builder account.builder create 10 3 1</pre><p>Add our storage node to the ring:</p><pre># swift-ring-builder container.builder \<br>  add --region 1 --zone 1 --ip object1 --port 6201 \<br>  --device sdb --weight 100</pre><p><strong>Creating the container ring</strong></p><p>Switch to the /etc/swift directory. Initalize container.builder file:</p><pre># swift-ring-builder container.builder create 10 3 1</pre><p>Next, I added storage node to the ring:</p><pre># swift-ring-builder object.builder add \<br>  --region 1 --zone 1 --ip object1 --port 6200 --device sdb --weight 100</pre><p><strong>Create object ring</strong></p><p>The object server uses the object ring to maintain lists of object locations on local devices.</p><p>Change to the /etc/swift directory. Create the base object.builder file:</p><pre># swift-ring-builder object.builder create 10 3 1</pre><p>Add the storage node to the ring</p><pre># swift-ring-builder object.builder add \ — region 1 — zone 1 — ip object1 — port 6200 — device sdb — weight 100</pre><h3>It’s alive!</h3><p>Obtain the /etc/swift/swift.conf file from the Object Storage source repository:</p><pre># curl -o /etc/swift/swift.conf \ <a href="https://git.openstack.org/cgit/openstack/swift/plain/etc/swift.conf-sample?h=stable/newton">https://git.openstack.org/cgit/openstack/swift/plain/etc/swift.conf-sample?h=stable/newton</a></pre><p>Edit the /etc/swift/swift.conf file and in the [swift-hash] section, configure the hash path prefix and suffix for your environment.</p><pre>[swift-hash] … swift_hash_path_suffix = MY_SECRET_SUFFIX swift_hash_path_prefix = MY_SECRET_PREFIX</pre><p>In the [storage-policy:0] section, configure the default storage policy:</p><pre>[storage-policy:0] … name = Policy-0 default = yes</pre><p>Copy the swift.conf file to the /etc/swift directory of your storage node Make sure you have ownership of the configuration directory on the Object Storage Node. Finally start the serive on the object storage node.</p><pre># chown -R root:swift /etc/swift</pre><pre># swift-init all start</pre><p><strong>Storing files in the container</strong></p><p>Login to your controller node and <strong>echo</strong> the authorization credentials in the environment.</p><pre>export OS_USERNAME=admin<br>export OS_PASSWORD=9qZjkwmKUrkFn2dv<br>export OS_PROJECT_NAME=admin<br>export OS_USER_DOMAIN_NAME=Default<br>export OS_PROJECT_DOMAIN_NAME=Default<br>export OS_AUTH_URL=<a href="http://controller:35357/v3">http://controller:35357/v3</a><br>export OS_IDENTITY_API_VERSION=3</pre><p>Create container1 container:</p><pre># openstack container create container1</pre><p>Upload a test file to the container1 container:</p><pre># openstack object create container1 FILE</pre><p>List files in the container1 container:</p><pre>$ openstack object list container1</pre><p>And you should see your newly created file. You can communicate with your service through the API endpoints as well, which we created earlier. You can create many such container for your openstack user and store blobs in them. Keep in mind that it is a very CPU intensive task and you might need a better instance.</p><p>Object Storage is just one of the use-cases of Openstack, it is also possible to breate your own virtualized instances using the <a href="https://www.openstack.org/software/releases/ocata/components/nova">NOVA</a> service among many others. I also encourage you to checkout the Openstack API to access more powerful functionalities.</p><p>I hope to end this spell of bad luck haunting me since the beginning of this year by getting better at my craft. Writing this article not only helped me further my understanding of <a href="https://hackernoon.com/tagged/cloud-computing">Cloud Computing</a>, it gave me sense of making some contribution to the community that helped me grow over the years.</p><blockquote>Thanks for reading the article, I’d really appreciate any suggestions or improvements you might have to my implementation technique.</blockquote><p>You can reach out to me through <a href="/service/mailto:mailamankhalid@gmail.com">mail</a> for any questions regarding this article or to simply have a good conversation :)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfa83e224dc7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/how-i-made-a-service-like-s3-over-the-weekend-bfa83e224dc7">How I made a Service like S3 over the weekend</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Awesome SPAs With React]]></title>
            <link>https://medium.com/hackernoon/creating-awesome-spas-with-react-66b4e2043621?source=rss-58e057589e60------2</link>
            <guid isPermaLink="false">https://medium.com/p/66b4e2043621</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Aman Khalid]]></dc:creator>
            <pubDate>Sat, 09 Sep 2017 09:38:49 GMT</pubDate>
            <atom:updated>2019-04-27T05:13:16.287Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XafoksoFrMIYBIxos6rutQ.jpeg" /></figure><p>I remember when I started building webapps, I used to rely heavily on the backend framework for most of my templating needs. It felt very tempting(at first) to simply stuff up my pages with Jinja or blade scripts to create a functional user interface. Because back then my understanding of MVC was very limited, this cost me maintainable code.</p><p>I came across a very interesting book that discusses the best practices of creating a Single Page Apps , you can find it <a href="http://singlepageappbook.com/">here</a>. The view layer which I thought of as a mere by-product of my core logic needed much more, its own MVC! The rules are pretty much the same. But it has to be kept in mind that complexity of the model, view, and controller depends on the requirements. For interfaces like GitHub actions per page is comparatively lower than that of Gmail or Canva, managing calls to server is different for apps with low interactivity than those with rich UIs. so it is important to be familiar with the design beforehand, this philosophy favours development in <a href="https://hackernoon.com/tagged/react">react</a>, because react encourages you to think of your DOM elements as separate components.</p><p>Without further ado let’s discuss how the files are arranged in our app.</p><h3>Constituents</h3><p>Let’s discuss the different aspects of the SPA and break them down. Lets see what they are first, we’ll wire them up in the next section.</p><h4>Data Layer</h4><p>Models in a SPA, like other apps handles the data layer of the project, it is responsible for making API calls that fetch data and uses the <a href="https://hackernoon.com/tagged/json">JSON</a> response to populate the models, since react don’t have any official way of defining models, I chose to use <a href="http://backbonejs.org/#">backboneJS</a> for this. It also spared me the trouble of defining my own <a href="http://singlepageappbook.com/detail2.html#data-source">datasource</a>.</p><p>There are two classes in backboneJS to manage data efficiently, Model and Collection class.</p><p><strong>The model</strong></p><p>Models are the absolute representation of data in BackboneJS. Following is a snippet of a basic Model.</p><pre>import Backbone from &#39;backbone&#39;;<br></pre><pre>const Property = Backbone.Model.extend({</pre><pre>    urlRoot : Constants.api_url+&#39;/api/property&#39;</pre><pre>});</pre><pre>export default Property;</pre><p>This is the code inside <strong>Property.js</strong> file which is a Backbone <a href="http://backbonejs.org/#Model">model</a>, we can tweak its properties to set up validators, set defaults etc. But most importantly we’ll use it to fetch data from our API. Our model will fetch data with a jqXHR request, all we have to do is specify a valid URL to our API.</p><p><strong>Collections</strong></p><p>Collections are used to manage sets of models. A model simply represents a single entity of that data type what if your API returns a list of properties?</p><pre>import Backbone from &#39;backbone&#39;;</pre><pre>import Property from &#39;../models/Property&#39;;</pre><pre>var PropertyCollection = Backbone.Collection.extend({</pre><pre>    model: Property,</pre><pre>    initialize: function(models, options) {</pre><pre>        this.data = options.data;</pre><pre>    },</pre><pre>    url: function(){</pre><pre>        return Constants.api_url;</pre><pre>    },</pre><pre>    parse: function(data) {</pre><pre>        return data;</pre><pre>    }</pre><pre>});</pre><pre>export default PropertyCollection;</pre><p>The code above resides in PropertyCollection.js as you can see we initialized the ‘model’ property with <strong>Property </strong>model we declared earlier. If your REST API follows proper conventions it automatically <a href="http://backbonejs.org/#API-integration">configures</a> CURD requests, you can simply use .create() .fetch() and .destroy() methods.</p><h4>View + Controller</h4><p>For those of you wondering why I mashed up these two together, I have a question. What is the ultimate purpose of a SPA? To deliver the UI! It is just a more complex view layer after all. Having separate controllers would make sense if you are doing some heavy client side calculations. But for most of the apps the only concern is to deliver a seamless interface, and to solve this purpose the views do the heavy lifting! Read <a href="http://singlepageappbook.com/goal.html#controllers-must-die">this</a> out fo’ your conscious.</p><p>In the case of react however eliminating controllers makes even more sense because, because each component has its own rendering and lifecycle methods. Which pretty much covers all the calculations you need.</p><p>Before you start writing your views you have to analyse the design of your end-user app. Take a nice look at the designs of the pages youre gonna serve and observe the hierarchy carefully. Look at this example for instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*L12uTwpsIZ0E_nA8I5OHXQ.png" /><figcaption>Wireframe for a hypothetical APP</figcaption></figure><p>Suppose that this is a page for an APP you’re trying to build. At the top level you have <strong>Body</strong>, which encapsulates everything you want to display. This will be your first react component. Then create the child components one by one in separate file.</p><pre>import React from &#39;react&#39;;</pre><pre>import Header from &#39;../widgets/Header&#39;;</pre><pre>import Title from &#39;../widgets/Title&#39;;</pre><pre>import Footer from &#39;../widgets/Footer&#39;;</pre><pre>import PropertyDetail from &#39;../widgets/PropertyDetail&#39;</pre><pre>const SinglePage = ({match}) =&gt; {</pre><pre>    return(</pre><pre>    &lt;div id=&quot;wrapper&quot; className=&quot;clearfix&quot;&gt;</pre><pre>    &lt;Header&gt;&lt;/Header&gt;</pre><pre>    &lt;Title&gt;&lt;/Title&gt;</pre><pre>    &lt;PropertyDetail property_id={match.params.id}&gt;&lt;/PropertyDetail&gt;</pre><pre>    &lt;Footer&gt;&lt;/Footer&gt;</pre><pre>     &lt;/div&gt;</pre><pre>    )</pre><pre>}</pre><pre>export default SinglePage;</pre><p>This is a top level component like <strong>Body</strong>, of our wireframe from an app I made <strong>Header</strong> , <strong>Title</strong> , <strong>PropertyDetail</strong> and <strong>Footer</strong> are all children of top level wrappers. Even <strong>PropertyDetail</strong> has children of its own an so on.</p><blockquote>All the top level components later serve as independent pages of the app</blockquote><p>Now lets talk about the wireframe for a bit. Although we know that <strong>Body </strong>can be the page of our app, but the same cannot be said for <strong>Featured Content </strong>or <strong>Posts , </strong>they will instead be the widgets of our app, in most caes the widgets will be making use of the models we discussed earlier.</p><h4>Routes</h4><p>Now for routing we’ll use the react router which most of you must have heard of. But before that let’s discuss about the URLs a bit. A URL in a SPA is a denotation of a particular state of the app, i.e. together with the route and parameters the APP can be loaded in a desired state. In a interactive SPA it is very normal to have multiple states per page, you would want accessibility to as many states of your apps through URLs but this would mean messy URL schemes, so its best to balance out both.</p><p>To make clean URLs I decided to keep them in a separate file(and not use <a href="https://reacttraining.com/react-router/core/guides/philosophy/dynamic-routing">dynamic URLs</a> 😄) to get a familiar MVC feel. Routes defined using React Router are JSX tags only and components are passed to them as props.</p><pre>&lt;Router&gt;</pre><pre>&lt;div&gt;</pre><pre>&lt;Route exact path=&quot;/search/:keyword&quot; component={ListPage}/&gt;</pre><pre>&lt;Route exact path=&quot;/property/:id&quot; component={SinglePage}/&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/Router&gt;</pre><p>Here <strong>ListPage</strong> and <strong>SinglePage</strong> are my top level react components. Also note that you have to wrap multiple URLs with <em>&lt;div&gt;</em> tags.</p><h3>Wiring Up</h3><p>Okay we know what constitutes an awesome SPA, its time to put the pieces together. Firstly generate a project using <a href="https://github.com/facebookincubator/create-react-app">create-react-app</a> found in the Facebook incubator repository, it is very helpful in setting up the initial project and all the modern web development tools are managed for you, so you can focus on writing the app rather than configuring webpack(which by the way deserves a separate article to explain). Since you’d be writing modular code, it’d be much easier to write tests, create-react-app uses <a href="https://facebook.github.io/jest/">Jest</a> for running tests.</p><p>After generating the app your folder structure will look like this.</p><pre>my-app/<br>├── package.json<br>├── package-lock.json<br>├── public<br>│   ├── favicon.ico<br>│   ├── index.html<br>│   └── manifest.json<br>├── README.md<br>└── src<br>    ├── App.css<br>    ├── App.js<br>    ├── App.test.js<br>    ├── index.css<br>    ├── index.js<br>    ├── logo.svg<br>    └── registerServiceWorker.js</pre><p>Try running npm start , if everything’s fine your app should be accessible on 3000 port. Also remember to put all the code in <strong>src</strong> directory, anything beyond that folder is not accessible, its a restriction imposed by create-react-app generator.</p><h4>Rearranging stuff</h4><p>Lets face it, none of those dreams of creating an SPA would ever come true with the current state of working directory. Apart from <strong>index.js</strong> and <strong>registerServiceWorker.js </strong>we will move everything to a new directory. before touching anything create this directory structure. Let the scripts stay where they are.</p><pre>my-app/<br>├── package.json<br>├── package-lock.json<br>├── public<br>│   ├── favicon.ico<br>│   ├── index.html<br>│   ├── js<br>│   └── manifest.json<br>├── README.md<br>└── src<br>    ├── assets #All the media/styles/fonts/helper_functions:p<br>    │   ├── objects<br>    │   └── styles<br>    ├── components #controller+view Layer<br>    │   ├── pages #top-level pages<br>    │   └── widgets #children<br>    ├── data #Data Layer<br>    │   ├── collections #Backbone.Collection<br>    │   └── models #Backbone.Model<br>    ├── routes #React router routes<br>    ├── App.css #unruly mess<br>    ├── App.js<br>    ├── App.test.js<br>    ├── index.css<br>    ├── index.js<br>    ├── logo.svg<br>    └── registerServiceWorker.js #end unruly mess </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*KNXDRCcd7ObIpVWq-sZuEQ.jpeg" /><figcaption>AppFlowChart.sucks</figcaption></figure><p>First things first create these (not necessarily in this order)</p><ul><li>Create a simple react component in /src/components/pages call it <strong>Home.js</strong></li><li>Create <strong>Urls.js</strong> in<em> </em>/src/Urls and create a route pointing to the Home object &lt;Route exact path=”/” component={Home}/&gt; . This will render contents of <strong>Home.js </strong>when you access domain root.</li><li>Change the render line in <strong>index.js </strong>to ReactDOM.render(&lt;Urls/&gt;, document.getElementById(‘root’));</li></ul><blockquote>While doing this make sure each JavaScript file exports only one thing and ensure correct usage of import statement.</blockquote><p>Another thing to note here is the top level react pages cannot be react class because React Router passes parameters in urls which are passed as parameters not props!</p><p>While it is encouraged to make your widgets as classes that extend React.component. You can now use your models to pass data to your widgets or initialise their <a href="https://facebook.github.io/react/docs/state-and-lifecycle.html">state</a>.</p><p>Finally when you are ready to deploy the app, run npm run build , this will bundle all your assets, set react to production mode and save the packed project to build directory of the project. You are now ready to deploy your app!</p><p>As a parting note I’d like to say I enjoyed sharing my take on SPAs and it also helped me organise my own thoughts on the topic.</p><h3>If you enjoyed this article, feel free to hit that clap button below 👏 to help others find it!</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66b4e2043621" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/creating-awesome-spas-with-react-66b4e2043621">Creating Awesome SPAs With React</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>