<?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 Nicos Tsourektsidis on Medium]]></title>
        <description><![CDATA[Stories by Nicos Tsourektsidis on Medium]]></description>
        <link>https://medium.com/@nicotsou?source=rss-3f36e7f5ac47------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cjen7jNkVHcFsaCZjPDqQg.jpeg</url>
            <title>Stories by Nicos Tsourektsidis on Medium</title>
            <link>https://medium.com/@nicotsou?source=rss-3f36e7f5ac47------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 10:00:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nicotsou/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[TypeScript: The Type Experiment]]></title>
            <link>https://nicotsou.medium.com/typescript-the-type-experiment-dd26232fd2e5?source=rss-3f36e7f5ac47------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd26232fd2e5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Nicos Tsourektsidis]]></dc:creator>
            <pubDate>Fri, 15 Jul 2022 16:48:50 GMT</pubDate>
            <atom:updated>2022-11-24T21:14:20.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="The Type Experiment: Can you spot the JavaScript errors?" src="https://cdn-images-1.medium.com/max/1024/1*qF9DRRAPvE5qW0A6wErVFg.png" /></figure><p>Read the following JavaScript code and try to spot any mistakes:</p><pre>const favorites = {<br>  tracks: [],<br>  totalLength: 0,<br>};</pre><pre>function addToFavorites({ title, artist, album, length }) {<br>  favorites.tracks.add({ title, artist, album, length });<br>  favorites.totalLength = favorites.totalLength + track.length;<br>}</pre><pre>const track = {<br>  title: &#39;Bohemian Rhapsody&#39;,<br>  artists: [&#39;Queen&#39;],<br>  album: &#39;A Night At The Opera&#39;,<br>  length: &#39;5.45m&#39;,<br>};</pre><pre>addToFavorites(track);</pre><p>Some of you may think to copy this snippet and paste it into your browser’s console. I want to save you from this extra effort; this code has zero JavaScript errors. It compiles perfectly!</p><p>Now, without reading the solution below, pause for a minute and try to spot any potential issues.</p><p>The solution follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*sbw5WPuz-LmmcSd4tM3IQA.gif" /></figure><p>No peeking!</p><h3>The Solution</h3><p>Let’s copy that code snippet to our TypeScript file to see what we will get.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*03IxkczfYgfjRE0YTXRm7g.png" /><figcaption>Yup! As expected, we do have a couple of issues in this code…</figcaption></figure><p>This code will not work, but believe it or not, it is perfectly legit in JavaScript. By that I mean that <em>technically</em> we are not violating any of the compiler rules.</p><blockquote><em>Not even </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode"><em>strict mode</em></a><em> can save us here.</em></blockquote><p>Of course, TypeScript inferred the types and quickly identified the errors:</p><ul><li>At line #7, we are using an array method that doesn&#39;t exist. The correct method is push() not add().</li><li>At line #8, we are adding a string &#39;5.45m&#39; to the number 0. Again, this is valid JavaScript code. The JavaScript compiler will automatically coerce the number to a string and the result will be &#39;5.45m&#39;, which is far ahead of what we wanted to achieve here.</li><li>Ultimately, at line #13, we have a typo in the property name artist, which must not be plural.</li></ul><p>Want to watch the explanation in a video?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FD_0KI6SePcA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DD_0KI6SePcA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FD_0KI6SePcA%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/e36bffbbd945f13d2e1998b4c3cd32b4/href">https://medium.com/media/e36bffbbd945f13d2e1998b4c3cd32b4/href</a></iframe><p>It’s part of my ✨ <a href="http://tltr-typescript.com/"><strong>free course for TypeScript</strong></a> ✨. I teach everything I know about the language, with practical examples and a lot of fun! 🤗</p><p>Prefer to reading instead? Check out my full article, in which I explain all these in detail. I also write about my experience learning the language.</p><p>And trust me, I was also late on this as much as you are.</p><p>Happy coding!</p><p>I have much more content in the pipeline for TypeScript.</p><ul><li><strong>🐥 </strong><a href="https://twitter.com/nicotsou"><strong>Follow</strong></a> me on Twitter</li><li><strong>💌 </strong><a href="https://fantastic-crafter-6730.ck.page/88d8f79c35"><strong>Subscribe</strong></a> to my mailing list</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd26232fd2e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WTF is TypeScript?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://nicotsou.medium.com/wtf-is-typescript-9ec7e1b1ec20?source=rss-3f36e7f5ac47------2"><img src="https://cdn-images-1.medium.com/max/1200/1*QVBNhJSCgSOOp37wZWp_MQ.png" width="1200"></a></p><p class="medium-feed-snippet">If you want to get an idea about what TypeScript is and how it could help you, this article is for you, my friend.</p><p class="medium-feed-link"><a href="https://nicotsou.medium.com/wtf-is-typescript-9ec7e1b1ec20?source=rss-3f36e7f5ac47------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://nicotsou.medium.com/wtf-is-typescript-9ec7e1b1ec20?source=rss-3f36e7f5ac47------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ec7e1b1ec20</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Nicos Tsourektsidis]]></dc:creator>
            <pubDate>Sat, 25 Jun 2022 19:24:40 GMT</pubDate>
            <atom:updated>2022-11-24T21:14:41.857Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Learn React By Building A Twitter Clone]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://nicotsou.medium.com/learn-react-twitter-clone-c1589d0f7416?source=rss-3f36e7f5ac47------2"><img src="https://cdn-images-1.medium.com/max/1920/1*n3x26vlK5e5xGvzLGF_Ieg.jpeg" width="1920"></a></p><p class="medium-feed-snippet">My goal with this article is to help you learn React. We will create a small twitter clone. I will guide you how to build your own app&#x2026;</p><p class="medium-feed-link"><a href="https://nicotsou.medium.com/learn-react-twitter-clone-c1589d0f7416?source=rss-3f36e7f5ac47------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://nicotsou.medium.com/learn-react-twitter-clone-c1589d0f7416?source=rss-3f36e7f5ac47------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1589d0f7416</guid>
            <category><![CDATA[js]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Nicos Tsourektsidis]]></dc:creator>
            <pubDate>Sat, 08 May 2021 10:34:36 GMT</pubDate>
            <atom:updated>2021-05-08T10:34:36.716Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Why Did You Become A Software Engineer?]]></title>
            <link>https://nicotsou.medium.com/why-did-you-become-a-software-engineer-fdf46edfe24f?source=rss-3f36e7f5ac47------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdf46edfe24f</guid>
            <category><![CDATA[procrastination]]></category>
            <category><![CDATA[user-interface]]></category>
            <category><![CDATA[motivation]]></category>
            <category><![CDATA[career-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nicos Tsourektsidis]]></dc:creator>
            <pubDate>Wed, 24 Mar 2021 09:28:23 GMT</pubDate>
            <atom:updated>2021-03-24T09:28:23.360Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yct5nV6uR322v0i9jWmqhg.jpeg" /></figure><p>No, seriously now, why did you become a software engineer?</p><p>Was it the beauty of the algorithms? The intelligence of the design patterns? The mysteriously blinking lights in server rooms? The revolution of technology and how it improves our lives? The happiness to see other people react to your creations? The agile manifest? The money they promised you? The feeling you helped the world become a better place? The need to have a job? The dirty hacks you invent to deal with something you don’t know? The fact you will never be without a job? The coffee you drink in your breaks? The dream to become the cockiest boss alive? Was it your mom?</p><p>I published mυ story about <a href="https://nicotsou.com/2021-03-21-why-I-became-a-software-engineer/">Why I Became A Software Engineer</a> to my personal blog, which is a directors-cut version of this article. You can read the full article there <em>or</em> continue reading the short version here.</p><p>I always had an interest about User Interfaces and technology. I spent a lot of years trying to build personal websites and blogs. This drove me to start learning programming and eventually become a software engineer.</p><p>My curiosity helped me spend endless amount of hours. I had to deal with many issues to see my creations going published. This was a natural process.</p><p>In the beginning of my career I took a lot of risks to become a software engineer. I said no to more profitable jobs, against what it was considered safe, in favour of gaining experience. I also had an opinion about design, software architecture and marketing, even before I joined the university.</p><p>In the process, blinded by success and professionalism, I forgot how it was when I started. I was afraid taking chances, I lost my motivation, I was procrastinating things and the bad habits list goes on. I recently discovered how much I missed being a creator. This was the best motivator I had in my life. This was my <em>drive</em> for my personal and professional success.</p><p>What is your story?</p><p>Can you easily tell what your main driver was? Do you think it still drives you today or was there something you lost in the process? Is your job as a programmer how you imagined it would be?</p><p>📖 Read about my story:<br>👉 <a href="https://nicotsou.com/2021-03-21-why-I-became-a-software-engineer/">https://nicotsou.com/2021-03-21-why-I-became-a-software-engineer/</a></p><p><em>Cover Credit: Luca Bravo</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdf46edfe24f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TLTR; Declarative UI]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://nicotsou.medium.com/tltr-declarative-programming-c8cb068fd4d?source=rss-3f36e7f5ac47------2"><img src="https://cdn-images-1.medium.com/max/2600/1*q-boVUhX8bfygFJZrEndCA.jpeg" width="4729"></a></p><p class="medium-feed-snippet">Declarative programming makes your code more concise, easier to read and reason about and reduces side effects.</p><p class="medium-feed-link"><a href="https://nicotsou.medium.com/tltr-declarative-programming-c8cb068fd4d?source=rss-3f36e7f5ac47------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://nicotsou.medium.com/tltr-declarative-programming-c8cb068fd4d?source=rss-3f36e7f5ac47------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8cb068fd4d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-design]]></category>
            <dc:creator><![CDATA[Nicos Tsourektsidis]]></dc:creator>
            <pubDate>Wed, 01 Jul 2020 19:12:23 GMT</pubDate>
            <atom:updated>2023-01-24T07:05:55.930Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[TL;DR Redux]]></title>
            <link>https://nicotsou.medium.com/tltr-redux-e4fc30f87e4a?source=rss-3f36e7f5ac47------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4fc30f87e4a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Nicos Tsourektsidis]]></dc:creator>
            <pubDate>Tue, 10 Oct 2017 18:39:27 GMT</pubDate>
            <atom:updated>2023-01-24T07:05:12.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uGSpbOJUgzM9NNW78IPSAQ.jpeg" /></figure><p>Redux is a tiny Javascript library that manages the state of your application in a more consistent and practical way.</p><blockquote>Think <em>state</em> as a repository in the memory which stores data from a database, an api, the local cache, a UI element in the screen like a form field and more.</blockquote><p>The creator of Redux, <a href="https://medium.com/u/a3a8af6addc1">Dan Abramov</a>, started working on this project while he was preparing <a href="https://www.youtube.com/watch?v=xsSnOQynTHs">his speech for React Europe</a>.</p><p>He wanted to create a predictable state container that supports logging, hot reloading, time traveling and universal apps.</p><p>Redux is a simpler implementation of the <a href="https://facebook.github.io/flux/docs/in-depth-overview.html">Flux</a> pattern, an architecture that Facebook uses for building their web and mobile apps.</p><p>It implements core concepts of functional programming, inspired by <a href="http://elm-lang.org/">Elm</a>.</p><p>It works great with modern libraries and frameworks like <a href="https://github.com/reactjs/react-redux">React</a>, <a href="https://github.com/revue/revue">Vue</a>, <a href="https://github.com/angular-redux/ng-redux">Angular</a> and many more.</p><h3>How It Works</h3><p>We store everything in a plain JavaScript object:</p><pre>{<br>  todos: [{<br>    text: &#39;Eat food&#39;,<br>    completed: true<br>  }, {<br>    text: &#39;Exercise&#39;,<br>    completed: false<br>  }]<br>}</pre><h4>Actions</h4><p>To perform a change we have to dispatch an <em>Action</em>. These are plain JavaScript objects as well:</p><pre>{ type: &#39;ADD_TODO&#39;, text: &#39;Go to swimming pool&#39; }<br>{ type: &#39;TOGGLE_TODO&#39;, index: 1 }</pre><h4>Action Creators</h4><p>Usually we create functions that return these objects. We call them <em>Action Creators</em>:</p><pre>function addTodo(text = &#39;&#39;) {</pre><pre>  return { type: &#39;ADD_TODO&#39;, text }</pre><pre>}</pre><pre>function toggleTodo(index = 0) {</pre><pre>  return { type: &#39;TOGGLE_TODO&#39;, index }</pre><pre>}</pre><h4>Reducers</h4><p>To modify the state we use plain functions. They return the new state according to the dispatched action. We call these functions <em>Reducers</em>:</p><pre>function todos(state = [], action) {<br>  switch (action.type) {<br>    case &#39;ADD_TODO&#39;:<br>      return state.concat([{ text: action.text, completed: false }])<br>    case &#39;TOGGLE_TODO&#39;:<br>      return state.map(<br>        (todo, index) =&gt;<br>          action.index === index<br>            ? { text: todo.text, completed: !todo.completed }<br>            : todo<br>      )<br>    default:<br>      return state<br>  }<br>}</pre><p>As your app grows, the complexity of the state object increases. You can organize it with composable reducers and conbine them to a bigger one:</p><pre>function todoApp(state = {}, action) {<br>  return {<br>    todos: todos(state.todos, action),<br>    files: files(state.files, action),<br>    folders: folders(state.folders, action),<br>    notifications: notifications(state.notifications, action),<br>    filter: filter(state.filter, action),<br>    searchField: searchField(state.searchField, action),<br>    ...<br>  }<br>}</pre><h4>Store</h4><p>To use Redux you have to create a <em>store</em>. This object<em> </em>manages everything for you. We initialize it with our root reducer:</p><pre>import { createStore } from &#39;redux&#39;<br>import todoApp from &#39;./reducers&#39;</pre><pre>// create the store<br>let store = createStore(todoApp)</pre><pre>// read the state object<br>store.getState()</pre><pre>// dispatch actions that eventually modify the state<br>store.dispatch(addTodo(&#39;Learn about actions&#39;))<br>store.dispatch(toggleTodo(0))</pre><p>Finally, the store needs to be subscribed to a listener. Every time we mutate the state it will notify your app:</p><pre>// log state to the console every time it gets updated<br>let unsubscribe = store.subscribe(() =&gt;<br>  console.log(store.getState())<br>)</pre><pre>// stop listening to state updates<br>unsubscribe()</pre><p>This is the complete lifecycle. We follow the same flow for every single change. We describe the behaviour of the app without touching the UI.</p><h3>The Famous Three Principles</h3><p>When you think about Redux you have to think the following:</p><blockquote><strong>Single source of truth:</strong> The state of your whole application is stored in an object tree within a single store.</blockquote><p>There are no multiple stores like other flux libraries. This simplifies testing, debugging. Things like time traveling, universal apps become a reality.</p><blockquote><strong>State is read-only:</strong> The only way to change the state is to emit an action, an object describing what happened.</blockquote><p>No one writes directly to the state. Never! We always use actions. They know how to mutate the state better than us. And we trust them. Always!</p><blockquote><strong>Changes are made with pure functions: </strong>Never mutate the state directly, always return a new object.</blockquote><p>A <a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976"><em>pure function</em></a> is a function where the return value is only determined by its input values, without observable side effects.</p><p>Every reducer should return a new object and not to mutate the existing one. This is a simpler way of having immutable data in your app.</p><h3>How To Use Redux With React</h3><blockquote>Redux works great with libraries like <a href="https://reactjs.org/">React</a>. Every time you have a state mutation, the root component gets the update and re-renders the UI. Pretty simple right?</blockquote><h4>Install 👩‍💻</h4><p>There is a package called react-redux that handles the binding for you:</p><pre>npm install --save react-redux</pre><h4>Provide 🤗</h4><p>First of all you have to use a <em>Provider</em>:</p><pre>import React from &#39;react&#39;<br>import { render } from &#39;react-dom&#39;<br>import { Provider } from &#39;react-redux&#39;<br>import App from &#39;./components/App&#39;<br>import store from &#39;./pathToStore&#39;<br><br>render(<br>  &lt;Provider store={store}&gt;<br>    &lt;App /&gt;<br>  &lt;/Provider&gt;,<br>  document.getElementById(&#39;root&#39;)<br>)</pre><p>It’s a Higher Order Function that uses <a href="https://reactjs.org/docs/context.html">Context</a> to make the store available to every component in the tree. It just makes your store available everywhere.</p><h4>Connect 👪</h4><p>The first step is to decide which component you want to bind with Redux. In React we have <a href="https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0">two kind of components</a>:</p><p><em>Presentational Components</em> describe how things look. They don’t know redux. They use props to read data and to invoke callbacks to update them.</p><p><em>Container Components</em> describe how things work. They just pass the state down using props. They subscribe to Redux.</p><p>Picking where to put the containers in your component tree is similar to the topic <a href="https://reactjs.org/docs/thinking-in-react.html">which components should have state</a>.</p><p>To bind a React component with Redux use the HOF connect():</p><pre>import { connect } from &#39;react-redux&#39;<br>import TodoList from &#39;./TodoList&#39;</pre><pre>const TodoListContainer = connect(<br>  mapStateToProps,<br>  mapDispatchToProps<br>)(TodoList)<br><br>export default TodoListContainer</pre><p>It creates a parent component that does the binding and passes everything as props to the child component.</p><p>It also does performance optimizations so you don’t have to use shouldComponentUpdate() in your React components at all.</p><p>As you can see it accepts two callbacks. Each of them returns an object. Use the first one to map Redux state to props:</p><pre>const mapStateToProps = state =&gt; {<br>  return {<br>    todos: state.todos<br>  }<br>}</pre><p>The second one maps dispatch functions to props as callback functions:</p><pre>const mapDispatchToProps = dispatch =&gt; {<br>  return {<br>    onTodoClick: id =&gt; {<br>      dispatch(toggleTodo(id))<br>    }<br>  }<br>}</pre><p>In our example the component &lt;TodoList&gt; will accept the following props:</p><pre>TodoList.propTypes = {<br>  onTodoClick: PropTypes.func.isRequired,<br>  todos: PropTypes.object.isRequired<br>}</pre><h4>Enjoy 🍾</h4><p>You have succesfully connected your store with your view. Now remember:</p><ol><li>Every time something happens you call an action</li><li>The reducers decide which mutations they have to apply to their state</li><li>Your containers get the updated state and they pass the data down to the presentational components</li></ol><h3>Async Redux</h3><blockquote>Redux is synchronous by default. There are <a href="https://medium.com/@jtbennett/asynchronous-actions-in-redux-8412cf92a26f">multiple ways</a> to add async behaviour.</blockquote><h4>Async Actions</h4><p>Every async behaviour usually has 3 different kinds of actions:</p><ul><li>FETCH_POSTS_REQUEST: The request has began. You may store in your state a flag isFetching and if it’s true to show a loading indicator.</li><li>FETCH_POSTS_SUCCESS: The request has finished successfully. Change the flag isFetching to false, remove the loader and show the posts.</li><li>FETCH_POSTS_FAILURE: The request has failed. Change the flag isFetching to false, store and display the error in the screen.</li></ul><h4>Async Action Creators</h4><p>The simplest implementation is to use <em>thunks. </em>You must install and integrate a <em>middleware</em> called redux-thunk. Here’s how it works:</p><pre>export const REQUEST_POSTS = &#39;REQUEST_POSTS&#39;<br>function requestPosts(subreddit) {<br>  return {<br>    type: REQUEST_POSTS,<br>    subreddit<br>  }<br>}<br><br>export const RECEIVE_POSTS = &#39;RECEIVE_POSTS&#39;<br>function receivePosts(subreddit, json) {<br>  return {<br>    type: RECEIVE_POSTS,<br>    subreddit,<br>    posts: json.data.children.map(child =&gt; child.data),<br>    receivedAt: Date.now()<br>  }<br>}<br><br>// This is a thunk action creator!<br>export function fetchPosts(subreddit) {<br>  return function (dispatch) {</pre><pre>    // dispatch the request<br>    dispatch(requestPosts(subreddit))<br><br>    return fetch(`https://www.reddit.com/r/${subreddit}.json`)<br>      .then(<br>        response =&gt; response.json(),<br>        error =&gt; console.log(&#39;An error occured.&#39;, error)<br>      )<br>      .then(json =&gt;<br>        dispatch(receivePosts(subreddit, json))<br>      )<br>  }<br>}</pre><p>We will dispatch fetchPosts() as before. This will immediately dispatch requestPosts() and then receivePosts() when it will receive the data.</p><h3>Middleware</h3><blockquote><em>Middleware</em> is some code you can put between the framework receiving a request, and the framework generating a response.</blockquote><p>In Redux they provide a third-party extension point between dispatching an action and the moment it reaches the reducer.</p><p>People use Redux middleware for logging, crash reporting, talking to an asynchronous API, routing, and more.</p><p>Here’s how to apply middleware in action:</p><pre>import thunkMiddleware from &#39;redux-thunk&#39;<br>import { createLogger } from &#39;redux-logger&#39;<br>import { createStore, applyMiddleware } from &#39;redux&#39;<br>import { selectSubreddit, fetchPosts } from &#39;./actions&#39;<br>import rootReducer from &#39;./reducers&#39;<br><br>const loggerMiddleware = createLogger()<br><br>const store = createStore(<br>  rootReducer,<br>  applyMiddleware(<br>    thunkMiddleware, // lets us dispatch() functions<br>    loggerMiddleware // neat middleware that logs actions<br>  )<br>)</pre><p>In this example we added a logger that logs each action in the console. We also added redux-thunk, as we described above.</p><h3>DevTools</h3><p>Redux has an outstanding set of <a href="https://github.com/zalmoxisus/redux-devtools-extension">developer tools</a>, which will improve your debugging experience. Extensions are available for <a href="https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd">Chrome</a> and <a href="https://addons.mozilla.org/en-US/firefox/addon/remotedev/">Firefox</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*lAp8ZAk5uNFTuxjhx4GTdw.gif" /><figcaption>Inspect every single action and understand what happened.</figcaption></figure><p>To enable this functionality you should install the package redux-devtools-extension . It’s just another middleware you have to apply to your store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFJdTQCHH60QDDWTJobVRw.gif" /><figcaption>Go back in time and replay every single action.</figcaption></figure><p>Just inspect the page and open the Redux tab. You can replay every action, skip actions, analyze state mutations, or even export automated unit tests!</p><h3>Testing</h3><blockquote>Because most of the Redux code you write are functions, and many of them are pure, they are easy to test without mocking.</blockquote><p>Here’s how to test an action creator using <a href="https://facebook.github.io/jest/">Jest</a>:</p><pre>import * as actions from &#39;../../actions/TodoActions&#39;<br>import * as types from &#39;../../constants/ActionTypes&#39;<br><br>describe(&#39;actions&#39;, () =&gt; {<br>  it(&#39;should create an action to add a todo&#39;, () =&gt; {<br>    const text = &#39;Finish docs&#39;<br>    const expectedAction = {<br>      type: types.ADD_TODO,<br>      text<br>    }<br>    expect(actions.addTodo(text)).toEqual(expectedAction)<br>  })<br>})</pre><p>When it comes to a reducer, you have to test it’s behavior in every single action with two objects, one for before and one after:</p><pre>describe(&#39;todos reducer&#39;, () =&gt; {<br>  it(&#39;should return the initial state&#39;, () =&gt; {<br>    expect(reducer(undefined, {})).toEqual([<br>      {<br>        text: &#39;Use Redux&#39;,<br>        completed: false,<br>        id: 0<br>      }<br>    ])<br>  })<br><br>  it(&#39;should handle ADD_TODO&#39;, () =&gt; {<br>    expect(<br>      reducer([], {<br>        type: types.ADD_TODO,<br>        text: &#39;Run the tests&#39;<br>      })<br>    ).toEqual([<br>      {<br>        text: &#39;Run the tests&#39;,<br>        completed: false,<br>        id: 0<br>      }<br>    ])<br><br>    expect(<br>      reducer(<br>        [<br>          {<br>            text: &#39;Use Redux&#39;,<br>            completed: false,<br>            id: 0<br>          }<br>        ],<br>        {<br>          type: types.ADD_TODO,<br>          text: &#39;Run the tests&#39;<br>        }<br>      )<br>    ).toEqual([<br>      {<br>        text: &#39;Run the tests&#39;,<br>        completed: false,<br>        id: 1<br>      },<br>      {<br>        text: &#39;Use Redux&#39;,<br>        completed: false,<br>        id: 0<br>      }<br>    ])<br>  })<br>})</pre><h3>Tips &amp; Tricks</h3><ul><li>Instead of Object.assign() you can use the <em>spread operator </em>to simplify your reducers:</li></ul><pre>function todoApp(state = initialState, action) {<br>  switch (action.type) {<br>    case SET_VISIBILITY_FILTER:<br>      return { ...state, visibilityFilter: action.filter }<br>    default:<br>      return state<br>  }<br>}</pre><ul><li>Make your apps load faster with <a href="http://redux.js.org/docs/recipes/ServerRendering.html"><em>universal rendering</em></a>.</li><li>Use reselect to <a href="http://redux.js.org/docs/recipes/ComputingDerivedData.html">compute derived data</a>.</li><li>Relational data? Just <a href="http://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html"><em>normalize</em></a> the shape of your state to make your life easier.</li></ul><h3>Resources</h3><ul><li>The official Redux documentation contains many useful articles and practices for Redux and React in general: <a href="http://redux.js.org/">http://redux.js.org</a></li><li>An amazing video series for starters: <a href="https://egghead.io/courses/getting-started-with-redux">https://egghead.io/courses/getting-started-with-redux</a></li><li>The same great video series for advanced Redux concepts: <a href="https://egghead.io/courses/building-react-applications-with-idiomatic-redux">https://egghead.io/courses/building-react-applications-with-idiomatic-redux</a></li></ul><p><em>The goal of this article is to give you a quicker overview of the library. If you decide to use Redux please read the </em><a href="http://redux.js.org/"><em>official documentation</em></a><em>. We used most of the ideas, examples and definitions directly from there. 📖</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4fc30f87e4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>