<?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 Alex Richardson on Medium]]></title>
        <description><![CDATA[Stories by Alex Richardson on Medium]]></description>
        <link>https://medium.com/@acr13?source=rss-4a180d3d9941------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7-2tMDLoINeekQT3.</url>
            <title>Stories by Alex Richardson on Medium</title>
            <link>https://medium.com/@acr13?source=rss-4a180d3d9941------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 09:28:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@acr13/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[Common patterns with Redux-Saga]]></title>
            <link>https://medium.com/universe-engineering/common-patterns-with-redux-saga-ed68f89dfecf?source=rss-4a180d3d9941------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed68f89dfecf</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux-saga]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Alex Richardson]]></dc:creator>
            <pubDate>Thu, 26 Oct 2017 14:46:31 GMT</pubDate>
            <atom:updated>2017-10-26T14:49:50.308Z</atom:updated>
            <content:encoded><![CDATA[<p>In my first blog post on this topic “<a href="https://engineering.universe.com/what-is-redux-saga-c1252fc2f4d1"><em>What is Redux-Saga?</em></a><em>”, </em>I compared the basic differences between <a href="https://github.com/redux-saga/redux-saga">redux-saga</a> and <a href="https://github.com/gaearon/redux-thunk">redux-thunk</a>, two middleware libraries to help manage asynchronous code in our react-redux apps at Universe. If the saga pattern is unfamiliar to you, I recommend checking out the <a href="https://redux-saga.js.org/">redux-saga docs</a> along with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function%2A">ES6 Generators</a>.</p><p>In this post I’m going to outline a few common patterns with redux-saga we use here at Universe on a day-to-day basis. These include:</p><ol><li>Running multiple requests in parallel.</li><li>Using the race keyword to timeout multiple requests gracefully.</li><li>Using sagas to manage a queue of events.</li></ol><h4>Running multiple requests in parallel</h4><p>This is a common pattern we rely on, since most of the data we need from our backend is across multiple endpoints (<a href="https://developers.universe.com/page/graphql-explorer">although we’ve launched a GraphQL beta</a> 😃) and we don’t care which request finishes first.</p><p>Note, this is <strong>different</strong> from the <a href="https://redux-saga.js.org/docs/advanced/RunningTasksInParallel.html">recipe in the docs</a>, which describes waiting for each request to complete before being able to access any of the responses (like Promise.all). The following pattern allows you to start many requests at once, but they are all individual tasks that can finish at any time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/191e0f6c8abc893a9c1ddcb71a5d4c2f/href">https://medium.com/media/191e0f6c8abc893a9c1ddcb71a5d4c2f/href</a></iframe><p>This pattern can be a little bit hard to digest at first glance; lets break it down a bit:</p><ol><li>First we have a watcher (onPageInit) that will fire our saga (fetchDataForPage ) any time the ON_PAGE_MOUNT action type is seen.</li><li>In the fetchDataForPage saga, we first gather any dependencies we need to make our requests (userIds, etc)</li><li>Using redux-saga’s all and fork APIs, we start as many requests as we need in parallel. We pass our reusable requestAndPut side effect function, along with the actual request function we want to call eg: firstRequest, any parameters we need, and finally the action creator we want to call if the request succeeds.</li><li>If any of the requests fail, we can use the catch block for our error handling.</li><li>Else, the action creators will dispatch our success actions, leaving it up to our reducers to handle these and update our store accordingly.</li></ol><p>The magic here is in the requestAndPut helper function. The fork API expects a function to call, along with any parameters you wish to pass to the function. In this case, we always pass in requestAndPut as our function to call, along with a list of parameters, and an action creator. Because these are coupled together, the success actions fire right after our requests finish. They are all independent of one another.</p><h4>Using the race keyword to timeout multiple requests gracefully</h4><p>Continuing in the spirit of our first pattern, sometimes all of those nice parallel requests you just started, might have to get cancelled 😃. Luckily this is quite easy when using redux-saga!</p><p>The docs have a nice <a href="https://redux-saga.js.org/docs/advanced/RacingEffects.html">recipe for cancelling a single request</a> which I highly recommend checking out first. Here is that same recipe augmented slightly to handle multiple requests (using the pattern from above).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c0f2f1d6b52effdc9b1ccb5e877eaa4/href">https://medium.com/media/8c0f2f1d6b52effdc9b1ccb5e877eaa4/href</a></iframe><p>In this example, we are cancelling all of our requests if we receive an action type ( ON_PAGE_CHANGED in this case ) <em>before</em> all of the requests complete. This makes it simple to re-use this pattern elsewhere, as all that really changes is the action type we are listening for when we want to cancel our tasks. This could be as simple as a cancel button being clicked, a tab layout change, or even a set time limit (5 seconds for example).</p><h4>Using sagas to manage a queue (array) of events</h4><p>Here at Universe we show a wide range of notifications to our users depending on the state of the action they are trying to complete. Put simply, we show different success, warning, or error messages in the form of a flash message, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*4D5-H7P-QN52m2Sp--i6Kw.gif" /><figcaption>Sample error &amp; success flash messages</figcaption></figure><p>At first glance this may seem simple (it is!), but we can leverage a lot of utility functions from redux-saga to help make this flow even simpler. This way we stay out of setInterval callbacks which can be tricky to debug at times.</p><p>This is the exact code that runs the flash messages in the GIF above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bea6ebfc66d2f61a46a0ddcfb3bd2cd4/href">https://medium.com/media/bea6ebfc66d2f61a46a0ddcfb3bd2cd4/href</a></iframe><p>This is a saga (onAddFlashMessage) that will be constantly running while our app is in use. It first checks if we have any events in the queue we want to process. If we do, we loop through each event and process it, then we wait until we get a new event in the queue (ADD_FLASH_MESSAGE). Rinse and repeat.</p><p>It’s important to note that this pattern could be used for any queue of events, like network requests, disk operations, etc. All that really has to change is how we want to handle each event (showFlashMessage), and our selector functions we use to get data from our store ( getFlashQueue ).</p><p>Hopefully these three patterns can be of use to you or your team to help manage side effects in redux apps!</p><p>Also, I hope this unlocks different ways of augmenting the recipes in the docs to help solve those harder problems.</p><p><em>You can check out part 1 of the redux-saga series here: </em><a href="https://engineering.universe.com/what-is-redux-saga-c1252fc2f4d1">https://engineering.universe.com/what-is-redux-saga-c1252fc2f4d1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed68f89dfecf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/universe-engineering/common-patterns-with-redux-saga-ed68f89dfecf">Common patterns with Redux-Saga</a> was originally published in <a href="https://medium.com/universe-engineering">Universe Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Redux-Saga?]]></title>
            <link>https://medium.com/universe-engineering/what-is-redux-saga-c1252fc2f4d1?source=rss-4a180d3d9941------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1252fc2f4d1</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[redux-thunk]]></category>
            <category><![CDATA[redux-saga]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-redux]]></category>
            <dc:creator><![CDATA[Alex Richardson]]></dc:creator>
            <pubDate>Tue, 13 Jun 2017 15:43:48 GMT</pubDate>
            <atom:updated>2017-06-13T15:43:48.912Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://redux-saga.js.org/">Redux-saga</a> is a redux middleware library, that is designed to make handling side effects in your redux app nice and simple. It achieves this by leveraging an ES6 feature called <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/function*">Generators</a>, allowing us to write asynchronous code that looks synchronous, and is very easy to test.</p><p>Before we get any deeper, it’s important to note, that the actual term “saga” has a history in the world of computer science, and isn’t strictly limited to the world of JavaScript. If you’re interested in learning more about Sagas, I recommend checking out this amazing talk by Caitie McCaffrey, titled ‘Applying the Saga Pattern’.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FxDuwrtwYHu8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DxDuwrtwYHu8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FxDuwrtwYHu8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cb47e6b85d3a5963b1b834fe5de32ad/href">https://medium.com/media/8cb47e6b85d3a5963b1b834fe5de32ad/href</a></iframe><p>To sum up rather quickly, the Saga pattern is way a to handle long running transactions with side effects or potential failures. For each transaction we wish to complete, we will also need a counter-transaction to revert the original if anything went wrong. Another great resource on this is a blog post by <a href="https://medium.com/u/31daca79e798">Roman Liutikov</a> called <a href="https://medium.com/@roman01la/confusion-about-saga-pattern-bbaac56e622">‘Confusion about Saga pattern’</a>.</p><h3><strong>Why should we use Sagas?</strong></h3><p>Now, when creating a new react-redux app, you’ll generally be guided to use <a href="https://github.com/gaearon/redux-thunk">redux-thunk</a> or <a href="https://github.com/redux-saga/redux-saga">redux-saga</a> to handle asynchronous actions. So why should we use redux-saga?</p><p>Well, straight from the docs:</p><blockquote>“Contrary to redux thunk, you don’t end up in callback hell, you can test your asynchronous flows easily and your actions stay pure.”</blockquote><p>Let’s unpack each of these by comparing a simple example using sagas and thunks. Let’s make an API request to fetch some data on a button click.</p><p>Redux Thunk:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4df0d1fe4e13088feaa8fd6a5e44e5b/href">https://medium.com/media/a4df0d1fe4e13088feaa8fd6a5e44e5b/href</a></iframe><p>Here we have an action creator getDataFromAPI() that would be called from some Button component’s onClick event, which starts our async process:</p><ul><li>First we fire an action letting our store know that we are about to make an API request ( dispatch(getDataStarted() )</li><li>Next we actually make the API request, which returns a promise.</li><li>Then we fire a success action along with our API response or an error action with an error response if anything went wrong.</li></ul><p>Redux Saga:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0433e0b128bd875b0185df1afb80a6f0/href">https://medium.com/media/0433e0b128bd875b0185df1afb80a6f0/href</a></iframe><p>The exact same process, but the code looks a little bit different.</p><ul><li>Instead of calling dispatch in our thunk example, we now call put (we can think of these as equivalent).</li><li>We have a ‘watcher’ function that listens to our ‘start’ action. This assumes a Button’s onClick handler would fire a simple redux action with a type API_BUTTON_CLICK</li><li>We use redux-saga’s call effect, which is a way to get data from any async function (promise, different saga, etc)</li></ul><p>Fairly simple, right? On some button click, we’re going to make an API request to some endpoint. If it succeeds we dispatch a new action with our payload. Otherwise we dispatch an error action with an error message.</p><p>Right away, it should be noted how much easier it is to read and to understand the saga example. That’s not to say the thunk example is hard to understand, but we can get rid of a few intricacies like returning a function and dealing with a promise chain. Instead we can simply write a try/catch block to catch any errors involved with our network request, and to put (or dispatch) an action to notify our reducers.</p><p>Secondly, and arguably most importantly, our Saga side effect function is now <em>pure</em>. This is because the call(getDataFromAPI) doesn’t actually execute the API request, it returns a pure object that looks like this:{ type: &#39;CALL&#39;, func, args } The actual fetch execution is taken care of by the redux-saga middleware, and will return the value back into our generator (hence the yield keyword) or throw an error if there was one.</p><p>This is a pretty powerful concept, as we can now test our saga functions with ease. A test for the above snippet would look something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5376081f9d9da949036e13a98d3a9520/href">https://medium.com/media/5376081f9d9da949036e13a98d3a9520/href</a></iframe><p>Whereas testing the thunk snippet above gets a little trickier. We would have to mock the actual getDataFromAPI call, and any other functions we call inside the thunk. This may not seem like big task, but as our actions grow in complexity, our tests surely will too, which is best to be avoided.</p><p>Hopefully this illustrated the three main points of redux-saga to be a little bit clearer. We don’t end up in callback-hell, we keep our actions pure, and our asynchronous flows are easy to test. To learn more, I recommend to check out these resources:</p><ul><li><a href="https://medium.freecodecamp.com/async-operations-using-redux-saga-2ba02ae077b3">Async operations using redux-saga</a></li><li><a href="https://riad.blog/2015/12/28/redux-nowadays-from-actions-creators-to-sagas/">Redux-Nowadays: From actions creators to sagas</a></li><li><a href="http://konkle.us/master-complex-redux-workflows-with-sagas/">Master Complex Redux Workflows with Sagas</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1252fc2f4d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/universe-engineering/what-is-redux-saga-c1252fc2f4d1">What is Redux-Saga?</a> was originally published in <a href="https://medium.com/universe-engineering">Universe Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>