<?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 Pratik Chakravorty on Medium]]></title>
        <description><![CDATA[Stories by Pratik Chakravorty on Medium]]></description>
        <link>https://medium.com/@pratikch1253?source=rss-ee0b245106cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TTWPDRpV2FaSS9zqe0YSag.jpeg</url>
            <title>Stories by Pratik Chakravorty on Medium</title>
            <link>https://medium.com/@pratikch1253?source=rss-ee0b245106cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 06:49:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pratikch1253/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[Generators in JavaScript]]></title>
            <link>https://codeburst.io/generators-in-javascript-7b861eb5cc4?source=rss-ee0b245106cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b861eb5cc4</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Pratik Chakravorty]]></dc:creator>
            <pubDate>Mon, 24 Sep 2018 15:07:06 GMT</pubDate>
            <atom:updated>2018-09-24T15:07:06.138Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8XerrLuGASX_oxJPglX3g.png" /></figure><p>We all know that a function in JavaScript runs in a top down fashion. For example in the following code:</p><pre>function sayHello() {<br>  console.log(&quot;Hello&quot;);<br>  console.log(&quot;Hi There!!&quot;);<br>}<br>sayHello();</pre><p>This provides the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/140/1*z8Af84ZriyYi-CUV7BK1ng.png" /><figcaption>console log output</figcaption></figure><p>Generator functions allow you to pause a function and resume a function. So with this you can suspend a function in between and do something else. Finally resume the functions execution right at the point you suspended. The following code is an example of a generator function:</p><pre>function* sayHello() {<br>  //this is a generator function<br>}</pre><p>Notice the * right after the function keyword. This asterisk is used to denote a function as a generator function. Now with a generator function you get a special keyword that you can use to suspend from a function and go do something else. This keyword is called yield. Remember this keyword will only work when you are inside a generator function. The code for that will look as follows:</p><pre>function* sayHello() {<br>  yield &quot;Hello&quot;;<br>  yield &quot;Hi There!!&quot;;<br>}</pre><p>Now to use a generator function you can do the following:</p><pre>const sayHelloGen = sayHello();<br>console.log(sayHelloGen.next());</pre><p>This gives you the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*lV5MafJxEqOHJwMYZglObg.png" /><figcaption>generator function output</figcaption></figure><p>Now in the above code notice the use of the method next. This method allows you to output whatever you yield from the generator function. In this case the first thing that we yield from the generator function above is the string &quot;Hello&quot; and so we get that but not exactly as a string but rather as an object with a value property set to &quot;Hello&quot;. This object also contains another important property called done which has a boolean value of false. This means that the generator function has not finished in completion and still has more things to return back to which is certainly the case. Now if we write the following code again.</p><pre>console.log(sayHelloGen.next());</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*gFQv95boIxkEKqpS1uMugw.png" /><figcaption>generator function output</figcaption></figure><p>We get the next thing that we yield which is “Hi There!!”. We still see that the value of the done property is set to false. Now if we run the above code again we can see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*dR7DU-0ehGn04qxhGCz7mg.png" /><figcaption>generator function output</figcaption></figure><p>Interestingly now the value property has been set to undefined as we don’t have anything else to yield and the done property is now set to true. Now no matter how many times we execute the above code it will return the same object.</p><p>Now in technical lingo what is happening is that the generator function returns something called an iterator and we go through each objects in the iterator through the use of the next method. Now generators are useful as it maintains the state value. To give an example take the following:</p><pre>function* increment() {<br>  let i = 0;<br>  yield i;<br>  i++;<br>  yield i;<br>  i++;<br>  yield i;<br>  i++;<br>}<br><br>const incrementGen = increment();<br><br>console.log(incrementGen.next());<br>console.log(incrementGen.next());<br>console.log(incrementGen.next());</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*2znu8bPgJ601_bipxfkV3A.png" /></figure><p>As you can see that when we call the next method for the first time we get back 0 as the value. Now when we call it again it goes back to the generator function executes the code right after the first yield and then gives us back a value with 1. The same thing happens when we call the next method again. So with generator functions we can maintain the state of some variable even after the function has been suspended.</p><p>Now instead of writing these yield statements a bunch of times we can make use of the for of loop and just write it once. For example suppose we have the following code:</p><pre>const items = [&quot;Apples&quot;, &quot;Grapes&quot;, &quot;Tomatoes&quot;];<br>function* justLooping() {<br>  for (item of items) {<br>    yield item;<br>  }<br>}<br><br>const loopingGen = justLooping();<br>console.log(loopingGen.next());<br>console.log(loopingGen.next());<br>console.log(loopingGen.next());</pre><p>This gives us the following output in the browser’s console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*81TJVO8QQFqrxvCopw2vxA.png" /></figure><p>So the for of loop works with generators as well. We can use it to yield a bunch of things without writing yield every dang time. Now that’s all fine and good but you might be wondering why do I even care about all this where will I actually need a generator function.</p><p>The importance of generator function comes in cases when you have to do Ajax requests. We all have had the issue of underfetching with API calls. We fetch some data from an API call and then we use a specific thing from that data to fetch another thing and then we use something else from there and fetch another. As you can see this waterfall API fetching goes on. By waterfall I mean that besides the first one each successive API requests need the existence of the previous one.</p><p>For example lets say we have the following code:</p><pre>function* getStuff() {<br>  const user = yield ajax(&quot;http://api.github.com/users/pratik-chakravorty&quot;);<br><br>  const repos = yield ajax(<br>    &quot;http://api.github.com/users/pratik-chakravorty/repos&quot;<br>  );<br>}<br><br>function ajax(url) {<br>  fetch(url)<br>    .then(data =&gt; data.json())<br>    .then(data =&gt; getStuffGen.next(data));<br>}<br><br>const getStuffGen = getStuff();<br>getStuffGen.next();</pre><p>Now I know the above code is not the best example but it drives the point through. Imagine we have two API’s that return some data. Now we need the data from the first API to actually make the request for the data of the second API. This could be anything from an ID property to a username. Now what the above code is doing is that first we have defined our generator function getStuff which has two const variables each of them have a yield. Now when we execute getStuffGen.next() it basically starts the whole thing. It goes to the generator function finds the first yield and executes the function beside it which is an ajax function. Can&#39;t find a reference to this function inside its own scope goes to the outer scope finds the reference and executes the function passing the value of the url. The ajax function contains a call to the fetch API which then gives back the data for the given API.</p><p>Now notice the line getStuffGen.next(data). This line uses the next method in a different way. Instead of calling next directly without any arguments it passes the data that we got back from our API call. Now where does this data get stored. Well it gets stored in the user const variable in the getStuff function</p><p>Effectively what is happening is that until the data from the first yield comes back the second yield in that generator function won’t be called at all. This makes the code more readable which is a big thing when we have thousands of such API requests everywhere. So to illustrate my point lets add some console.logs in the above code.</p><pre>function* getStuff() {<br>  console.log(&quot;Before Fetching User&quot;);<br>  const user = yield ajax(&quot;http://api.github.com/users/pratik-chakravorty&quot;);<br>  console.log(user);<br><br>  console.log(&quot;Before Fetching User Repos&quot;);<br>  const repos = yield ajax(<br>    &quot;http://api.github.com/users/pratik-chakravorty/repos&quot;<br>  );<br>  console.log(repos);<br>}<br><br>function ajax(url) {<br>  fetch(url)<br>    .then(data =&gt; data.json())<br>    .then(data =&gt; getStuffGen.next(data));<br>}<br><br>const getStuffGen = getStuff();<br>getStuffGen.next();</pre><p>This gives us the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4h1xB9jY0X-H1rFCiK7qzQ.png" /></figure><p>So with that I hope this clears the idea behind generator functions. In simple terms its nothing but a function with special play and pause controls. That’s what the feature image of this blog post means. Generator functions are used in the popular Redux library Redux-Saga which is used for writing async-actions in Redux hence it is a pretty important concept to understand.</p><p>As always thanks for reading this article and I will be back with another one.</p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b861eb5cc4" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/generators-in-javascript-7b861eb5cc4">Generators in JavaScript</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Redux Thunk]]></title>
            <link>https://codeburst.io/understanding-redux-thunk-6dbae0241817?source=rss-ee0b245106cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dbae0241817</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Pratik Chakravorty]]></dc:creator>
            <pubDate>Thu, 09 Aug 2018 15:40:24 GMT</pubDate>
            <atom:updated>2018-08-09T15:40:24.825Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YIwZP_yrjmSV2sZPh572KA.png" /><figcaption>End Goal</figcaption></figure><p>Redux is a state management library that has become increasingly popular but there is a learning curve to it. There are certain technical terms that throws off people when they first start learning Redux. If you feel like you need to understand Redux a bit more I suggest trying out my <a href="https://codeburst.io/redux-a-crud-example-abb834d763c9">Redux CRUD article</a>. It is a long article that goes over the important concepts of Redux like what are actions,reducers and stores all while building a CRUD based application. In this post which is a follow up to the previous Redux article I will try to explain what is Redux Thunk by building a Github Search application.</p><p>So let’s get started first thing you will need is create-react-app so make sure you have it installed in your computer if not type the following command in a terminal:</p><pre>npm install -g create-react-app</pre><p>Why are you using npm why not yarn? Old habits. Now that you have the tool set up lets create a new project.</p><p>Type the following in the terminal:</p><pre>create-react-app github-search</pre><p>This should create a new project for you with all the dependencies. Let’s open this up in a new text editor by changing to this directory using:</p><pre>cd github-search</pre><p>I use visual studio code as my text-editor but you can use whatever you are comfortable. Now whenever I start writing any React application first thing I do is a bit of clean up as we do not require some of these files you can keep them if you like. So go back to the terminal and type the following:</p><pre>cd src<br><br>rm App.css App.test.js logo.svg registerServiceWorker.js</pre><p>Once that is done go back to the text-editor and make some changes to the index.js file. The changes should be as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16ae30f8fac2fd4c24f443c29bb39a30/href">https://medium.com/media/16ae30f8fac2fd4c24f443c29bb39a30/href</a></iframe><p>Now head to App.js and make the following changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/777f5d83b0e24558bfe6f72bb2aa9204/href">https://medium.com/media/777f5d83b0e24558bfe6f72bb2aa9204/href</a></iframe><p>Now go back to the root directory of the project and type the followng:</p><pre>npm start</pre><p>This gives us the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*9LwSBPd3nI6GKbxy0Y6dvw.png" /><figcaption>create-react-app output</figcaption></figure><p>Now lets install redux, redux-thunk and react-redux.</p><pre>npm install redux redux-thunk react-redux</pre><p>Now create a new folder under the src directory and call it actions. Next create a file under that folder and name it fetchAction.js. Once that is done create another folder under the src directory called reducers and create a file under it called index.js. Once all that is done under the src directory create a file called store.js.</p><p>Now lets write some code. Inside store.js write the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f88fe2d430f7fa5d01c59ef318e3118b/href">https://medium.com/media/f88fe2d430f7fa5d01c59ef318e3118b/href</a></iframe><p>We import the createStore function and the applyMiddleware function. What is a middleware? Well it is nothing but a piece of code that sits between your actions and your reducers. It takes your actions does something to it before passing it down to the reducer. Think of it like a middle-man.</p><p>Now createStore is used for creating the redux store while the applyMiddleware will be used for adding the thunk middleware. Next we have an import statement from the reducers directory ignore that for now. Basically it is importing the reducer we will need for this application. Here the name of the reducer is asyncReducer. Next we import thunk from the redux-thunk package.</p><p>Finally we create the store using the createStore method passing the asyncReducerand theapplyMiddleware functions to it.</p><p>Now that we have the store lets write the reducer for this application. Go back to index.jsunder the reducers directory. Note go to index.js under the reducers folder not the root index.js file. In there write the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3138925b6b751222753f045f64c7b146/href">https://medium.com/media/3138925b6b751222753f045f64c7b146/href</a></iframe><p>Here we have a pretty basic reducer. What is interesting here is the shape of the state object. The state contains two properties one is userData and the other is isFetching. The userData is an object that will house all the user related information that we will get from our API. The isFetching property will be used to load the loading indicatior depending upon when the API request is made. isError is used to render an error message in case we do not get back any user data.</p><p>Go back to index.js and make the following changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e00b1c1cd26cea8d6e9211531bb3baee/href">https://medium.com/media/e00b1c1cd26cea8d6e9211531bb3baee/href</a></iframe><p>Here we have imported the store that we created earlier inside store.js. We are also making use of the Provider component that allows us to access the store state from our components. Hence we pass the App component which is the root component into the provider and passing the store as a prop.</p><p>Now lets go back to fetchAction.js which is inside our actions folder and write the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb98408262cc5598baf3716096f198c1/href">https://medium.com/media/eb98408262cc5598baf3716096f198c1/href</a></iframe><p>In here we are making use of action creators. Now action creators are just functions that returns an action object. Here we have three action creators each of them returning an action. A little refresher before going forward. Actions are plain old javascript objects which has a mandatory type property. This property defines what sort of action/event is taking place in the application. The first action creator fetch_post is responsible for starting the fetch request. It would be used mainly for showing the loading indicator.</p><p>The second action creator receive_post will be called when we get back the data from github. Finally receive_error is an action creator that will be called only when we have an error in getting our data back from github&#39;s servers.</p><p>Now you might be wondering what is a thunk or where does a thunk come into play. Well let’s discuss it. First lets understand what is a thunk in the most basic sense. A thunk is a function that returns another function. For example:</p><pre>function say() {<br>  return function something() {<br>    //code here<br>  };<br>}</pre><p>The above function say() is a thunk because it returns another function in this case something(). Now how is this useful you might ask. Well we know that in redux reducers are pure functions hence we can&#39;t do any async operations inside the reducers and actions are just plain old objects.Now our dispatch method inside the store accepts an action object as its parameter what the redux thunk middleware does is that if say an action creator returns a function instead of an object then it simply executes that returning function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vtYeZg_wvFsm6aKpi70_Og.png" /><figcaption>What Redux Thunk really is</figcaption></figure><p>Now the returning function can accept two parameters. Those are dispatch and getState. This is great because with dispatch we can call other action creators. So now all we do for async operations is to do everything that will be async inside the returning function and then call the relevant action creators when the data comes back passing in the new data that we get from the API. The other relevant action creators in this case receive_post will then pass this new data in an action object to the reducer and then the reducer can update the application&#39;s state with the new data.</p><p>So with that in mind let’s modify the code in fetchAction.jsas so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97d587cecc173aa89ea79a0e165cc94f/href">https://medium.com/media/97d587cecc173aa89ea79a0e165cc94f/href</a></iframe><p>So now we have a new function at the bottom called thunk_action_creator. This function takes a username as its parameter. First we take the username and sanitize the data like removing whitespaces and then put it in the variable user. After that we have our first use of dispatch where we call the fetch_post action creator which will be used for setting our loading indicator as previously stated. Next we return a function from the thunk_action_creator. This function has access to dispatch and the getState methods of the store object. Here we return something from the fetch call. In the parameter we pass in the url that will be used for fetching users and pass along the username that will be provided by the user. Finally when the data comes back we call another action creator using dispatch which is receive_post which takes in the newly received data from the API and passes it as an argument. Finally if the data that is returned has a message property with a value of Not Found we simply throw a new error stating that the user with such username does not exist and so we catch this error and make a call to receive_error which will be used for setting our error flag.</p><p>With that in place lets go back to the reducer function and add some more code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e95454ff5f5512c6e839568c2b7f5ee/href">https://medium.com/media/5e95454ff5f5512c6e839568c2b7f5ee/href</a></iframe><p>We have three switch cases. The first one FETCH_USER is used for setting the loading indicator. The next one FETCHED_USER is used for setting the data that came from the API in the userData object. Finally we have RECEIVE_ERROR which sets the error flag to true. Here is a link to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign">Object Assign </a>if you feel like you need a refresher.</p><p>Now lets head back to App.js and start building the user interface and hook all this up.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ab88e9350a00e82ba8832c4eb5eba00/href">https://medium.com/media/3ab88e9350a00e82ba8832c4eb5eba00/href</a></iframe><p>I have already prepared the styles for this which are as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65aa0885f1968bda4f90ffff8fb88e77/href">https://medium.com/media/65aa0885f1968bda4f90ffff8fb88e77/href</a></iframe><p>Put all that code inside index.css. Note that I am using a custom font here so you might have to try something else.Now with all that if we go back and check the browser it should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*PLCHJQyaaEOVCeg2QaZ_wg.png" /><figcaption>What the app looks like</figcaption></figure><p>Now if we type something in the input and hit submit we can see that we are able to capture the user data inside the console as well.</p><p>Now I know I could have made the form a controlled component and used an onChangehandler. I used refs as they are simpler to understand atleast for me. You can switch back to using your preferred way.</p><p>Now lets head back to App.js and connect it to our store.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d54592da1959d38ad8478099fab6dcf5/href">https://medium.com/media/d54592da1959d38ad8478099fab6dcf5/href</a></iframe><p>If we check the console we can see that we have gained access to our store state from within the App component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*9ZaAAJ5ukzEgxifYDEOM4w.png" /><figcaption>We have access to our state</figcaption></figure><p>If the above code feels weird to you I strongly suggest checking out my Redux article where I go in depth about connect and how the above code basically works.</p><p>Now that we have access to the store lets dispatch some action</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0aaec8fb252d47b1175ba1341970e5d/href">https://medium.com/media/d0aaec8fb252d47b1175ba1341970e5d/href</a></iframe><p>A lot going on here. First we make use of our thunk_action_creatorinside our handleSubmit where we dispatch it passing in the username that we got back from the user.</p><p>Inside the App component after the form element we check to see if the isFetching flag from our state is set to true if yes we show the loading indicator. Next we check to see if there are any errors while fetching the data if yes we show the error message. Finally we check to see whether the userData object is empty or not. If not we render the &lt;UserInfo&gt;component and pass in the userData object as a user prop.</p><p>Inside the UserInfo component we have the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/497e6d8bac34925d8247af270294965c/href">https://medium.com/media/497e6d8bac34925d8247af270294965c/href</a></iframe><p>Just a basic component that takes in the userData object and shows it on screen. Now if we go back to the browser and type a username back we see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CdWzXHv0rWC4NNEZM70JhQ.png" /><figcaption>It’s fetching user data</figcaption></figure><p>Now I know all of this is overkill to create such a basic application. We could have done it with React itself. Yes, I agree but my main objective here was to show you how redux thunk works with a simpler example. Once you understand this you can easily take this approach and replicate it in bigger projects with some modifications.</p><p>Now that you have an understanding of redux thunk improve this application even further use React Router and create a separate page use some other API&#39;s like Reddit&#39;s API and fetch some data and show it in a nice clean user interface. Maybe learn how you can cache these requests. You can even add some custom animations as the UserInfo component is revealed. As you can see we can easily expand this application to more complex territories if we desire.</p><p>Thanks for reading this long article and I will be back with another one.</p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dbae0241817" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/understanding-redux-thunk-6dbae0241817">Understanding Redux Thunk</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux-A CRUD Example]]></title>
            <link>https://codeburst.io/redux-a-crud-example-abb834d763c9?source=rss-ee0b245106cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/abb834d763c9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Pratik Chakravorty]]></dc:creator>
            <pubDate>Sun, 01 Apr 2018 23:44:20 GMT</pubDate>
            <atom:updated>2018-04-01T23:44:20.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kz_QmZCyF6wkOGIy14KUSQ.png" /><figcaption>What we are aiming for</figcaption></figure><p>This article’s goal is to explain the core concepts of Redux by making a CRUD application. Most applications are CRUD applications. If you don’t know what CRUD really is, it’s short for Create, Read, Update and Delete.</p><p>So this blog post will show you the steps to create an app where the user can create posts, read posts , edit posts and delete posts using React and Redux so let’s get started. I believe that you have <a href="https://nodejs.org/en/">Nodejs </a>installed on your system.</p><p>First let’s spin up a new project so go to a directory where you will store this project and type the following in the terminal-</p><pre>create-react-app crud-redux</pre><p>The above command uses the <a href="https://github.com/facebook/create-react-app">create-react-app</a> CLI tool to generate a react boilerplate project for us so that we don’t have to configure any tooling. If that command fails for you or gives out an error make sure you have create-react-app installed on your machine. If not do the following and then run the above command.</p><pre>npm install -g create-react-app</pre><p>The above command will install create-react-app globally on your system so that you can use it anywhere you want.</p><p>Once that command finishes it’s job you will have a new directory named ‘crud-redux’. Change to this new directory. Now let’s clean this up a little bit as we don’t need some of the stuff for this project.</p><p>Type the following</p><pre>cd src</pre><pre>rm App.css App.test.js logo.svg registerServiceWorker.js</pre><p>Finally go back to the root directory of the project and open it up in your favorite text-editor.</p><p>Now let’s install Redux and it’s React bindings. So back in the terminal type the following-</p><pre>npm install --save redux react-redux</pre><p>Redux is a state management library that gives you access to the state anywhere in your components without the need to pass props. So it can be used with any front-end libraries like Angular and React but it works best with React. ‘react-redux’ is the official library that connects the two.</p><p>Since we deleted some of those files earlier we need to make some changes in index.js and App.js which are as follows-</p><p>Go to crud-redux/src/index.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df5c3645c8dc33c6f183b2d43ae4035d/href">https://medium.com/media/df5c3645c8dc33c6f183b2d43ae4035d/href</a></iframe><p>and crud-redux/src/App.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc1471d36623f1e1a238c31a1d896c81/href">https://medium.com/media/dc1471d36623f1e1a238c31a1d896c81/href</a></iframe><p>With that done, let’s start the server and make sure everything is working before we start writing any code. To start the server type the following command in the terminal</p><pre>npm start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*HTf1AiQxwJ3PmpplU0ybKA.png" /><figcaption>React is Running</figcaption></figure><p>If you are getting errors please make sure you have made those changes that I have shown above in index.js and App.js.</p><p>Whenever I make any React application I always try to make the basic version of it and then add interactivity to it. So with that in mind let’s create some components. In crud-redux/App.js do the following-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/010fcd9cffc5604d77998a91500787e3/href">https://medium.com/media/010fcd9cffc5604d77998a91500787e3/href</a></iframe><p>Here I have created two components. The PostForm component will contain the form elements for creating a post and the AllPost component will contain all the posts. So let’s create the files for each of these components. Under src folder create two files called ‘PostForm.js’ and ‘AllPost.js’.</p><p>Inside PostForm.js add the following code-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9435eeaba945d78e24eb21c1d3652dc7/href">https://medium.com/media/9435eeaba945d78e24eb21c1d3652dc7/href</a></iframe><p>We will add styles later so let’s get on with the other component. Inside crud-redux/src/AllPost.js add the following lines-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5096526793565858a0d09ebff682d857/href">https://medium.com/media/5096526793565858a0d09ebff682d857/href</a></iframe><p>With that we have the following output in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*16mmwAgkL8Eq5g72KkH2yA.png" /><figcaption>UI for Creating Post and Displaying Posts</figcaption></figure><p>Now that we have our basic UI in place let’s get into Redux. First thing to understand about Redux is something called the <strong>store</strong>. It’s where the entire state of your application will live. This is the first main benefit of using Redux. Instead of having to manage the state in different components we have to only manage it in one single place called the store. The store is an object which has some methods in it that allows us to get the current state of our application, subscribe to changes or update the existing state of our application. This is great because now we don’t have to pass down data from the parent component to deeply nested child components through props. So anytime a component needs data it can ask the store and the store will provide it with the data. As simple as that. With that in mind let’s create the store. In our crud-redux/src/index.js make the following changes-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e5921fa6d10bf80a09a3a943aab8f76/href">https://medium.com/media/5e5921fa6d10bf80a09a3a943aab8f76/href</a></iframe><p>The <strong>createStore</strong> method will allow us to create the store but we are not done yet. This method needs a special argument and this argument goes by a special name called the ‘<strong>reducer</strong>’. Let’s create a separate folder called reducers. So under crud-redux/src create a folder called ‘reducers’. Inside that folder create a file called postReducer.js Add the following code for now.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad2c45053f7b720672bfd8ee280f4d0a/href">https://medium.com/media/ad2c45053f7b720672bfd8ee280f4d0a/href</a></iframe><p>We will fill in the contents of that function a bit later. Now let’s understand another important concept in Redux called <strong>actions</strong>. Actions are nothing but plain Javascript objects with a type property. This type property describes the event that is taking place in the application. This event can be anything from incrementing a counter to adding items in an array. These actions help us track the different events that are happening in our application. The structure of an action is as follows-</p><pre>{<br> type: &#39;EVENT_NAME&#39;</pre><pre>}</pre><p>An action can have any number of properties but it must have a type property. So an action can include data like so</p><pre>{<br>  type:&#39;ADD_ITEM&#39;,<br>  name: &#39;Redux&#39;</pre><pre>}</pre><p>In this example the event name is ‘ADD_ITEM’ and the data is the name property with a value of ‘Redux’. Now another important term that is used alongside actions is called dispatch. When we say ‘dispatch an action’ we simply mean call the dispatch method which is inside the store object with an action. Still with me?</p><p>Let’s look at the store. The store that we created using the <strong>createStore </strong>method is an object which has some methods in it. One of those methods is called dispatch. This dispatch method accepts an object as it’s argument and this object is what we call as ‘action’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJpRSSkw5Cl7eodib3YT3Q.png" /><figcaption>what dispatch really is</figcaption></figure><p>With that out of the way, let’s finally go back to that function that we wrote earlier inside postReducer.js. You see whenever we dispatch an action, this action with it’s type property is received by something called the reducer. Now what the heck is the reducer? Well it’s nothing but a function that takes the <strong>current state </strong>and an <strong>action </strong>that was dispatched as it’s parameters and returns the <strong>new state.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E-n_l5VWtBKhTyAmmRmngw.png" /><figcaption>What Reducer really is</figcaption></figure><p>So next time when you see the term reducer thrown around remember that it’s just a function that gives you new state for your components.</p><p>Now the question is how does the reducer go about producing the new state for the application. Well that is pretty simple, it first checks which <strong>type </strong>of action was dispatched and based on it returns the new state. Under crud-redux/src/reducers/postReducer.js add the following lines of code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b11e9b4b979458c33103c724acce2bea/href">https://medium.com/media/b11e9b4b979458c33103c724acce2bea/href</a></iframe><p>Now what is happening here is that we are using a ‘switch statement’ and we are switching based on the value of <strong>action.type. </strong>If the value is ‘ADD_POST’ we are returning a new array containing action.data. Basically whenever the ‘ADD_POST’ event happens we want to push some data into the state array.Now what is action.data? Well it’s nothing but an object with our individual post title and the post message. One thing to note here is that the reducer function expects a default value for the state. Here we are using ES6 default-parameter syntax to add that. The default value for the state here is an empty array. One other thing to note is that a reducer must always have the default clause inside the switch statement. In the default clause we simply return the state. This is done so that in case none of the action.type value matches any of the cases we simply return the state.</p><p>Now that we have some code inside postReducer.js let’s import it in our index.js file and pass it to the store as an argument.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36d6ae08683d727beb21bbb883913661/href">https://medium.com/media/36d6ae08683d727beb21bbb883913661/href</a></iframe><p>Now that we are done with the reducer. Let’s pass this store to our components. To do that let’s use the Provider component from the ‘react-redux’ library. Change crud-redux/src/index.js as follows-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2b9da6827809a8b4e22ac4da2838708/href">https://medium.com/media/b2b9da6827809a8b4e22ac4da2838708/href</a></iframe><p>The Provider component uses something called React Context which allows you to pass the store object to any components that needs to access it without the need to pass props. Here we are wrapping the App component which is our parent component with the Provider component so that all the child components in our app can get access to the store. The Provider component takes the store as a prop.</p><p>Let’s head back to our PostForm component and connect it to our store so that we can dispatch actions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d80cd8311815bb62ef2921736e34e20e/href">https://medium.com/media/d80cd8311815bb62ef2921736e34e20e/href</a></iframe><p>So in here the form element now accepts an onSubmit event. Whenever this event takes place the handleSubmit function will execute. The handleSubmit function takes one argument which is the event. Calling e.preventDefault() will prevent the page from refreshing. Next we grab the value of the title and the message from the inputs using <a href="https://reactjs.org/docs/refs-and-the-dom.html">refs </a>and then put them inside an object called data. We also have an id property whose value is set to whatever new Date() returns. We will use this id property to perform update and delete operations.</p><p>Let’s put in some values in the title and the post fields and log it to the console. This is to make sure that the data is being captured. Add a console.log() in between like in the following-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe77ebf41fa28bc33ece35359f735215/href">https://medium.com/media/fe77ebf41fa28bc33ece35359f735215/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYSXI0huuB0h8_IGQIDN1Q.png" /><figcaption>console.log(data) output</figcaption></figure><p>It seems like our data is being captured properly. Great all is left now is to dispatch an action. To do that we will make use of the <strong>connect()</strong> function provided by the react-redux library. Now this is where things might get a bit tricky but I will try my best to explain it. We know that our state lives inside this object called the store and this store has it’s own set of methods for getting the current state of our application, updating the state of our application and subscribing for changes. We have already discussed one of these methods called dispatch. We need dispatch whenever we want to pass some action to the reducer to tell some sort of event has happened and then the reducer can decide what to do with the state. But to do that we need access to dispatch. Won’t it be great if we somehow got access to the dispatch method as a prop. That is what connect() allows you to do. connect() returns a function which takes in your current component as an argument and returns a new component with dispatch method as it’s prop. The main idea to remember is that connect will ultimately return a new component which has the dispatch method as a prop.The basic syntax for writing connect in your React components is as follows-</p><pre>export default connect()(component-name)</pre><p>So let’s use that and add it in our PostForm.js. So after that our component will look like so-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ec6b2dad958c8fec9e5dcc3de64a224/href">https://medium.com/media/8ec6b2dad958c8fec9e5dcc3de64a224/href</a></iframe><p>With that in place we can easily access dispatch in our components so let’s use it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a00a61ff32b99f868273b698263e8a5/href">https://medium.com/media/6a00a61ff32b99f868273b698263e8a5/href</a></iframe><p>Remember that connect() gives you access to dispatch as a prop. Here once we have captured the data from the form we dispatch the action using this.props.dispatch() passing in the data object with a type of ‘ADD_POST’.</p><p>Great, now we have added some data in our state but we can’t see any of those changes reflected in our application so let’s fix that. Before doing that let’s understand one more important thing about connect(). This special function provided by the react-redux library gives you access to dispatch whenever you call it wrapping the component-name as an argument to the function that is returned. We have seen this syntax which is as follows-</p><pre>export default connect()(component-name)</pre><p>Additionally, connect can do more. It can give you access to your state which is living inside your store object. To get access to your state, we need to use a special function called <strong>mapStateToProps</strong>. This function does exactly what it is named, map the state from the store object to the props object in your components. Let’s define this mapStateToProps function-</p><pre>const mapStateToProps = (state) =&gt; {</pre><pre> return {</pre><pre> posts: state</pre><pre> }</pre><pre>}</pre><p>The argument to mapStateToProps is our application state. To understand this better, imagine whatever you pass inside the mapStateToProps argument is your state. Next question to ask is what is that state is it an array or an object or something else? Well that will depend on what you have defined it in your reducer. Since we have only one reducer which is the postReducer, we know that the state is an array.</p><p>Next we return an object with a key posts and the value is the state itself. The key that we use in mapStateToProps will be available to us as props inside the component.</p><p>With that in place let’s add this function as an argument to our connect. So inside crud-redux/src/AllPost.js make the following changes-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35c518de927bc0102a206117b1dcc8da/href">https://medium.com/media/35c518de927bc0102a206117b1dcc8da/href</a></iframe><p>Now to check what we have here, we can log this.props.posts like so</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56898fc0e6b89529574e9f0fb952b3c2/href">https://medium.com/media/56898fc0e6b89529574e9f0fb952b3c2/href</a></iframe><p>To test this out enter some values in the title and the message fields and check your console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZ2vcsesi7km6e9qoFvZPg.png" /><figcaption>we have the post!</figcaption></figure><p>Great so we have the post. All is left is to display it in the browser. To do that let’s create another component called Post. So under crud-redux/src create a new file and call it ‘Post.js’. Now head back to AllPost.js and make the following changes-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63ed23b243272c64795b59bbd009ecaf/href">https://medium.com/media/63ed23b243272c64795b59bbd009ecaf/href</a></iframe><p>We have imported the Post component inside AllPost and used the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">Array.prototype.map</a> function to loop over each of the individual posts inside this.props.posts and pass it down to the Post component with the key as post.id and the post itself. Inside crud-redux/src/Post.js add in the following-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/212e08d05d279a04f59eb38cab7d9980/href">https://medium.com/media/212e08d05d279a04f59eb38cab7d9980/href</a></iframe><p>With that in place, enter some values in the title and the message fields and see if it is being displayed under All Posts like so-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*PWGI9CSYxtdKzJRvyklehQ.png" /><figcaption>We finally have the Posts.</figcaption></figure><p>If you have got this far, great you are finally done with the <strong>C </strong>and the <strong>R </strong>part of this CRUD application as now we can create posts and can read them as well.</p><p>Before diving into the update and the delete part of this application let’s recap.</p><p>The entire state of our application lives inside an object called the store. In order to update the state we need to dispatch an action. Actions are nothing but Javascript objects with a type property which describes the event taking place. Events can be anything from updating counters to adding posts like we have seen above. Once the action has been dispatched, it is received by the reducer. The reducer takes in the current state of the application and the dispatched action and produces the next state of the application based on action.type.</p><p>For our React application to use the Redux store, we use the Provider component provided by the react-redux library and put it as the root of all the components.</p><p>In order to access our Redux store within our React components we use the special connect() function. This function gives us access to dispatch and when we pass in mapStateToProps it gives us access to the state. mapStateToProps is a function that takes in the state of our application as a parameter and returns an object with keys of that object becoming the props of the component so that whenever we use this.props.key_name we get back the state we need.</p><p>With that out of the way, let’s go back to the Post.js file and add in some buttons for Delete and Edit.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/817b2d986285d51520fa7acca0e12f67/href">https://medium.com/media/817b2d986285d51520fa7acca0e12f67/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*ayFG3-RHWQxp1GSl19wgBg.png" /><figcaption>Edit and Delete Buttons</figcaption></figure><p>Let’s tackle the delete functionality first as it is easier. What we want to do is that whenever the user clicks the delete button it should remove the post. Now to do that we need to identify which post the user is deleting and we can do that with the post.id property that we included when we were adding the post earlier in PostForm component. So we need the following things, first we need an onClick handler so that when the user clicks the delete button we can do something. Then what we need is to dispatch an action of type say ‘DELETE_POST’. We know pretty well how to get that going and that is by using connect.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9aea1ec04fa666e605eec2e34cfc0a0/href">https://medium.com/media/b9aea1ec04fa666e605eec2e34cfc0a0/href</a></iframe><p>Here inside the onClick handler we have an arrow function that is invoked when the user clicks the delete button. Once they do, we dispatch an action of type ‘DELETE_POST’ and we also pass in the id of the given post.</p><p>To make this work we need to add this event in our reducers so let’s go back to our reducers under crud-redux/src/reducers/postReducer.js and add in the following-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b05d4028ccc9578e89b2a3768fb44abe/href">https://medium.com/media/b05d4028ccc9578e89b2a3768fb44abe/href</a></iframe><p>Here we use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">Array.prototype.filter </a>to remove the post with the id that matches action.id.</p><p>Now that is in place, go back to the app and try adding some data and then click the delete button. If the post goes away then great you have successfully implemented the <strong>D </strong>of this CRUD application. The only thing that is left is the update operation.</p><p>The last and the final CRUD operation is the Update operation and this one is a bit different. All the other operations we have seen are mostly one-click operations. You click on post, the post gets added,click on delete the post gets removed. This is not the case with Update. Because to update an existing post, first the user clicks on edit and then we provide them with a way in which they can change the post title and the message. Finally when they submit the changes, we perform the necessary updates and show it in the browser. So from this we know that the update operation is a two-step operation.</p><p>One approach in doing this is to use a boolean in our data object. This boolean will be false initially when the posts are added but when the user clicks on edit, we change it’s value to true. If the value of this boolean is true then instead of rendering a regular Post component, we render a special EditComponent which will have a form with title and message fields. Once the user has made the necessary changes and hits update we go back to rendering the Post component but with the updated value. So let’s do this-</p><p>Inside crud-redux/src/PostForm.js make the following changes-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8f4c5d85d45b71859ff1a4b44abf015/href">https://medium.com/media/f8f4c5d85d45b71859ff1a4b44abf015/href</a></iframe><p>Here we have added an extra property called ‘editing’ and have set its value as false. Next create a file called EditComponent.js inside the src folder. Once that is done head over to crud-redux/src/AllPost.js and make the following changes-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f96cb7bd65cedbe7c8fa9e729253e9ef/href">https://medium.com/media/f96cb7bd65cedbe7c8fa9e729253e9ef/href</a></iframe><p>All that this code is doing is that it is checking the value of editing in each of the posts and if it is true then instead of rendering the Post component it is rendering the EditComponent and passing it the post as a prop.</p><p>Before going in and adding the Form in EditComponent, we need to make one more change inside Post.js so go inside crud-redux/src/Post.js and make the following change-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aaaf132d947b75e7274652416059f925/href">https://medium.com/media/aaaf132d947b75e7274652416059f925/href</a></iframe><p>All we are doing is that when the user clicks the edit button we are dispatching an action of type ‘EDIT_POST’ and also passing the id of the post.</p><p>Since we have dispatched a new event, we need to make some changes in postReducer.js so head over to this file and make the following changes-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aac8a9de892c71a5f97100f9e2bdaabd/href">https://medium.com/media/aac8a9de892c71a5f97100f9e2bdaabd/href</a></iframe><p>Here we are using Array.prototype.map to loop over each item and then check the id of the post with the id that was passed in the action. If there is a match then return a new object but change the value of editing to true if it was false or vice-versa. If there is no match then just return the object as it is.</p><p>Finally, let’s head over to EditComponent.js and add in the following-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63977ced98cecab54d5e7ee9532e7ee4/href">https://medium.com/media/63977ced98cecab54d5e7ee9532e7ee4/href</a></iframe><p>Here we are creating another Form which has an onSubmit handler. When the form is submitted, this.handleEdit function is invoked. This function takes in the event as a parameter. e.preventDefault() stops the page from refreshing. Then we are grabbing the data from the inputs using refs and putting it inside an object.Finally we are dispatching a new action with type property as ‘UPDATE’ . We are also passing in the id of the post that needs to be updated along with the updated data. Don’t forget to use the connect function when dispatching actions.</p><p>Since we have added in a new event in our files, we need to make some changes in the reducer so head back to the reducer and make the following changes-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b22c40fbf5c51bf34cb3e58b4d2506a/href">https://medium.com/media/1b22c40fbf5c51bf34cb3e58b4d2506a/href</a></iframe><p>In here all we are doing is using Array.prototype.map and looping over each posts and the post whose id matches the one with the id that was passed in the action we are returning a new object but with the updated values for title and message.Finally we are setting editing to false.</p><p>With that we are done, head over to the app, add some posts and hit the edit button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*20p1rbzVpoirX660qJOwOg.png" /><figcaption>And the Update Form appears!</figcaption></figure><p>When we hit the edit button the post changes to a form with the title and the message fields populated with the current values. Let’s make a change and hit update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*y3d0D_sAZ4mxpH2-BdjZPQ.png" /><figcaption>Update Works!</figcaption></figure><p>Great, so our CRUD functionality is complete. Now let’s add in some styles so that it looks good. I have written all the CSS for this application inside index.css just to keep things simple. Here is all the CSS code you need-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/819b6646d972bc0cb55454455ef44ade/href">https://medium.com/media/819b6646d972bc0cb55454455ef44ade/href</a></iframe><p>With all the CSS code, here are the final changes for each of the components-</p><p>App.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b20af169b72b08ba626a8bce9ca4d3a/href">https://medium.com/media/6b20af169b72b08ba626a8bce9ca4d3a/href</a></iframe><p>PostForm.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1cb4dc39d490a3fd8b8e4cba9bc5ff5/href">https://medium.com/media/a1cb4dc39d490a3fd8b8e4cba9bc5ff5/href</a></iframe><p>Post.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37ac1dc68542efc13e6755808e18e483/href">https://medium.com/media/37ac1dc68542efc13e6755808e18e483/href</a></iframe><p>AllPost.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dae6f250d0df82b331a93dc569de818a/href">https://medium.com/media/dae6f250d0df82b331a93dc569de818a/href</a></iframe><p>EditComponent.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27c47836d109a7edeeea5fbf1f963b2a/href">https://medium.com/media/27c47836d109a7edeeea5fbf1f963b2a/href</a></iframe><p>Finally the postReducer.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cfe04ba9801f9b5c966b8d286a55c88/href">https://medium.com/media/2cfe04ba9801f9b5c966b8d286a55c88/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*titbUYUo9bMKMg_D5VWO3g.png" /><figcaption>After Adding some CSS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*xE86SvODuahkB96hdZNV7A.png" /><figcaption>After Adding some CSS</figcaption></figure><p>Here I have applied basic styles so that the app looks decent. You can modify it according to your needs. So if you have followed with me in this long blog post till the end then please congratulate yourself as now you know the core fundamentals of Redux. There are more advanced concepts that I did not go through like action-creators,middleware,combining multiple reducers and handling external API requests just to keep things simple. As always since this is my first blog post there can be some errors or mistakes so please don’t hesitate to point that out. If you like to challenge yourself then please extend this application even further. Try adding a comments feature or an authentication system where only authorized users can view the posts and a user can modify only his/her own posts,add support for upvotes and downvotes for each posts maybe add in some animations when you create a post or delete a post.There are so many things that you can do to improve this app.</p><p>Thanks for reading.</p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abb834d763c9" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/redux-a-crud-example-abb834d763c9">Redux-A CRUD Example</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>