<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pierre Carion on Medium]]></title>
        <description><![CDATA[Stories by Pierre Carion on Medium]]></description>
        <link>https://medium.com/@pcarion?source=rss-ab26558952f4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*9JbNmQGm-T9Gud1X.jpg</url>
            <title>Stories by Pierre Carion on Medium</title>
            <link>https://medium.com/@pcarion?source=rss-ab26558952f4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 02:44:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pcarion/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[A consul, a vault and a docker walk into a bar.]]></title>
            <link>https://medium.com/@pcarion/a-consul-a-vault-and-a-docker-walk-into-a-bar-d5a5bf897a87?source=rss-ab26558952f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5a5bf897a87</guid>
            <category><![CDATA[vault]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[consul]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Pierre Carion]]></dc:creator>
            <pubDate>Sun, 30 Apr 2017 01:41:19 GMT</pubDate>
            <atom:updated>2017-04-30T01:41:19.692Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQA3HEj48B381t2QvBK6UA.jpeg" /></figure><p>When you develop a non trivial application, you often need to split it in multiple components. I will try to avoid the term micro-service to avoid any religious war here, but, at the bare minimum, you often need to access a database, reach some external services or may be access some cloud based services, like S3, to store files.</p><p>In that kind of scenario, you’re quickly facing 2 boring problems:</p><ul><li>how to access those services. For example, what is the host and port of your mysql database</li><li>where to store your credentials. In the case of Mysql, where do you store your username and password.</li></ul><p>One common way to solve both problems, is to store this information in a configuration file. That works, but:</p><ul><li>that’s not very safe. We all have heard horror stories where password were inadvertently stored in a github repo</li><li>that’s kind of tedious to change URL services when needed or to setup different environments like development, staging and production.</li></ul><p><a href="https://www.hashicorp.com/">Hashicorp</a>, a SF based company, not only has a cool name but on top of that offers two open sourced tools to address that kind of problem:</p><ul><li>consul — <em>Service Discovery and Configuration Made Easy</em></li><li>vault — <em>A Tool for Managing Secrets</em></li></ul><p>To test those tools, you can either run them locally on your machine or, as all the cool kids do these days, you can install them in a docker container.</p><p>I guess I am cool then because I plan to show you how to do just that.</p><p>As a side note, as both consul and vault are written in go, they don’t require any installation procedure per se: those tools come as a single binary file that you only need to put in a directory in your PATH.</p><p>In this article, I will be using <em>docker</em> and <em>docker-compose</em> to setup 3 containers:</p><ul><li><strong>consul.server</strong>: the consul agent</li><li><strong>vault.server</strong>: the value server</li><li><strong>bash.test</strong>: a simple bash container to test the access to consul and vault</li></ul><p>A pre-requisite for this article is that you have a basic knowledge of <em>docker</em> and <em>docker-compose</em>.</p><h3>Consul container</h3><p>Things are easy here as there is already an official docker image for consul in the <a href="https://hub.docker.com/_/consul/">official docker repository</a>.</p><p>The only specific (but non required) configuration I did was to use different external port for consul ion order not to conflict if I was also running a consul container on my host.</p><p>I could have left docker pick for me external ports but it would have then been a little bit less convenient to test: I would have to query docker to get the actual port number being used.</p><p>The docker-compose configuration for consul is:</p><pre>consul:<br>  container_name: consul.server<br>  command: agent -server -bind 0.0.0.0 -client 0.0.0.0 -bootstrap-expect=1<br>  image: consul:latest<br>  volumes:<br>    - ./etc/consul.server/config:/consul/config<br>  ports:<br>    - &quot;9300:9300&quot;<br>    - &quot;9500:9500&quot;<br>    - &quot;9600:9600/udp&quot;</pre><p>The config file that we pass to consul trough a docker volume is config.json and contains:</p><pre>{<br>  &quot;datacenter&quot;: &quot;dc1&quot;,<br>  &quot;log_level&quot;: &quot;DEBUG&quot;,<br>  &quot;server&quot;: true,<br>  &quot;ui&quot; : true,<br>  &quot;ports&quot;: {<br>    &quot;dns&quot;: 9600,<br>    &quot;http&quot;: 9500,<br>    &quot;https&quot;: -1,<br>    &quot;serf_lan&quot;: 9301,<br>    &quot;serf_wan&quot;: 9302,<br>    &quot;server&quot;: 9300<br>  }<br>}</pre><p>If you need more information about those configuration parameters, here are a couple of interesting links:</p><ul><li><a href="https://www.consul.io/">Hashicorp consul website</a></li><li><a href="https://www.consul.io/docs/agent/options.html">Consul agent configuration file</a></li><li><a href="https://docs.docker.com/compose/compose-file/compose-file-v2/">docker compose configuration file</a></li></ul><p>With this setup, the docker server will be available from the host in HTTP using the port 9500.</p><h3>Vault container</h3><p>Vault also has an an official docker image available <a href="https://hub.docker.com/_/vault/">in the official docker repository</a>.</p><p>The docker compose configuration section vault is:</p><pre>vault:<br>  container_name: vault.server<br>  image: vault<br>  ports:<br>    - &quot;9200:8200&quot;<br>  volumes:<br>    - ./etc/vault.server/config:/mnt/vault/config<br>    - ./etc/vault.server/data:/mnt/vault/data<br>    - ./etc/vault.server/logs:/mnt/vault/logs<br>  cap_add:<br>    - IPC_LOCK<br>  environment:<br>    - VAULT_LOCAL_CONFIG={&quot;backend&quot;:{&quot;consul&quot;:{&quot;address&quot;:&quot;${LOCAL_IP}:9500&quot;,&quot;advertise_addr&quot;:&quot;http://${LOCAL_IP}&quot;, &quot;path&quot;:&quot;vault/&quot;}},&quot;listener&quot;:{&quot;tcp&quot;:{&quot;address&quot;:&quot;0.0.0.0:8200&quot;,&quot;tls_disable&quot;:1}}}<br>  command: server</pre><p>I know. The VAULT_LOCAL_CONFIG is a bit messy.</p><p>In a more readable form, this variable would read like that:</p><pre>{<br>  &quot;backend&quot;:{<br>    &quot;consul&quot;:{<br>      &quot;address&quot;:&quot;${LOCAL_IP}:9500&quot;,<br>      &quot;advertise_addr&quot;:&quot;http://${LOCAL_IP}&quot;, <br>      &quot;path&quot;:&quot;vault/&quot;<br>    }<br>  },<br>  &quot;listener&quot;:{<br>    &quot;tcp&quot;:{<br>      &quot;address&quot;:&quot;0.0.0.0:8200&quot;,<br>      &quot;tls_disable&quot;:1<br>    }<br>  }<br>}</pre><p>Better right?</p><ul><li>Vault needs some storage mechanism in order to persist its data in a secure way. You could use the file system, but consul is also an option. We told vault to use consul as a <em>backend</em> here.</li><li>We could have used a file to store this configuration, but as you can see in the value of a 2 variables, we need the IP address of the host machine that we stored in the LOCAL_IP environment variable. We could solve that problem by using a unix socket for consul, or create a shared network, but ‘.. I’ll let you explore that yourself.</li><li>In the docker compose file, we change the external port of vault to be 9200 instead of the standard 8200, to avoid any conflict with a potential vault running locally.</li><li>hint: The LOCAL_IP variable can be set in a .env file in the directory where you start docker-compose. <a href="https://docs.docker.com/compose/env-file/">Just saying</a>.</li></ul><h4><strong>Note</strong>:</h4><p>Based on <a href="https://github.com/hashicorp/vault/issues/107">this github issue</a>, I had to add the advertise_addr parameter to the environment variable, even though this is not really documented.</p><p>Without that variable , I would get this error when starting the vault server:</p><pre>Error detecting redirect address: Get <a href="http://192.168.0.16:9500/v1/agent/self">http://192.168.0.16:9500/v1/agent/self</a>: EOF<br>Error initializing core: missing redirect address</pre><h3>let’s start docker!</h3><p>With those containers, you can start docker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*J4Y7-M1gaa16s_c9hMkptg.png" /><figcaption>docker up!</figcaption></figure><p>You can ignore the bash.test for now.</p><h4>a few docker command</h4><p>There are a few docker commands which are helpful to get an idea of what’s going on.</p><ul><li>docker-compose up — to start the containers described in the docker-compose file</li><li>docker ps — all — to get a list of all your processes</li><li>docker ps — all — format “{{.ID}} {{.Status}}: {{.Names}} {{.Command}} — same information but in a more terse format</li><li>docker logs &lt;name of container&gt; — to see the log of a given container such as:docker logs consul.server</li><li>docker-compose down — to shutdown all the containers</li></ul><p>Both consul and docker containers are based on the alpine container : this is a minimal docker image based on Alpine linux.</p><p>It is so minimal, that there is no bash, but there is a ash shell interpreter that you can connect to in order to explore the container:</p><p>docker exec -it vault.server ash</p><p>There is not much you can really do from that shell, that’s why we created a…</p><h3>bash test container</h3><p>A more convenient way to explore consul and vault is to create a docker container, with a full bash, and preconfigured to access consul and vault.</p><p>To do that, we can write a simple Dockerfile:</p><pre>FROM ubuntu:16.04<br>MAINTAINER Pierre Carion &lt;pcarion@gmail.com&gt;<br>ENV VAULT_VERSION 0.7.0<br>ENV CONSUL_VERSION 0.8.1</pre><pre>RUN apt-get update \<br>  &amp;&amp; apt-get install -y \<br>  build-essential \<br>  git \<br>  curl \<br>  wget \<br>  vim \<br>  net-tools \<br>  iputils-ping \<br>  dnsutils \<br>  zip \<br>  unzip \<br>  &amp;&amp; wget -O /tmp/vault.zip &quot;https://releases.hashicorp.com/vault/${VAULT_VERSION}/vault_${VAULT_VERSION}_linux_amd64.zip&quot; \<br>  &amp;&amp; unzip -d /bin /tmp/vault.zip \<br>  &amp;&amp; chmod 755 /bin/vault \<br>  &amp;&amp; rm /tmp/vault.zip \<br>  &amp;&amp; wget -O /tmp/consul.zip &quot;https://releases.hashicorp.com/consul/${CONSUL_VERSION}/consul_${CONSUL_VERSION}_linux_amd64.zip&quot; \<br>  &amp;&amp; unzip -d /bin /tmp/consul.zip \<br>  &amp;&amp; chmod 755 /bin/consul \<br>  &amp;&amp; rm /tmp/consul.zip \<br>  &amp;&amp; apt-get clean \ <br>  &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><pre>VOLUME &quot;/mnt/data&quot;<br>CMD [&quot;/bin/bash&quot;]</pre><p>Long file, but no rocket science in there:</p><ul><li>install a set of development tools may want to use in that kind of container (compiler, git, network tools)</li><li>we download the consul and vault binary files that we unzip in /bin — we will have to update the VAULT_VERSION and CONSUL_VERSION if a new version of those programs are released. We would then have to rebuild the docker image.</li></ul><p>The command to build the docker image is:</p><p>docker build -t bash.test ./docker_images/bash.test</p><p>The last step is to add this container to our docker-compose.yml file.</p><pre>bash_test:<br>  container_name: bash.test<br>  image: bash.test<br>  environment:<br>    - CONSUL_HTTP_ADDR=${LOCAL_IP}:9500<br>    - VAULT_ADDR=http://${LOCAL_IP}:9200<br>  volumes:<br>    - ./etc/bash.test/data:/mnt/data<br>  command: tail -f /dev/null</pre><p>Pretty straightforward too:</p><ul><li>we define 2 environment variables CONSUL_HTTP_ADDR and VAULT_ADDR used respectively by the CLI `consul` and `vault` to access their associated servers</li><li>we use a dummy command (tail -f) which would block the container and so preventing it from dying.</li></ul><p>Once we restart all our containers with docker-compose, we can then attach a bash to our bash.test container by doing this:</p><p>docker exec -it bash.test bash</p><p>In that shell, you can then verify that you have access to consul and vault:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*E-rjW7cFQ4x7jgSAnG8Jjw.png" /><figcaption>testing access to consul and vault from bash container</figcaption></figure><p>The access to consul seems to be working but the error from vault… is also a good sign.</p><p>When a vault server is just started, it is in an not initialized state as describe in <a href="https://www.vaultproject.io/intro/getting-started/deploy.html">that document</a>.</p><p>The good news is that we now have a bash script to complete that initialization.</p><h3>Initializing and unsealing the Vault</h3><p>The first step is to initializing the vault.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*kTloczIR6IrZna2eHTYVgw.png" /><figcaption>initializing the vault</figcaption></figure><p>This step will give you keys to unseal and the root token to access the vault from a client.</p><p>Time to unseal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*E9S0jPf27tLWMehrCW7wJw.png" /><figcaption>unseal the vault</figcaption></figure><p>Pretty anticlimactic right?</p><p>The only information which should give you joy is: Sealed: false.</p><p>For our test, we will be using the initial root token provided during the vault initialization <strong>BUT</strong> that’s not the proper way to use that token. We’ll see in another article how to properly use tokens in applications.</p><p>In order for the client to work, you can set the token in an environment variable:</p><pre>export VAULT_TOKEN=2ca82ba1-840d-908f-e089-1cd539cb9ace</pre><p>We can now write and read to our new secret store:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*DNPiIqjgdQspF8N6wpOj7A.png" /><figcaption>read and write to the store</figcaption></figure><h3>More to come</h3><p>In this article, we have only explained how to setup consul and vault inside a docker container and verified that the setup was working properly.</p><p>In a real life solution, things have to be automated a little bit more and we’ll see in another article how to manage the tokens and how to access to those private data in a <em>real</em> application.</p><p>Feel free to post comments if you have any questions or email me at pcarion@gmail.com.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5a5bf897a87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux]]></title>
            <link>https://medium.com/@pcarion/redux-1046b0346e7f?source=rss-ab26558952f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1046b0346e7f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Pierre Carion]]></dc:creator>
            <pubDate>Mon, 09 Nov 2015 03:00:18 GMT</pubDate>
            <atom:updated>2015-11-09T03:00:18.675Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nd2oLMHyhwYU1yFAxpmDtA.jpeg" /></figure><p>Redux is a gem inside an incredibly small library.</p><p>Redux creator, <a href="https://twitter.com/dan_abramov">Dan Abramov</a>, was even able to reduce -pun intended- this library to a mere <a href="https://gist.github.com/gaearon/ffd88b0e4f00b22c3159">99 lines</a> of Javascript by removing all the sanity checks.</p><p>I would even argue that Redux is actually one single file — <em>createStore.js</em> — which exposes only 4 functions.</p><p>The other files are sugar on top of Redux: they provide very useful mechanisms to support redux, but they are sugar nonetheless.</p><p>In a recent podcast, Dan Abramov explained that he started to work on Redux because he wanted to go to Paris to attend <a href="https://www.react-europe.org/2015/2015.html">React Europe</a> conference last July.</p><p>Dan wrote Redux as a byproduct to support his talk about <a href="https://www.youtube.com/watch?v=xsSnOQynTHs">Hot reloading and Time travel</a> for React web applications.</p><p>A couple of months later, Dan’s talk is, by far, the <a href="https://www.youtube.com/channel/UCorlLn2oZfgOJ-FUcF2eZ1A/videos?sort=p&amp;flow=grid&amp;view=0">most popular video of React Europe</a> and the Redux project has now more than 8000 stars on on <a href="https://github.com/facebook/react">GitHub</a>.</p><p>Not too shabby for 99 lines of code. Or so.</p><blockquote>Redux may well be one of the first really successful “talk-driven development” project.</blockquote><h4>reducer + flux = redux</h4><p>Even though Redux is independent from React, its inception is still an attempt to simplify the Flux architecture for React applications.</p><p>You can read <a href="https://medium.com/@dan_abramov/the-evolution-of-flux-frameworks-6c16ad26bb31#.1yla952hx">here</a> how Dan explains why he wanted to <em>fix</em> Flux frameworks.</p><p>Redux takes its name from the reducer function which, with the store, is the key component of Redux.</p><h4>Store</h4><p>The state of the application is fully owned by the store and, contrary to most Flux application, a Redux application has only 1 store.</p><p>A store exposes 4 methods:</p><ul><li><strong>getState()<br></strong>To retrieve the current state of the application</li><li><strong>dispatch()</strong><br>To process a new action</li><li><strong>subscribe()</strong><br>To allow components to be notified when the state changes</li><li><strong>replaceReducer()</strong><br>This is an <em>extra</em> method to allow hot reloading of the reducer.</li></ul><p>That’s it. That’s all you really need to know about redux.</p><h4>How to use redux?</h4><p>We’ll start here with the <em>simplest</em> way to use the <em>core</em> Redux API.</p><p>This is in <em>not</em> the proper way to use Redux for a real application but that’s a good way to learn the core concepts of Redux.</p><p>Don’t worry, we will later revisit this code to <em>fix</em> it to make it more production ready.</p><h4>Example application</h4><p>As an example, we will consider an application where we have a counter which can be incremented or decremented.</p><h4>The Store owns the state</h4><p>The central piece or gate keeper in Redux is the store: all the core Redux APIs are applied on the store instance.</p><p>The store holds the entire state of your application and you have to go through the store to access or change the state.</p><p>The function to create the store is:</p><pre>function createStore(reducer, initialState)</pre><p>In our example, the state would hold the counter itself:</p><pre>const initialState  = {<br>  counter: 0<br>}</pre><h4>Action</h4><p>The <a href="https://github.com/rackt/redux/blob/master/docs/basics/Actions.md">definition</a>, of an action is also straightforward:</p><blockquote>Actions are payloads of information that send data from your application to your store. They are the only source of information for the store.</blockquote><p>An action is a plain old Javascript object.</p><p>The only requirement is to have a <em>type</em> property (a String) to describe the nature of the action to perform. The other properties of the action depend on the type.</p><p>For our example, we have 2 types of actions:</p><ul><li>an action to increment the counter</li><li>an action to decrement the counter</li></ul><p>The actions will be like:</p><pre>{<br>  type: &#39;INCREMENT&#39;,<br>  value: 1<br>}</pre><p>and :</p><pre>{<br>  type: &#39;DECREMENT&#39;,<br>  value: 5<br>}</pre><h4>store.dispatch()</h4><p>When something changes in your application:</p><ul><li>you create an action to describe this change and</li><li>you pass this action to the store</li></ul><p>For example :</p><pre>store.dispatch({ type:&#39;INCREMENT&#39; , value: 2});</pre><p>The store will then call the reducer to get a new state.</p><h4>Reducer</h4><p>The reducer function is the most important part of Redux. That’s where the actual processing of your application takes place.</p><p>The prototype of the reducer is:</p><pre>reducer: (previousState, action) =&gt; newState</pre><p>In plain English that gives :</p><blockquote>reducer: A function that returns the next state tree, given the current state tree and the action to handle.</blockquote><p>The crucial part is that the implementation of the reducer has to be a <strong><em>pure</em></strong> <strong><em>function</em></strong> that must follow a very strict mantra:</p><blockquote>Given the same arguments, a reducer should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation.</blockquote><p>To be a pure function, that <a href="https://github.com/rackt/redux/blob/master/docs/basics/Reducers.md#handling-actions">means that</a> :</p><ul><li>a reducer should not mutate the incoming action</li><li>a reducer should not mutate the previous state</li><li>a reducer should not create side effects such as calling an API, logging information, etc…</li><li>a reducer should not call non-<em>pure</em> functions such as <em>Date.now()</em>, <em>Math.random()</em>, etc…</li></ul><p>This is a very strong constraint but this is the main reason why redux is powerful.</p><p>The reasons behind those constraints will become obvious once you use Redux inside a React based web application.</p><p>In our example, the reducer would be:</p><pre>const reducer = function(state, action) {<br> switch(action.type) {<br> case &#39;INCREMENT&#39;:<br>   <strong>return Object.assign</strong>({}, state, {<br>     counter: state.counter + action.value<br>   });<br> break;<br> <br> case &#39;DECREMENT&#39;:<br>   <strong>return Object.assign</strong>({}, state, {<br>     counter: state.counter - action.value<br>   });<br> break;<br> <br><strong> default:<br>   return state;</strong><br> }<br>}</pre><p>The use of <em>Object.assign()</em> to update a counter may seem overkill right?</p><p>A more <em>natural</em> implementation could have been:</p><pre>case &#39;INCREMENT&#39;:<br>  state.counter += action.value;<br>  return state;<br>break;</pre><p>This implementation violates the mantra for 2 reasons:</p><ol><li>the reducer mutates the previous state.</li><li>the reducer doesn’t return a brand new state</li></ol><p>Another very important constraint: you must return the initial state if you can’t process the action (<em>default</em> statement).</p><h4>Don’t. Ever. Mutate. The. State.</h4><p>There are multiple ways to achieve the non mutation of the state using <em>ES6 voodoo incantations</em>:</p><ul><li>you can use <em>Object.assign()</em> like in the example above</li><li>you can also use the ES6 spread operator:</li></ul><pre>return {<br>  ...state,<br>  counter: state.counter + action.value<br>}</pre><p>There are also non ES6 solutions.</p><p>You can use libraries like <a href="https://lodash.com/docs#merge"><em>lodash</em></a> or (<a href="http://underscorejs.org/#extend"><em>underscore</em></a>) and use the <em>merge</em> (or <em>extend</em>) method on an empty object:</p><pre>return _.merge({}, currentState, stateChanges)</pre><p>For the same reasons as mentioned above, don’t ever do:</p><pre>return _.merge(currentState, stateChanges)</pre><p>As you can see, it is tough to ensure the non mutation of the state.</p><p>It requires some muscle memory in your coding style before it becomes natural to write a good reducer method.</p><p>A convenient library can help you in your journey: <a href="https://facebook.github.io/immutable-js/">Immutable.js</a>.</p><h4>Immutable.js</h4><p>The <a href="https://facebook.github.io/immutable-js/">description</a> of the library explains why this library makes sense with Redux:</p><blockquote><a href="http://en.wikipedia.org/wiki/Immutable_object">Immutable</a> data cannot be changed once created, leading to much simpler application development, no defensive copying, and enabling advanced memoization and change detection techniques with simple logic</blockquote><p>The state of the application can be <em>trapped</em> inside an Immutable:</p><pre>const initialState = Immutable.Map({<br>  counter: 0<br>});</pre><p>and our reducer would become:</p><pre>switch(action.type) {<br>  case ‘INCREMENT’:<br>    return state.set(‘counter’, <br>      state.get(‘counter’) + action.value);<br>  break;<br>  case ‘DECREMENT’:<br>    return state.set(‘counter’, <br>      state.get(‘counter’) — action.value);<br>  break;<br>  default:<br>    return state;<br>}</pre><p>The code is a bit verbose. But you minimize the risk of inadvertently changing the current state.</p><p>If you need to get back a plain old Javascript object, you can use the <em>toJS()</em> method.</p><h4>store.subscribe()</h4><p>Finally, some parts of your applications will be interested to know when the state is updated.</p><p>The subscribe method on the store allows you to register a listener:</p><pre>store.subscribe(function() {<br> console.log(‘new state:’ , store.getState());<br>});</pre><p>If you send multiple actions to your state:</p><pre>store.dispatch({ type:’INCREMENT’ , value: 2});<br>store.dispatch({ type:’DECREMENT’ , value: 5});</pre><p>You’ll get notified that the change has changed:</p><pre>➜ babel-node index.js<br>new state: { counter: 2 }<br>new state: { counter: -3 }</pre><p>It may be worth mentioning that the method <em>subscribe()</em> returns a function that you can invoke to cancel the subscription.</p><h3>The end. But not quite.</h3><p>At this stage, all you need to know about the principles of Redux has been said.</p><p>The definition of Redux should now make more sense:</p><blockquote>Redux is a predictable state container for JavaScript apps.</blockquote><p>The <em>predictable</em> nature of Redux is due to the fact that:</p><ol><li>the flow of data is strictly unidirectional</li><li>the <em>pure function</em> nature of the reducer removes any unintended side effects during the processing of the data.</li></ol><p>Another benefit of Redux is that the history of the application can be completely captured by the list of actions received during the life time of the application — that’s the core feature of Redux which allowed Dan to showcase hot reloading and time travel during its presentation in Paris…</p><h3>The “not quite” part</h3><p>As said in the introduction, even though the code above is totally valid … you can’t <em>really</em> use Redux the way it was presented.</p><p>There are some <em>development patterns</em> to add to this foundation to make redux really usable in the context of a real application.</p><p>Those development patterns are exposed in the remaining parts of the Redux API:</p><ul><li>combineReducers,</li><li>bindActionCreators,</li><li>applyMiddleware,</li><li>compose</li></ul><h3>Redux revisited</h3><p>Let’s see how we can improve the code above to make it suitable for a more real application.</p><h4>The need to split the reducer</h4><p>The state of an application tends to grow exponentially with the complexity of the application. So does the list of possible actions.</p><p>It would become quickly unmanageable to have one single reducer to process all the actions.</p><p>Nobody wants a switch statement with hundreds of case statements right?</p><p>The general pattern to fix this, is to shape the state in a way where the different <em>domains</em> of the applications are located in different substates inside the global state, using specific properties.</p><p>For instance :</p><pre>const initialState = {<br>  authentication : {<br>    // the state information about authentication<br>  },<br>  featureA : {<br>    // the state information about the feature A  <br>  },<br>  .../...</pre><p>Redux comes with an API to attach a specific reducer to each substate.</p><h4>combineReducers()</h4><p>The <em>combineReducers()</em> method allows you to split the reducer in multiple function — each of those reducers would apply on a sub-state.</p><p><strong>First attempt (spoiler alert: failed)</strong></p><p>Let’s suppose for our application has 2 counters now.</p><p>The initial state would be:</p><pre>const initialState = {<br> A: {<br>   counter: 0,<br> },<br> B: {<br>   counter: 0,<br> },<br>};</pre><p>The way you would split the reducers is to have an object with 2 methods, whose name match the name of the substate:</p><pre>const funcs = {<br> A(state, action) {<br>   switch (action.type) {<br>     .../... <br>   });<br> },</pre><pre> B(state, action) {<br>   switch (action.type) {<br>     .../... <br>   });<br> },<br>};</pre><pre>const store = createStore(combineReducers(funcs), initialState);</pre><p>This code won’t work :</p><pre>Error: Reducer “A” returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined.</pre><p>This error is related to the management of the initial state.</p><p>This error may seem confusing because we did define an initial state when we created the store.</p><p><strong><em>combineReducers()</em> builds its own default state</strong></p><p>The <em>combineReducers()</em> creates a unique reducer from multiple reducers and during this process guesses the shape of the state based on the name of the methods found in the object passed as a parameter.</p><p>That means that the combineReducers will automatically build the default value of the state for you.</p><p>The value of each substate in the created initial state is … undefined.</p><p>The solution is to define the initial state in the reducers themselves:</p><ul><li>by using a default value for your state parameter (value used when it is undefined eg. at initialization time) or</li><li>by handling the case where the state is undefined</li></ul><p>The first solution gives a more elegant code.</p><p>The code for our reducers would become:</p><pre>const funcs = {<br> A(state = { counter: 0 }, action) {<br>   switch (action.type) {<br>     .../... <br>   });<br> },</pre><pre>B(state = { counter: 10 }, action) {<br>   switch (action.type) {<br>     .../... <br>   });<br> },<br>};</pre><pre>const store = createStore(combineReducers(funcs));</pre><p>From the code above, <em>combineReducers()</em> will infer that the initial state of the application is:</p><pre>{<br> A: {<br>   counter: 0,<br> },<br> B: {<br>   counter: 10,<br> },<br>};</pre><p>To really shine, this pattern require that you refactor a bit your code so that the reducing functions don’t appear inline inside the object.</p><p>You extract your individual reducers as standalone functions:</p><pre>function reduceA(state = { counter: 0 }, action) {<br> switch (action.type) {<br> case ‘INCREMENT_A’:<br>   return Object.assign({}, state, {<br>     counter: state.counter + action.value,<br> });</pre><pre> default:<br>   return state;<br> }<br>}</pre><pre>function reduceB(...)</pre><p>and you finally combine them:</p><pre>const funcs = {<br> A: reduceA,<br> B: reduceB,<br>};</pre><pre>const store = createStore(combineReducers(funcs));</pre><p>If the name of your reducers function match the name of the substates properties, then you could use a shorthand version:</p><pre>const funcs = {<br> reduceA,<br> reduceB,<br>};</pre><p>This would give this state:</p><pre>{ <br>  reduceA: { <br>    counter: 2 <br>  }, <br>  reduceB: { <br>    counter: 10 <br>  } <br>}</pre><p>There is another interesting way to nicely structure your code using combineReducers().</p><p><strong>ES6 modules to the rescue</strong></p><p>The use of ES6 module allows you to clearly separate the reducer methods from the combination step.</p><p>Thats a 3 steps process:</p><p>Step 1: You define each of your reducers in separate files:</p><pre>// in the file <strong>reducerA.js</strong></pre><pre><strong>export default function reducer</strong>(state = { counter: 0 }, action) {<br> switch (action.type) {<br>   case ‘INCREMENT_A’:<br>     return Object.assign({}, state, {<br>       counter: state.counter + action.value,<br>   });</pre><pre>   default:<br>     return state;<br> }<br>}</pre><p>The name of the reducer in this file does not matter : you don’t tie yet this reducer to a substate of your application</p><p>Step 2: you create a file which will import all those reducers in 1 single file and will give associate them to a name there:</p><pre>// in the file <strong>reducers.js</strong></pre><pre>import A from ‘./reducerA’;<br>import B from ‘./reducerB’;</pre><pre>export { A, B };</pre><p>Step 3: the code to combined those reducers becomes dramatically simpler:</p><pre>import * as reducers from ‘./reducers’;<br>const store = createStore(combineReducers(reducers));</pre><p>This pattern nicely splits your code:</p><ul><li>each reducer is in its own file. The name of the reducer doesn’t matter. Easy to unit test.</li><li>The <em>reducers.js</em> file gives a clear view of the layout of the state of your application</li><li>The integration code to create the store is a one liner.</li></ul><blockquote>Side note: even though it is not absolutely required to use ES6 with Redux or React, your code will be much simpler if you do.</blockquote><blockquote>You need to add <a href="https://babeljs.io/">babel</a> and <a href="https://webpack.github.io/">webpack</a> to your tool belt … may seem daunting at first, but definitely worth the effort.</blockquote><h4>Now what?</h4><p>The remaining methods (bindActionCreators, applyMiddleware, compose) are more deeply related to the use of Redux inside a React application:</p><p><strong>bindActionCreator()</strong></p><p>One of the main pattern encouraged by redux is the separation between of <a href="http://rackt.org/redux/docs/basics/UsageWithReact.html">Smart and Dumb components</a>.</p><p>The dumb components should not be aware of Redux.</p><p>Considering that the components are supposed to dispatch the actions that may be a problem as that would require them to know the dispatch method:</p><pre>store.dispatch({ type:’INCREMENT’ , value: 2});</pre><p>The solution to that is the ActionCreator pattern.</p><p>The way you handle actions is that they are defined in their own module where:</p><ul><li>you define constants to hold the value of the type of actions and</li><li>you define ActionCreators functions which create and return actions</li></ul><p>Like that:</p><pre>export const INCREMENT_COUNTER = ‘INCREMENT_COUNTER’;<br>export const DECREMENT_COUNTER = ‘DECREMENT_COUNTER’;</pre><pre>export function increment(value) {<br>  return {<br>    type: INCREMENT_COUNTER,<br>    value: value,<br>  };<br>}</pre><pre>export function decrement(value) {<br>  return {<br>    type: DECREMENT_COUNTER,<br>    value: value,<br>  };<br>}</pre><p>You then collection all those exports in one object:</p><pre>import * as CounterActions from ‘../actions/counter’;</pre><p>The CounterAction will have 2 function properties: increment and decrement.</p><p>The call to:</p><pre>bindActionCreators(CounterActions, dispatch);</pre><p>will wrap all those methods into a dispatch call so they may be invoked without arguments.</p><p>Your react components will be able to invoke those methods while remaining totally unaware of Redux.</p><p><strong>applyMiddleware()</strong></p><p>The fact that reducers must be pure functions with no side effects is OK but what if we do need to perform side effect code?</p><p>Here come Redux Middlewares.</p><p>Middlewares in Redux would deserve their own article. <a href="https://medium.com/@meagle/understanding-87566abcfb7a">And they have</a>.</p><p>A Middleware allows you wrap the calls to the store dispatch function and to chain all those middlewares together.</p><p>With a middleware you can add logging, handle asynchronous API calls, enable hot reloading, etc…</p><p><strong>compose()</strong></p><p>With Redux, we are definitely in functional programming territory.</p><p>This compose() function is a utility function allowing you to compose a chain of single arguments functions.</p><h3>Conclusion</h3><p>That’s a long article to describe such a simple library.</p><p>The next step will be to describe the use of Redux inside a React based application.</p><p>There are 2 extra libraries to make that easier:</p><ul><li><a href="https://github.com/rackt/react-redux">React-Redux</a> : that’s the official React bindings for Redux.</li><li><a href="https://github.com/rackt/redux-router">Redux-Router</a> : even though the use of a router is not strictly required, it brings sanity in the development of a non trivial React application.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1046b0346e7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>