<?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 Patrick Murphy on Medium]]></title>
        <description><![CDATA[Stories by Patrick Murphy on Medium]]></description>
        <link>https://medium.com/@patrickmurphy_53381?source=rss-830bf45bfe19------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HZclVBcDOxik9Qtc.</url>
            <title>Stories by Patrick Murphy on Medium</title>
            <link>https://medium.com/@patrickmurphy_53381?source=rss-830bf45bfe19------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 04:11:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@patrickmurphy_53381/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[2019 Fullstack Web Dev For Idiots (like me): Part 0 — Mental Roadblocks and Dev Environment]]></title>
            <link>https://medium.com/@patrickmurphy_53381/2019-fullstack-web-dev-for-idiots-like-me-part-0-mental-roadblocks-and-dev-environment-d9a8ce0adfac?source=rss-830bf45bfe19------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9a8ce0adfac</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[node-for-begginners]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[visual-studio-code]]></category>
            <dc:creator><![CDATA[Patrick Murphy]]></dc:creator>
            <pubDate>Thu, 29 Nov 2018 00:41:16 GMT</pubDate>
            <atom:updated>2018-11-29T00:41:16.786Z</atom:updated>
            <content:encoded><![CDATA[<h3>2019 Fullstack Web Dev For Idiots (like me): Part 0 — Mental Roadblocks and Dev Environment</h3><h4>Overview:</h4><p>I wrote this post to help people out who are just getting started with development, but can’t get past setting up all the tools that they need, and might not even understand what those tools are or what they do. All of that is covered in the second section of the post, so feel free to skip ahead to that if that’s what’s most useful to you.</p><p>The first part of this post is speaking more to the mental roadblocks of getting started, and I’ve tried to address what I’ve seen as both my own stumbling blocks and the observed trepidations of others. That said, I’ve also tried to encapsulate and lay out the best advice and practices I’ve had the opportunity to receive or observe from devs that I respect a lot. Maybe not for everyone, but hopefully useful and in solidarity with some.</p><h4><strong>Philosophy:</strong></h4><ol><li><strong>Javascript, and why you should:</strong></li></ol><p>In the words of Frank Herbert, “fear is the mind killer”. Doubly true when it comes to teach yourself how to code in the current age, quadruply true if you suffer from a classic case of<strong> </strong><a href="https://en.wikipedia.org/wiki/Impostor_syndrome"><strong>imposter syndrome</strong></a> (super common in the programming world) or are still just wet behind the ears in the HTML/CSS world and have no idea where to even go from there.</p><p>No matter what you do, there’s going to be a ton of depth if you want there to be. Want to be a badass designer/developer and actually understand CSS-grids, gpu-accelerated animations, be a SASS master, etc? You can definitely do that, and there’s nothing wrong with that. However, whereas 10 years ago that would have provided some decent job security, my firm belief is that unless you’re already established in a some sort of marketing/creative dev shop doing already doing this work, the ability to be a straight up frontend designer has passed you by.</p><p>Yes, there will be a continuing demand for custom Wordpress/Hubspot/Drupal sites, etc., but my prediction is that Wix/Squarespace/et al, and machine learning are going to kill the vast majority of the static site development industry. Knowing HTML/CSS and a content management system used to be enough to build a career on. Though still viable, investing in that stack will only provide diminishing returns moving forward.</p><p>All that is to say: <strong>Javascript</strong>. Learn it. Don’t be afraid of it. Dive in with both feet. It has become an amazingly versatile language, and it’s ecosystem grows by the day. Pick a frontend js framework and get going. Don’t wait around until you “feel more comfortable” with HTML and CSS, because a) You’ll still learn a ton about those fundamentals when building an app, and b) JS, or JS frameworks, imo, should now be considered one of those fundamentals. If you want to become a web developer, or even a software engineer, but have pretty much no experience, build your fundamentals in a language that can be used both on the backend and the frontend (thank you Node.js), and then use that context to learn other languages. Don’t spread yourself thin trying to do everything at once, because you don’t have to. And most importantly, don’t be scared. Fear is the mind killer.</p><p><strong>2) I get it, and so do a lot of other people:</strong></p><p>When we talk about fear, we’re talking about that hesitation to just get started, that indecisiveness driven by the massive overload of information and options, that discrete fear that because you can’t understand it now, you won’t understand it ever. Real talk, so many of us feel this fear.</p><p>Truth is, everything that drives that fear never really disappears. There will always be an unknown. There will always be something you’ll struggle with. There will always be the lingering feeling that you’re not doing enough, fast enough. The only thing that changes is how you choose to react to it. As Greg Lemond, a 3-time Tour de France winner famously said: “It never gets easier, you just go faster.” I propose a reworking of this adage to: “It never gets easier, you just start doing it faster”.</p><p>Because doing it faster, or not waiting to get in under the hood and dirty your hands, seems to be the foremost attribute of the senior engineers I have the most respect for. Sure, their lifetime knowledge base helps check all the little boxes, but when faced with something new, they don’t waste time, <em>they just get in and do it.</em> The sooner you break something, the sooner you have a thread to pull to start figuring things out.</p><p>In summation, embrace the fear, and let overcoming it become what drives you. If you, as I often do, feel like the dumbest person in the room, conquering that fear and proving to yourself that you actually <em>can</em> do it becomes an incredibly powerful and motivating validation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEPYrlmqvZJxcK8ZpDQkWg.jpeg" /><figcaption>tl;dr</figcaption></figure><h4>Dev Environment:</h4><p>The impetus for this tutorial series came from working with a group of individuals from non-technical parts of my current company who wanted to level-up their careers and learn how to code, either to enhance their current roles, or to eventually make the jump to an engineering position.</p><p>That said, working with a varied group of people who are just getting started has empirically shown 2 things. 1) The number of dev dependencies people need to get up an running can be intimidating at first, and 2) a vast amount of the tutorial/stack overflow threads/blog posts/etc. assume the dev will have a bash environment. This is generally fine when someone has a Mac, but can present an additional roadblock when Windows users are trying to get started. With that in mind, the first thing any <strong>Windows </strong>user should do is get a bash terminal emulator. My personal favorite is <a href="http://cmder.net/"><strong>Cmder</strong></a>. Cmder will help standardize a lot of the reference information you’re going to find. (Also, re: the command line. Learn it. Love it. Live it. You’ll feel like <a href="https://en.wikipedia.org/wiki/Hackers_(film)"><strong>this</strong></a> in no time).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNrVZGO9hEOHHTbyt7jnag.png" /><figcaption>If’n yer on a Windows box.</figcaption></figure><p><strong>Text Editor:</strong></p><p>A lot of resources may say to use your editor flavor of choice. For standardization (and awesomeness), I say <a href="https://code.visualstudio.com/"><strong>VS Code</strong></a><strong>. </strong>It’s the best thing out there that’s not an IDE right now imo, and it gets a ton of support from Microsoft and the community. Integrated terminal is pretty tops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RFMh6fUG2KER3yI5uOW2Rw.png" /></figure><p><strong>Git:</strong></p><p>Get <a href="https://git-scm.com/"><strong>git</strong></a>. Git is a version control system. If this is greek to you, just understand the basic usage is for teams to be able to work on the same piece of code together. The usual process is to create a repo (file repository), most often on <a href="https://github.com/"><strong>Github</strong></a><strong> </strong>(please note git and github are not the same…), and then have team members clone that repository on their local machines and push/pull updates to that shared codebase. Usually, if one person is working on a different feature from everyone else, they’ll create their own branch from the master repository, work on their changes on that branched copy of the code, and then test to make sure it works with everyone else’s code before pulling it back into the shared repo. Here’s an example of how to use git from the command line (although there are visual interfaces for doing this, you’ll really learn best by using the cli tool):</p><pre>git clone <a href="http://www.github.com/exampleuser/example">www.github.com/exampleuser/example</a>-repo<br>cd example-repo<br>git checkout -b my-own-branch<br>/* do some work in the branch */<br>git add .<br>git commit -m &quot;this is a commit, and I&#39;m going to leave a message here about the work I have done&quot;<br>git push origin -u my-own-branch</pre><p>Here’s the flow of what’s going on above:</p><ol><li>We’re cloning (copying) a version of the remote repository (from github, in this instance) to our local machine.</li><li>We’re cd’ing (changing directories) into the directory we just cloned</li><li>We’re creating a local branch off of the repository we’ve cloned.</li><li>Do some work in the branch. Change a file’s contents, create a new file, delete a file, etc.</li><li>add all of our changes so that they’re tracked by git</li><li>commit all the files we’ve added so we can push them up. Git versioning works around the idea of commits. Each commit will get a unique commit id, and if we really screw up our code (or someone else’s), we can use the commit id to revert back to the un-screwed code like this git reset --hard uniqueC0m1tId (there are some caveats here, so check out <a href="https://stackoverflow.com/questions/4114095/how-to-revert-a-git-repository-to-a-previous-commit"><strong>this</strong></a> rad stack-overflow post for further reading). Commits must have commit messages -m, btw (good practice to make these messages descriptive of the work that’s new to the commit).</li><li>Now that we’ve committed our code locally , we’re going to push upstream to the remote branch. The first time we push up a branch we’ve created locally, we’ll use the -u flag for -upstream. (upstream/downstream, is the same as remote/ local ).</li><li>All further pushes to the branch can be done with git push origin my-own-branch .</li><li>Eventually, after all the work for our particular feature is done, we’ll want to merge our my-own-branch branch back into the remote master branch that we originally cloned, so everyone else that’s working on the codebase can git pull origin master and get all the updated work you’ve done.</li><li>Git can be <strong><em>confusing af. </em></strong>Don’t worry if it doesn’t all make sense at first. Just focus on the basics of clone, checkout, add, commit, push to start. You <em>will</em> run into the opportunity to learn more about git, I guarantee it.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*azvj1TbthkWVOVXyGns8PQ.png" /><figcaption>essential</figcaption></figure><p><strong>Node.js:</strong></p><p>Node is a beautiful thing, in my humble opinion. Still a bit of the redheaded stepchild of the backend world at the enterprise level (although that is changing, <a href="https://www.monterail.com/blog/nodejs-development-enterprises">https://www.monterail.com/blog/nodejs-development-enterprises</a>), Node allows developers to code their backend server and api logic in the same language they use in the frontend: Javascript.</p><p>If we look at the traditional front-end developer learning path, it usually goes like this: learn some HTML and super basic CSS. Now learn some more advanced CSS. Now learn some Javascript, maybe for simple animations, show/hide | expand/collapse functionality, etc. Now learn more advanced JS to dynamically generate some markup, fetch data with api calls, creating tracking objects in browser, etc. And, for a long time, that was about as far as you could go with JS, because you were constrained to using it in the browser. If you wanted to build a backend, you had to go learn php or python or .NET or Java or any of the myriad other languages that allowed for server side coding.</p><p>Now, frontend web dev, though requiring it’s own expertise and definitely not without its challenges, seems to have gotten a bit of a rep for being the “softer” side of programming. But, that’s precisely why it’s a great medium for getting into coding. At the outset, it can provide tangible early results (“Look, I got something to show up on the screen!”, “Look, I made the background blue!”, “Look, I made a little animation!”, and so-on and so-forth), and by the time one really starts digging into Javascript, they’ll already be learning the fundamentals of “real” programming: loops, conditionals, operators, etc.</p><p>So, if HTML/CSS/JS in the browser are the gateway drug, Node is the pure stuff right off the boat. The first time you write your own proxy api to bypass CORS restrictions can be intoxicating. And, if you stick at it, just like you learned those programming fundamentals with browser-side JS, you’ll learn the backend fundamentals like the HTTP protocol, RESTful services, authentication, MVC, etc., etc., etc. Node terraforms what you can do with your JS knowledge, and it’s a sublime thing to connect the full pipeline in the same language.</p><p>All that said, go get Node <a href="https://nodejs.org/en/"><strong>here</strong></a>. Once you’ve installed, you should be able to access it from the terminal by running node -v . If it returns a version number, then you know Node is installed and that the executable has been added to your system path. Usually this just works on Mac, but Windows users might benefit from <a href="https://thisdavej.com/install-upgrade-node-js-windows-easy-way/"><strong>this</strong></a> article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bN9-HmVGs462elQUCm42hg.png" /><figcaption>Your/the future</figcaption></figure><p><strong>Conclusion:</strong></p><p>And with that, you <em>should</em> have everything you need to <strong><em>get started. </em></strong>You could literally do anything at this point. However, I highly suggest you get started by learning React.js. And then build a backend for your React app with Express.js. And then mess around with hosted infrastructure on Amazon Web Services to deploy your app.</p><p>If the above sounds pretty 0–60, don’t worry, it is. That said, check out my upcoming posts about each one of those focus areas, and by the end of everything, you should <strong>a)</strong> have a little functioning web app that acts as your own portfolio (no note-taking app here), and <strong>b)</strong> have learned a whole ton of a lot, hopefully in a way that prepares you well to go out and create some awesome stuff at will. Stay tuned for links to those posts in the near future, and please leave a comment with any pain points you run into getting your dev environment set up, and I’ll work to keep this post updated with solutions to the edge cases. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9a8ce0adfac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing Heroku Toolbelt on Amazon Linux AMI]]></title>
            <link>https://medium.com/@patrickmurphy_53381/installing-heroku-toolbelt-on-amazon-linux-ami-ad0670333cf1?source=rss-830bf45bfe19------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad0670333cf1</guid>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[amazon-ec2]]></category>
            <dc:creator><![CDATA[Patrick Murphy]]></dc:creator>
            <pubDate>Fri, 23 Feb 2018 19:23:37 GMT</pubDate>
            <atom:updated>2018-02-23T19:23:37.295Z</atom:updated>
            <content:encoded><![CDATA[<p>This took a few hours of Googling and a few different sources to piece everything together, so though it might be worth a short write-up for some other like-minded individuals.</p><p>First off, follow the Standalone Installation guide here: <a href="https://devcenter.heroku.com/articles/heroku-cli">https://devcenter.heroku.com/articles/heroku-cli</a></p><p>Don’t forget to swap out REPLACE_ME_OS with linux and REPLACE_ME_ARCH with x86 , or whatever architecture your instance AMI is (You can find this by selecting the EC2 instance you’re interested in in the AWS console and then checking the AMI ID field below).</p><p>Also, pop open the tarball with vi before unzipping and copy-pasta the first line, as you’ll need to replace the heroku-cli-v6.x.x-darwin-64 in the mv command with whatever version is listed (other ways to do this obviously, but was quick + easy).</p><p>After you’ve followed the rest of the steps, you’ll also need to run the following before the toolbelt will actually run with the heroku command :</p><ul><li>yum -y install glibc.i686</li><li>sudo yum install libstdc++64.i686</li></ul><p>If heroku login still throws errors, try yum search libstdc++ , and then iterate through the list of available packages, using your best judgement as to which one will solve the error you’re seeing.</p><p>Hopefully though the toolbelt should be up and running, and entering your credentials with heroku login should have you on your way!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad0670333cf1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[First-time Dev: Building a Fullstack JS App for Salesforce with OAuth login, jsForce, React-Redux…]]></title>
            <link>https://medium.com/netscape/first-time-dev-building-a-fullstack-js-app-for-salesforce-with-oauth-login-jsforce-react-redux-ca5962fb7fe3?source=rss-830bf45bfe19------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca5962fb7fe3</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[jsforce]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Patrick Murphy]]></dc:creator>
            <pubDate>Sun, 08 Oct 2017 23:43:21 GMT</pubDate>
            <atom:updated>2018-04-05T14:22:06.710Z</atom:updated>
            <content:encoded><![CDATA[<h3>First-time Dev: Building a Fullstack JS App for Salesforce with OAuth login, jsForce, React-Redux, and Express</h3><h4>In the Beginning</h4><p>A few caveats, and some backstory: This is my first fullstack web app, so it may not offer the cleanest codebase, but 1) it works! and 2) bundles together a number of pieces I was able to find, understand, and combine in incremental steps. The hope is that there are other people out there looking to divorce from the Salesforce UX, but still use SF as a backend, but are either unable to gain developer access for their org or are more comfortable programming in an external environment and don’t want to go through the hassle of having to learn/use the Lightning/Apex systems and the Force.com dev environment, and that this writeup will help them get a working proof-of-concept set up in a reasonable amount of time.</p><p>Final caveat, this is also the first time I’ve built something using a full javascript environment, utilizing Node/Express on the backend and React/Redux for the client. Not that this should scare you off, as again 1) it works!, but 2) I hope that this writeup will be better for my naïveté, as a large part of the challenge I faced getting a working product off the ground was sifting through the technical jargon to understand what I actually needed to use, and 3) I hope by keeping it basic and covering the dev process soup-to-nuts, that anyone using this as a resource will be able to minimize the number of time-sucking tangents needed to get this off the ground, no matter their skill level. So, in part, this will post will be a hybrid of my dev story and code-writeup/tutorial.</p><p>Finally, finally, some backstory. I work for a medium sized company that was purchased by a larger company, which in turn was purchased by a company that’s near the top of the Forbes “America’s Largest Private Companies” list, all within a 2-year timeframe. I started on the ground floor in a support role for our suite of SaaS products, right as my company was transferring from an old but efficient home-grown CRM to the upstream org of Salesforce that our parent companies were on. Suddenly all departments in our company were switching from using a bespoke tool that provided only the information needed to get the job done for a certain role to a mashup SF dashboard that at once had too much information and then again not enough. Furthermore, a substantial portion of needed daily functionality was still locked into our old CRM, in regards to interacting with our proprietary software products, and was impossible to port to SF. That meant that for almost every team, a daily need arose to be in two systems at once. Thus, the problem posed: would it be it possible to create another customized CRM that could interact with SF to keep our parent orgs happy, but would provide the info/functionality we needed to gain efficiencies and avoid the double-dipping at our child company?</p><p>When I started in mid-summer, I had some prior experience as a front end developer/designer intern at a marketing company, and I knew about/was interested in Node development and learning a front end templating library (I ended up going with React as it does seem to be the current social climber). I also knew I wanted to move away from pure front-end work and towards a web engineering position at my current company. Solution posed: learn enough of the JS stack and SF API to build a proof-of-concept for an SF integrated CRM for our org, help the company out, learn a lot, and see how far I could get.</p><p>3 months later, this is what I’ve got.</p><p>(Also, a public repo of this project can be found here: <a href="https://github.com/mmurph23/salesforce-dashboard">https://github.com/mmurph23/salesforce-dashboard</a>)</p><h4>Step 1: Where the F*** do I start</h4><p>First challenge — how do I talk to Salesforce? Salesforce has a number of open API’s, but there are also a number of libraries that help standardize talking to SF. I ended up going with <a href="https://jsforce.github.io/">https://jsforce.github.io/</a>, as it appears to be well supported and the most robust of the options out there. In order to use any of these connection libraries, however, a “connected app” needs to be initiated in Salesforce.</p><p>If you do not have access to your orgs Salesforce Account, you can start by creating a “Developer Edition” account. Once you’ve walked through the setup process, or once you have developer permissions for your org, then search for “app” in the setup console, and select “app” in the Build section under the Create dropdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yvEBxxwXGlIxV294ntih2g.png" /><figcaption>Classic version of SF Developer account</figcaption></figure><p>Once you’re in, then click on “new” under the Connected App section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YSe1uOqE4Fzpm8sXYVqY-Q.png" /></figure><p>Fill out the required information as needed, but make sure to set “http://localhost:3030/token” as the callback URL, and select the “Enable OAuth Settings” option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEEdeekwGKmFU0N8ox7kSA.png" /></figure><p>Once you’ve clicked save, you’ll be redirected to an overview page with your Client Secret and ID. Copy these numbers into a notepad as you’ll need them to create a connection from your Express backend to your SF Connected App.</p><h4><strong>Step 2: Set up your Express backend API</strong></h4><p><strong>A) Node/NPM:</strong> With your Connected App setup, it’s time to start the heavy lifting. As Express is an abstraction on top of Node.js designed to make the implementation of a web application’s server framework easier to get started with, you’ll have to have Node.js installed. If you don’t, go to <a href="https://nodejs.org/en/">https://nodejs.org/en/</a> and follow their installation and setup instructions. Node also comes with a package manager, NPM, which makes it easy to install the libraries you’ll need for your application. Once configured, open up a command line window, and type npm -v. If a number comes back, ex. 6.1.11, that means you’ve got Node installed, and that number is the version that’s installed. (As an aside, this is assuming you’re running a bash command line. If you don’t have a Mac or Linux machine, this won’t be standard, so I recommend this bash emulator, <a href="http://cmder.net/">http://cmder.net/</a>, for Windows machines). If you don’t get anything back, you’ll need to do some system path configuration to get Node/NPM set up, and there are a number of YouTube walkthroughs out there for that already. This is the one piece of overhead that’s abstracted enough away from what we’re doing that I’m not going to do a write-up for it.</p><p><strong>B) Express.js: </strong>Once Node and NPM are installed/configured, create a new folder to hold your projects in. I usually keep this folders on the desktop, and to get into the folder from the command line the usual path from bootup would be cd desktop/name-of-folder…</p><p>Once in the folder, run npm install express-generator -g (docs for this tool here <a href="https://expressjs.com/en/starter/generator.html">https://expressjs.com/en/starter/generator.html</a>). When the packages have finished installing, in the command line type express name-of-project and hit enter. The generator tool will then scaffold out an app structure for you in a new “name-of-project” folder. When it’s finished, cd (or “change directory”) into the new project folder and run npm install. This command will install all the dependencies specified in the package.json file that was created by express-generator. Now we’re ready to get started configuring the backend!</p><p>The first file we want to focus on is “app.js” in the root directory. Open the whole project folder up in your editor of choice and then open up “app.js”. The top of the file should look a bit like this:</p><pre>var express = require(&#39;express&#39;);<br>var path = require(&#39;path&#39;);<br>var favicon = require(&#39;serve-favicon&#39;);<br>var logger = require(&#39;morgan&#39;);<br>var cookieParser = require(&#39;cookie-parser&#39;);<br>var bodyParser = require(&#39;body-parser&#39;);</pre><pre>var index = require(&#39;./routes/index&#39;);<br>var users = require(&#39;./routes/users&#39;);</pre><pre>var app = express();</pre><pre>// view engine setup<br>app.set(&#39;views&#39;, path.join(__dirname, &#39;views&#39;));<br>app.set(&#39;view engine&#39;, &#39;jade&#39;);</pre><p>If you’ve never used Node/Express before, this part should still be pretty easy to understand. The variables we are setting are instantiating some of the libraries we installed in our package.json dependency list inside of our app so that we can use them. Once we’re created a variable our app can use, then we can do things with those libraries. Ex., telling our app to use Express is done by the following lines of code:</p><pre>var express = require(&#39;express&#39;);</pre><pre>...</pre><pre>var app = express();</pre><p>In the first line we instantiate express as a variable we can access in our app, and then in the second line we run the default express function and assign it to the “app” variable.</p><p>Now, there are some things that express-generator creates for us that we’re actually not going to use, and there is also at least 3 packages that we’ll have to add ourselves.</p><p>First, let’s get those packages installed with NPM. Making sure that you’re still in your project folder in your terminal, type npm install --save express-session request jsforce to install all three packages at once. The --save flag will automatically add these to your package.json dependency list. Once they’re installed, reconfigure the top of your “app.js” file to look like this.</p><pre>const httpClient = require(&#39;request&#39;);<br>const express = require(&#39;express&#39;);<br>const jsforce = require(&#39;jsforce&#39;);<br>const path = require(&#39;path&#39;);<br>const session = require(&#39;express-session&#39;);<br>const bodyParser = require(&#39;body-parser&#39;);</pre><pre>// Setup HTTP server<br>const app = express();</pre><pre>//initialize session<br>app.use(session({secret: &#39;S3CRE7&#39;, resave: true, saveUninitialized: true}));</pre><pre>//bodyParser<br>app.use(bodyParser.json())<br>app.use(bodyParser.urlencoded({ extended: true }))</pre><p>Of note here are the app.use(session…) and app.use(bodyParser…) lines.</p><p>As you may have guessed, app.use is simply telling our app function to utilize certain other functions from certain other packages. The “session” usage allows us to create sessions for an instance of our application run. In this case, every time we connect to Salesforce, we will want to create a session object where we can save some connection variables that Salesforce returns to us after we log in from our app. The “secret”, “resave”, and “saveUnitialized” parameters that we declare are just configuration params for each unique session. You can read more about these at the express-session documentation here, <a href="https://github.com/expressjs/session">https://github.com/expressjs/session</a>.</p><p>Using “body-parser” allows us to correctly parse out the body of requests sent to our Express app. The http protocols define very specific ways information can be sent from one domain to another (more info here: <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers">https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers</a>), and when we eventually start passing “requests” from our React/Redux client to our backend Express app with some information we’ve collected from a user, we’ll need to ensure that our Express app can correctly receive the “body” on those request headers (the “body” is where a data payload is stored for passing on a request header. More on that when we cover it in the React/Redux section). In this case, we’ll be sending our data over in a JSON format, and app.use(bodyParser.json()) simply grabs the part of the body-parser library that works with parsing out JSON and tells our app to use it to read our payload.</p><p>Finally, make sure that at the bottom of server.js we include this line:</p><pre>module.exports = app;</pre><p>This should be the final line in the file, and allows us to export the app and all the methods/parameters we’ve defined for it to other files. On that note, let’s take a quick look at how we call our server.js file in another file and how we start our server from the command line.</p><p>First up is the package.json file that express-generator made for us, which should look something like this:</p><pre>{<br>  &quot;name&quot;: &quot;my-app&quot;,<br>  &quot;version&quot;: &quot;0.0.0&quot;,<br>  &quot;private&quot;: true,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node ./bin/www&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;body-parser&quot;: &quot;1.17.2&quot;,<br>    &quot;cookie-parser&quot;: &quot;1.4.3&quot;,<br>    &quot;debug&quot;: &quot;~2.6.3&quot;,<br>    &quot;express&quot;: &quot;4.15.4&quot;,<br>    &quot;express-session&quot;: &quot;1.15.5&quot;,<br>    &quot;jsforce&quot;: &quot;1.8.0&quot;,<br>    &quot;request&quot;: &quot;2.81.0&quot;<br>  }<br>}</pre><p>What we’re interested in is the “scripts” section, and the “start” command. Having defined “start”, if we are in the folder in the command line, we can type “npm start” and our app will run node ./bin/www, which will tells our Node.js runtime engine to look at the “www” file in the “bin” folder that the generator also created for us and use the parameters in that file to instantiate a web server to serve up our routes. Clicking into “bin/www”, we will see something like this:</p><pre>/**<br> * Module dependencies.<br> */</pre><pre>var app = require(&#39;../app&#39;);<br>var debug = require(&#39;debug&#39;)(&#39;test-project:server&#39;);<br>var http = require(&#39;http&#39;);</pre><pre>/**<br> * Get port from environment and store in Express.<br> */</pre><pre>var port = normalizePort(process.env.PORT || &#39;3000&#39;);<br>app.set(&#39;port&#39;, port);</pre><pre>/**<br> * Create HTTP server.<br> */</pre><pre>var server = http.createServer(app);</pre><p>Let’s tweak two lines. First, because we’ve changed the name of our server file and put it inside the server folder, the app delcaration should now read:</p><pre>var app = require(&#39;../server/server&#39;);</pre><p>and we’ll also change the port from the default 3000 to 3030. Now the top of the file should look like this:</p><pre>#!/usr/bin/env node</pre><pre>/**<br> * Module dependencies.<br> */</pre><pre>var app = require(&#39;../server/server&#39;);<br>/*var debug = require(&#39;debug&#39;)(&#39;dev-edition:server&#39;);*/<br>var http = require(&#39;http&#39;);</pre><pre>/**<br> * Get port from environment and store in Express.<br> */</pre><pre>var port = normalizePort(process.env.PORT || &#39;3030&#39;);<br>app.set(&#39;port&#39;, port);</pre><pre>/**<br> * Create HTTP server.<br> */</pre><pre>var server = http.createServer(app);</pre><p>Also note that I’ve commented out the debug include as the module was throwing an error I haven’t yet had the time to work around. It may or may not work for you, but if you get an error and see debug mentioned in the stack trace, this might be a workaround.</p><p>Now, if we go back to the command line and type “npm start” our server should boot without error. However, we haven’t defined any routes yet, so although you shouldn’t get a 404 when you navigate to <a href="http://localhost:3030/,">http://localhost:3030/</a> , you should get a “cannot GET” message, as the “/” and it’s contents need to be declared specifically.</p><p><strong>C) jsForce:</strong> jsForce provides us with a number pre-built options for connecting to Salesforce, and I’ve chose to use the OAuth2 method. At this point, I haven’t addressed session serialization from the app, and I’m not going to cover that here, as I’ll be undertaking a refactor in the coming weeks and will do another writeup then. For now, if you’ve required jsForce at the top of server.js, then you can instantiate a new OAuth connection with the loginUrl, clientSecret, and clientId that you declared or were assigned when you set up your Connected App in Salesforce. Plug those variables in to the codeblock below.</p><pre>//jsForce connection<br>const oauth2 = new jsforce.OAuth2({<br>    // you can change loginUrl to connect to sandbox or prerelease env.<br>    loginUrl : &#39;<a href="https://bspoke-dev-ed.my.salesforce.com&/#39;">https://your-unique-dev-url.my.salesforce.com&#39;</a>,<br>    //clientId and Secret will be provided when you create a new connected app in your SF developer account<br>    clientId : &#39;example id&#39;<br>    clientSecret : &#39;example secret&#39;,<br>    //redirectUri : &#39;<a href="http://localhost:&#39;">http://localhost:&#39;</a> + port +&#39;/token&#39;<br>    redirectUri : &#39;<a href="http://localhost:3030/token&#39;">http://localhost:3030/token&#39;</a><br>});</pre><p>Next, we’ll create our first Express route to handle redirecting a user to the Salesforce login page.</p><pre>app.get(&quot;/auth/login&quot;, function(req, res) {<br>  // Redirect to Salesforce login/authorization page<br>  res.redirect(oauth2.getAuthorizationUrl({scope: &#39;api id web refresh_token&#39;}));<br>});</pre><p>Again, we take the main app function, and apply an Express method to it. In this case, it’s a “get” route, which is part of the HTTP standard for RESTful web services (more on that here: <a href="http://www.restapitutorial.com/lessons/httpmethods.html">http://www.restapitutorial.com/lessons/httpmethods.html</a>). For this walkthrough, we’ll be covering two types of routes, “get” and “post”, and they’re pretty much exactly what they sound like. “Get” routes handle fetching data, and “post” routes handle passing, or posting, data. Both methods can return data, but only post can handle passing a data payload via the request header.</p><p>Breaking down the route params, we have the actual url endpoint, “/auth/login” in this case, and a callback function that has two parameters, req and res, or request and response. With this route defined, when we boot up our server and go to <a href="http://localhost:3030/auth/login,">http://localhost:3030/auth/login,</a> the response from that route will be to redirect us to the Salesforce login page with the oauth2 object we’ve defined. However, as we have not created the callback route we defined in our Salesforce Connected App (‘/token’), after you enter your SF credentials, the connection will time out because Salesforce will be looking for a route that doesn’t exist. So, let’s set that route up now. Again, it’s another “get” route with a callback function that has req and res parameters. It should look like this:</p><pre>app.get(&#39;/token&#39;, function(req, res) {</pre><pre>const conn = new jsforce.Connection({oauth2: oauth2});<br>    const code = req.query.code;<br>    conn.authorize(code, function(err, userInfo) {<br>        if (err) { return console.error(&quot;This error is in the auth callback: &quot; + err); }</pre><pre>console.log(&#39;Access Token: &#39; + conn.accessToken);<br>        console.log(&#39;Instance URL: &#39; + conn.instanceUrl);<br>        console.log(&#39;refreshToken: &#39; + conn.refreshToken);<br>        console.log(&#39;User ID: &#39; + userInfo.id);<br>        console.log(&#39;Org ID: &#39; + userInfo.organizationId);</pre><pre>        req.session.accessToken = conn.accessToken;<br>        req.session.instanceUrl = conn.instanceUrl;<br>        req.session.refreshToken = conn.refreshToken;<br></pre><pre>var string = encodeURIComponent(&#39;true&#39;);<br>       /* res.redirect(&#39;<a href="http://localhost:3000/?valid=&#39;">http://localhost:3000/?valid=&#39;</a> + string);<br>    });*/</pre><pre>});</pre><p>(we’ve commented out /* res.redirect(‘<a href="http://localhost:3000/?valid=&#39;">http://localhost:3000/?valid=&#39;</a> + string);<br> });*/ for the time being so that we don’t get an error when manually hitting the /auth/login route in the browser. We’ll need to uncomment this once we get our client app set up)</p><p>This is the meat of our SF connection, so let’s take some time to sift through it.</p><p>First, we initialize a new instance of our SF connection in our route using the same oauth2 object we defined at the top of server.js</p><p>Second, we parse out the code that Salesforce sent back to the /token url when it returned us from the login. Until we uncomment the response redirect at the bottom of the route, once you’ve logged in and been redirected to the token route, you should see something like ‘http://localhost:3030/token?query=longhashedoutstringxyz’. That long hashed out string is the value of the request query from Salseforce, and is our “handshake” to pass back to SF when we run conn.authorize(code, function(…){}). If we pass that code back to SF with the authorize function, SF will return some connection information that we will store as session variables to use every time we make a new handshake with SF for the calls from each route. To ensure those connection details are coming through, I’m logging out the details, and then setting them to session variables using the “session” constant we defined at the top of our file here:</p><pre>        req.session.accessToken = conn.accessToken;<br>        req.session.instanceUrl = conn.instanceUrl;<br>        req.session.refreshToken = conn.refreshToken;</pre><p>Et voilà, we have what we need to be redirected to Salesforce, log in, and then be redirected back to our app with details about our SF connection. Now, let’s write a test route to send a dummied up query over to Salesforce and get a list of accounts, like so:</p><pre>app.get(&#39;/api/accounts&#39;, function(req, res) {</pre><pre>// if auth has not been set, redirect to index<br>    if (!req.session.accessToken || !req.session.instanceUrl) { res.redirect(&#39;/&#39;); }</pre><pre>//SOQL query<br>    let q = &#39;SELECT id, name FROM account LIMIT 10&#39;;</pre><pre>//instantiate connection<br>    let conn = new jsforce.Connection({<br>        oauth2 : {oauth2},<br>        accessToken: req.session.accessToken,<br>        instanceUrl: req.session.instanceUrl<br>   });</pre><pre>//set records array<br>    let records = [];<br>    let query = conn.query(q)<br>       .on(&quot;record&quot;, function(record) {<br>         records.push(record);<br>       })<br>       .on(&quot;end&quot;, function() {<br>         console.log(&quot;total in database : &quot; + query.totalSize);<br>         console.log(&quot;total fetched : &quot; + query.totalFetched);<br>         res.json(records);<br>       })<br>       .on(&quot;error&quot;, function(err) {<br>         console.error(err);<br>       })<br>       .run({ autoFetch : true, maxFetch : 4000 });<br>});</pre><p>Again, the usual business with defining the route and the callback function, but this time we’re going to check that our session has a stored access token and instance URL, and throw an error if not. Assuming everything is good, we’ll define our Salesforce query (Salseforce has it’s own SQL like ‘SOQL’ query language, which you can read about here, <a href="http://www.sfdc99.com/2013/06/05/intro-to-soql-and-why-you-must-learn-it/">http://www.sfdc99.com/2013/06/05/intro-to-soql-and-why-you-must-learn-it/</a>), and assign it to variable ‘q’.</p><p>Then, we define an empty records array to hold the results from our query. This is important, as the jsforce .query() method is a closure, and if we don’t define a variable in our route that can be returned on the ‘res’ parameter, we’ll fetch the records, but won’t be able to send them to our client as a response.</p><p>Finally, we’ll utilize the .query() method from jsForce, and call it on our connection variable ‘conn’, and pass in the query ‘q’ that we’ve defined. Go ahead and save server.js and then run ‘npm start’ on the command line. If the server boots without error, go to the ‘/auth/login’ route in the url bar, step through the login redirect, and then after you’ve been returned to the ‘/token’ route, manually hit the ‘/api/accounts’ route in the URL bar and you should see a returned response of a JSON object with a list of accounts and the account info we requested in our query. Congrats, as you’ve made your first successful API call.</p><h4>Step 3.0 : Create a React/Redux client</h4><p><strong>a) The Redux/React flow:</strong> surprisingly easy once understood, but also can prove surprisingly hard to understand. React is fairly straightforward, and there are ton of great free resources to get you started. This (<a href="http://andrewhfarmer.com/getting-started-tutorials/">http://andrewhfarmer.com/getting-started-tutorials/</a>) was a pretty valuable blog post that presents a number of options ranging from super introductory to fairly advanced. Although we’ll go in-depth with how our React code works, I recommend one of the above tutorials if you have zero React experience and need to get up to speed. Redux, on the other hand, and how it interacts with your React components, is the part that myself and most other people seem to struggle with at first.</p><p>For me, the first part was understanding how the flow works. Knowing the shape of what I was trying to configure helped me get to the point where I could ask the right StackOverflow questions or generally know where to look in example code if I felt I was missing something. The diagram below is my attempt at a visualization of the data flow in the app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*rDURAWohIFCNhdUS__pwwg.png" /></figure><p>Here a function that’s triggered in React (it could fire when a button is clicked or when a component renders, for instance) will “dispatch” an “action” in Redux. “Dispatch” and “action” are terms related to Redux, so it’s important to understand what they mean, and what they do. A redux “action” is a function that has an object that you’ve defined inside of it. The below is an example of an action:</p><pre>//In ES6<br>const reduxAction = (passedParmeter) =&gt; ({type: REDUX_ACTION, payload: passedParameter});</pre><pre>//In vanilla JS<br>var reduxAction = function(passedParameter) {<br>     var object = {<br>                    type: REDUX_ACTION,<br>                    payload: passedParmeter<br>                  }<br>     return object;<br>}</pre><p>The function “reduxAction” accepts a passed-in parameter, and then appends that passed-in param as a value to the “payload” key in the object that it returns. The only purpose of the reduxAction function is to return the object inside of it. And in Redux, the objects these action functions return will always only have two fields, a “type” and a “payload”. Now that we’ve defined this action, we can “dispatch” it to our Redux reducer using the Redux library’s dispatch() function. Our “reducer” function is the default export from our redux file, and accepts the object that the “action” returns and updates our state based on the type defined in the payload, like so:</p><pre>export default (state = [], action) =&gt; {</pre><pre>switch (action.type) {<br>    case REDUX_ACTION:<br>      return {...state, passedParameter: action.payload}<br>    default:<br>      return state;<br>  }<br>};</pre><p>Let’s say that before the “reduxAction” function is called, our state doesn’t have a “passedParameter” field, it’s just an empty object, {}. Once the action has been dispatched to the reducer function like so:</p><pre>dispatch(reduxAction(&#39;passed string&#39;));</pre><p>The reducer function will look at the object reduxAction is passing to it, see that the payload value is “REDUX_ACTION”, and then updated (or create, in this case), the passedParameter filed in our state object. Now our state object looks like this —{passedParameter: &#39;passed string&#39;} .</p><p>Breaking it down a bit more, the reducer function expects an action, and it will used a switch statement to do something based on the “type” field of the action object (action.type ). Based on the type, it will return a copy of the current state (... is the javascript “spread” operator, which “spreads” all of the object fields out and makes a copy of them, and then returns a new version of the copied object, in this case, the “state” object) with whatever is passed in on the action.payload . If the we assign a payload to a field in the state object that doesn’t exist, the returned copy will have a new field with the payload value. If the field does exist, the value will be updated in the returned copy.</p><p>One big thing to understand here is that whatever updates we make to the state object are being done on brand new copies of the previous state. This allows for an “immutable” state object, meaning the state we passed in to our spread operator is not changed, but the copy that the spread operator returns is. This blog post does a great job of explaining why this is important: <a href="https://www.toptal.com/javascript/immutability-in-javascript-using-redux">https://www.toptal.com/javascript/immutability-in-javascript-using-redux</a>.</p><p><strong>B) The Redux/Express flow:</strong></p><p>Because our source of data for the React app, or the “state”, is controlled/managed by our Redux actions, any external data we interact with (the information we get from Salesforce in this case), will need to pass through Redux before being available in our React app. Let’s consider our reduxAction function. The function is expecting a passedParameter param. If that passed param is coming from an external source, the flow would look something like this.</p><pre>//reducer action<br>const reduxAction = (passedParmeter) =&gt; ({type: REDUX_ACTION, payload: passedParameter});</pre><pre>//dispatcher function<br>const dispatchReduxAction = () =&gt; {<br>    return (dispatch) {<br>       fetch(&#39;https://www.express-api.com/data&#39;)<br>         .then(res =&gt; res.json())<br>         .then(res =&gt; dispatch(reduxAction(res)))      <br>    } <br>}</pre><p>The dispatchReduxAction function doesn’t take any parameters, but it does return the results of a fetch call to an external data source and then dispatches the redux action with the result of our fetch call passed in as the (passedParameter) that reduxAction is expecting. If you want to read more about the Fetch API and how it works, including the functions it replaces, scotch.io has a great writeup here: <a href="https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data">https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data</a>. What’s important to know is that it at a minimum takes a URL parameter and returns as a result the response from the requested resource. It utilizes promises (again, scotch.io with a great explanation <a href="https://scotch.io/tutorials/javascript-promises-for-dummies">https://scotch.io/tutorials/javascript-promises-for-dummies</a>), which means you can chain it to other functions so that then can utilize the result of the fetch call. In longform, you can think of .then() as meaning “once this is done, <strong><em>then</em></strong> do this with the result.” Line by line, we fetch the data with fetch(&#39;https://www.express-api.com/data&#39;) , then we convert our result to JSON with .then(res =&gt; res.json()) , then we pass that result to reduxAction and dispatch the action with .then(res =&gt; dispatch(reduxAction(res))) . Simple, straightforward, and the code describes fairly clearly what we are doing.</p><h4>3.1: Creating our Client:</h4><p>Now that we’ve covered the flow, let’s actually create a React client to utilize our backend. In your express project root folder, npm install --save create-react-app . Create-react-app is an awesome package that bootstraps a pretty robust config for us to get started with React using a development server with hot-reloading, and sets up our bundler, Webpack, for us, among other things. Long story short, it abstracts away a lot of the roadblocks to setting up your first (or any) React application, and allows us to jump right into the coding. Once the package has installed, run create-react-app client and c-r-a will initialize a new React project in a folder called client. For the sake of making it easier to get everything set up when it’s actually time to build our app for production, I’m creating the client folder inside of the existing express app, and you should now see it in with the other primary folders. Cd into the client folder and lets take a look.</p><p><strong>a) setting a proxy route: </strong>Because our backend and frontend are both running in development environments on localhost, we will need to set up a proxy for our calls to our Express app so that our React client will think that any fetch requests it makes are actually to it’s own server, which allows us to get around the cross-domain errors our app will throw if we don’t configure a proxy. In your text editor, go ahead and open up the client folder’s package.json file. We’ll want to add a proxy route here like so:</p><pre>{<br>  &quot;name&quot;: &quot;client&quot;,<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;private&quot;: true,<br>  &quot;dependencies&quot;: {<br>    &quot;react&quot;: &quot;^15.6.1&quot;,<br>    ...<br>  },<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;react-scripts start&quot;,<br>    ...<br>  },<br>  &quot;proxy&quot;: {<br>    &quot;/auth/login&quot;: {<br>      &quot;target&quot;: &quot;<a href="http://localhost:3030/">http://localhost:3030</a>&quot;<br>    },<br>    &quot;/api/accounts&quot;: {<br>      &quot;target&quot;: &quot;<a href="http://localhost:3030/">http://localhost:3030</a>&quot;<br>    }<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;redux-devtools-extension&quot;: &quot;^2.13.2&quot;<br>  }<br>}</pre><p>Notice that the two proxy routes we’ve defined for /auth/login and /api/accounts have a target of <a href="http://localhost:3030/">http://localhost:3030</a> . As we configured it in our bin/www file, our Express backend is running on localhost:3030. Create-react-app defaults our client development server to localhost:3000. Now, when we make a fetch request like fetch(&#39;/auth/login) , our client app thinks that we’re directing it to another one of it’s own routes, and doesn’t freak out when we get redirected to the Salesforce login by our Express app because it thinks some external resource is trying to hijack what our browser is doing. As a rule of thumb, every time I create a new route in Express, the first thing I do after that is go and declare a proxy route for it in the client.</p><p><strong>b) Fetching data from our backend: </strong>now that we’ve defined a proxy, we can actually reach out and touch our backend from the client. As we mentioned in our flow discussion above, it will be Redux, not react that makes this connection. So, let’s get started building our first Redux reducer file. In your text editor, make a new folder called “reducers” and two files inside that called “index.js” and “reducer.js”. Open up “reducer.js” and create an action, a dispatch function, and a default reducer function to handle the action type, like so:</p><pre>//Action creator<br>const INITIAL_STATE = &quot;INITIAL_STATE&quot;;</pre><pre>//Reducer Action<br>export const loadAccounts = (accounts) =&gt; ({type: INITIAL_STATE, payload: accounts})</pre><pre>//dispatch loadAccounts<br>export const dispatchFetchAccounts = () =&gt; {<br>     return (dispatch) =&gt; {<br>          return fetch(&#39;/api/accounts&#39;, {credentials: &quot;include&quot;})<br>          .then(res =&gt; res.json())<br>          .then(accounts =&gt; dispatch(loadAccounts(accounts)))<br>     }<br>}</pre><pre>//Reducer<br>export default (state = [], action) =&gt; {</pre><pre>switch (action.type) {<br>    case INITIAL_STATE:<br>      return {...state, accounts: action.payload}<br>    default:<br>      return state;<br>  }<br>};</pre><p>To break up the logic a bit and make it cleaner, we can split out our fetch call into it’s own function, getAccounts and then call it in our dispatchFetchAccounts function:</p><pre>//Action creator<br>const INITIAL_STATE = &quot;INITIAL_STATE&quot;;</pre><pre>//Reducer Action<br>export const loadAccounts = (accounts) =&gt; ({type: INITIAL_STATE, payload: accounts})</pre><pre>//helper function</pre><pre>export const getAccounts = () =&gt; {<br>     return fetch(&#39;/api/accounts&#39;, {credentials: &quot;include&quot;})<br>               .then(res =&gt; res.json())<br>}</pre><pre><br>//Action dispatcher</pre><pre>export const dispatchFetchAccounts = () =&gt; {<br>     return (dispatch) =&gt; {<br>          getAccounts()<br>          .then(accounts =&gt; dispatch(loadAccounts(accounts)))<br>     }<br>}</pre><pre>//Reducer<br>export default (state = [], action) =&gt; {</pre><pre>switch (action.type) {<br>    case INITIAL_STATE:<br>      return {...state, accounts: action.payload}<br>    default:<br>      return state;<br>  }<br>};</pre><p>Finally, so that we can trigger the login route from our client, let’s export another function to handle our redirection to Salesforce:</p><pre>export const login = () =&gt; {<br>          window.location = &#39;/auth/login&#39;;<br>     return (dispatch) =&gt; {<br>          loggedIn()<br>     }<br>}</pre><p>We could write this function directly in our React component, but in the interest of keeping all our logic in one place, let’s put it in our Reducer file for now. So, our final reducer.js file should look something like this:</p><pre>//Action creator<br>const INITIAL_STATE = &quot;INITIAL_STATE&quot;;</pre><pre>//Reducer Action<br>export const loadAccounts = (accounts) =&gt; ({type: INITIAL_STATE, payload: accounts})</pre><pre>//helper functions</pre><pre>export const getAccounts = () =&gt; {<br>     return fetch(&#39;/api/accounts&#39;, {credentials: &quot;include&quot;})<br>               .then(res =&gt; res.json())<br>}</pre><pre>export const login = () =&gt; {<br>          window.location = &#39;/auth/login&#39;;<br>}</pre><pre>//Action dispatcher</pre><pre>export const dispatchFetchAccounts = () =&gt; {<br>     return (dispatch) =&gt; {<br>          getAccounts()<br>          .then(accounts =&gt; dispatch(loadAccounts(accounts)))<br>     }<br>}</pre><pre>//Reducer<br>export default (state = [], action) =&gt; {</pre><pre>switch (action.type) {<br>    case INITIAL_STATE:<br>      return {...state, accounts: action.payload}<br>    default:<br>      return state;<br>  }<br>};</pre><p>Now we have functions to set up to communicate with our backend. The next step is to pass these functions in to our React components so that we can use them from our client.</p><p><strong>C) Creating our Redux store:</strong></p><p>Redux works around the idea of a state “store” that combines all the pieces of state that our reducers handle (for now, we have only one reducer, but we could have many depending on the size and needs of our app). So, we need to define our store, and then expose that store to our React app. On the Redux side, we’ll do this by creating another file inside our “reducers” folder and call it “index.js”. Here are the contents of reducers/index.js:</p><pre>import reducer from &#39;./reducer&#39;;</pre><pre>import {combineReducers} from &#39;redux&#39;;</pre><pre>const rootReducer = combineReducers({<br>  reducer<br>});</pre><pre>export default rootReducer;</pre><p>Here we are combining all reducers (well, the one that we have for now) using the combineReducers function from Redux. We’ll assign these combined reducers to a rootReducer variable, and that will be the primary export from this file. We’ll also need another few packages to use with our store, so let’s install them first:</p><pre>npm install --save redux-devtools-extension redux-thunk</pre><p>We’ll cover what these packages do in a minute. First, in the root directory of the app, let’s create a file called “store.js”. In this file we will pull in our combined rootReducer and use that to configure the redux store we’ll pass to our React app.js file. The contents of store.js will look like this:</p><pre>import rootReducer from &#39;./reducers/index&#39;;<br>import {createStore, applyMiddleware, compose } from &#39;redux&#39;;<br>import { composeWithDevTools } from &#39;redux-devtools-extension&#39;;<br>import thunk from &#39;redux-thunk&#39;;</pre><pre>const enhancers = composeWithDevTools(applyMiddleware(thunk));</pre><pre>export default (initialState) =&gt; {<br>  return createStore(<br>    rootReducer,<br>    initialState,<br>    enhancers<br>  );<br>};</pre><p>Let’s look at the default export from this file:</p><pre>import {createStore, applyMiddleware, compose } from &#39;redux&#39;;</pre><pre>...</pre><pre>export default (initialState) =&gt; {<br>  return createStore(<br>    rootReducer,<br>    initialState,<br>    enhancers<br>  );<br>};</pre><p>This unnamed function takes as an argument an initialState , which is exactly what it sounds like, the initial state of our store. If we had pre-defined state values that we wanted to start our app with, we could pass in an object with those values here. The function returns a Redux store by using the createStore function from Redux, the root reducer we’ve imported from reducers/index.js, the initial state we pass in, and any enhancers for the store. It’s important to understand what the enhancers that we’re using do, so let’s take a closer look:</p><pre>import {createStore, applyMiddleware, compose } from &#39;redux&#39;;</pre><pre>...</pre><pre>import { composeWithDevTools } from &#39;redux-devtools-extension&#39;;<br>import thunk from &#39;redux-thunk&#39;;</pre><pre>const enhancers = composeWithDevTools(applyMiddleware(thunk));</pre><p>These are the libraries we installed a few minutes ago, and we’ll go over what they do now. We’re going to use the composeWithDevTools function from the redux-devtools-extension package, and thunk from redux-thunk . Assigning both to the enhancers variable, we utilize the composeWithDevTools to applyMiddleware and pass the thunk middleware to our store. That’s a lot to take in, so let’s try to understand what each one does. First composeWithDevTools allows us to use a set of Redux dev-tools in our browser tools (we’ll have to download this extension in our browser, but we won’t be able to use it without the dev-tools package in our app). This function will wrap up any other middleware, or non-included base functionality, that we’re declaring with Redux’s applyMiddleware function, so that our dev tools can be exposed to all of Redux’s middleware. Finally, the middleware we’re applying, thunk allows us to export functions from our reducers, as well as Redux actions. Without it, we’d have to manually dispatch actions from our React components, instead of defining our dispatch functions in the reducer file and exporting them.</p><p><strong>D) Wiring up our React App to the Redux Store:</strong></p><p>Create-react-app scaffolds out a baseline app for us. Without any configuration, we can cd in our client directory, run npm start and a super basic app will open on localhost:3000. We can see the code for this in our src/app.js file, but the app itself is being passed to our index.html file in src/index.js . Let’s go ahead an open up index.js in our text editor and edit it to look like this:</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import {Provider} from &#39;react-redux&#39;;<br>import App from &#39;./App&#39;;<br>import store from &#39;./store&#39;;</pre><pre>const store = store({});</pre><pre>ReactDOM.render(<br>  &lt;Provider store={store}&gt;<br>       &lt;App /&gt;<br>  &lt;/Provider&gt;,<br>  document.getElementById(&#39;root&#39;)<br>);</pre><p>This also requires that we install the react-redux package, se let’s do that now: npm install --save react-redux . React-redux gives us the &lt;Provider&gt; component, which we will pass our store to. Provider does exactly what it sounds like it does and provides the Redux store we’ve defined to our &lt;App&gt; component, which itself wraps up up all our other components, meaning that we can now access our Redux store from any of our React components. The store we pass in to our provider with &lt;Provider store={store}&gt; is the store we defined in store.js file. Remember that the store takes an initialState , which in this case is {} , an empty object. If you wanted to define some initial state, say booted: true , then you could pass in like so, const store=store({booted:true}) , and every time your app boots up, you’ll have a booted piece of state. You can mess around with passing in other pieces of initial state here if you want to get a better idea of how it works. This is great, now our store is being provided to our app, which means that any state updated from our calls to Salesforce via our Express app will get exposed to our client. However, we need to explicitly tell each of our components which piece or pieces of state we want them to interact with.</p><p><strong>E) Wiring up our React component to individual pieces of state:</strong></p><p>Now that we’ve provided our state to index.js , let’s open up the app.js file that our &lt;Provider&gt; component wraps up, and edit it to look like this:</p><pre>import React, { Component } from &#39;react&#39;;<br>import logo from &#39;./logo.svg&#39;;<br>import &#39;./App.css&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { bindActionCreators } from &#39;redux&#39;</pre><pre>import { dispatchFetchAccounts, login } from &#39;./reducers/reducer.js&#39;;</pre><pre>class App extends Component {<br>  render() {<br>    return (<br>      &lt;div className=&quot;App&quot;&gt;<br>        &lt;header className=&quot;App-header&quot;&gt;<br>          &lt;img src={logo} className=&quot;App-logo&quot; alt=&quot;logo&quot; /&gt;<br>          &lt;h1 className=&quot;App-title&quot;&gt;Welcome to React&lt;/h1&gt;<br>        &lt;/header&gt;<br>        &lt;p className=&quot;App-intro&quot;&gt;<br>          To get started, edit &lt;code&gt;src/App.js&lt;/code&gt; and save to reload.<br>        &lt;/p&gt;</pre><pre>&lt;button onClick={this.props.login}&gt;Login&lt;/button&gt;<br>        &lt;button onClick{this.props.dispatchFetchAccounts}&gt;Get<br>Accounts&lt;/button&gt;<br>       <br>     {this.props.accounts ? &lt;p&gt; this.props.accounts is now available! &lt;/p&gt; : &lt;p&gt; this.props.accounts is not yet available. &lt;/p&gt;}</pre><pre>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>const mapStateToProps = state =&gt; ({<br>  accounts: state.accounts,<br>});</pre><pre>const mapDispatchToProps = dispatch =&gt; bindActionCreators({<br>     login,<br>     dispatchFetchAccounts<br>}, dispatch);</pre><pre>export default connect(<br>     mapStateToProps,<br>     mapDispatchToProps<br>)(App);</pre><p>Ok, so what’s going on here? By this point, we’re assuming you have a basic knowledge of React, and that you understand how we’re defining a new “App” component and providing as the export for our file. You may also notice that we’ve added a few buttons:</p><pre>&lt;button onClick={this.props.login}&gt;Login&lt;/button&gt;<br>        &lt;button onClick{this.props.dispatchFetchAccounts}&gt;Get<br>Accounts&lt;/button&gt;</pre><p>and a ternary operator:</p><pre>{this.props.accounts ? &lt;p&gt; this.props.accounts is now available! &lt;/p&gt; : &lt;p&gt; this.props.accounts is not yet available. &lt;/p&gt;}</pre><p>If you look at your app in the browser, you’ll see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3wN9DeAs1976llE3QCg5g.png" /></figure><p>Starting with the ternary operator, we’re looking at whatever the boolean value the argument on the left side of the question mark evaluates to, true or false, and then if true, we do everything before “:”, and if false, we do everything after “:”. So, because this.props.accounts doesn’t exist yet, we’re displaying the message to the right of “:”. So, how do we get this.props.accounts to evaluate to true?</p><p>Well, that’s what our buttons are for. First, to get any data from Salesforce, we need to login. Let’s go ahead and click on the Login button… and like magic, we’re redirected to the Salesforce login page, and back to our client, with the url parameter of <a href="http://localhost:3000/?valid=&#39;">?valid=</a>true . Now that we’ve logged in, we can click on the Get Accounts button and we’ll see the message change to this.props.accounts is now available! . How does this work? How did we get our functions from our redux store into our component props? We did that by using react-redux and it’s connect method, and using the functions mapStateToProps and mapDispatchToProps to “connect” our App component to pieces of to the Redux store we passed in with the &lt;Provider&gt; component in index.js .</p><p>Let’s take a closer look at mapStateToProps and mapDispatchToProps , as these functions can sometimes be conceptually hard to grasp. Really, all they’re doing is saying to map a piece of the Redux store state or a Redux dispatch action to a prop in your component.</p><pre>const mapStateToProps = state =&gt; ({<br>  accounts: state.accounts,<br>});</pre><pre>const mapDispatchToProps = dispatch =&gt; bindActionCreators({<br>     login,<br>     dispatchFetchAccounts<br>}, dispatch);</pre><p>Above, we say that we want an accounts prop in our component, and we want it to be tied to the accounts piece of state in our store. Understanding that the state parameter mapStateToProps = state =&gt; ({...}) takes in is the state of the Redux store is key here.</p><p>Likewise, mapDispatchToProps maps our dispatch actions (or any functions exported from our Redux store, thanks to thunk) to props we can call from our component. If you want to understand more about the connect function and the parameters it takes, there’s useful writeup here: <a href="https://medium.com/mofed/reduxs-mysterious-connect-function-526efe1122e4">https://medium.com/mofed/reduxs-mysterious-connect-function-526efe1122e4</a>.</p><p>Lastly, we need to pass mapStateToProps and mapDispatchToProps into our connect function, and then actually wrap our App component in the connect function:</p><pre>export default connect(<br>     mapStateToProps,<br>     mapDispatchToProps<br>)(App);</pre><p>And, there you have it. From React to Redux to Express to Salesforce and back. It’s a simple implementation, we’re only grabbing some info from Salesforce, but a more rounded example with create and update functionality can be found here: <a href="https://github.com/mmurph23/sf-connect-dev">https://github.com/mmurph23/sf-connect-dev</a>.</p><h4>After-action:</h4><p>There’s a lot going on here, and there are a lot of things learned over the course of building this app out that suggest a significant refactor is needed (which may manifest a part 2 to this writeup). But, as stated at the beginning, it works, and this writeup is hopefully a complete resource for someone just getting started with React/Redux, or anyone looking to leverage the Salesforce API’s to get away from stock SF UI and functionality. If you have questions, or if something’s not working, please leave a note in the comments. Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca5962fb7fe3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/netscape/first-time-dev-building-a-fullstack-js-app-for-salesforce-with-oauth-login-jsforce-react-redux-ca5962fb7fe3">First-time Dev: Building a Fullstack JS App for Salesforce with OAuth login, jsForce, React-Redux…</a> was originally published in <a href="https://medium.com/netscape">Netscape</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>