<?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 Bhupendra Singh on Medium]]></title>
        <description><![CDATA[Stories by Bhupendra Singh on Medium]]></description>
        <link>https://medium.com/@bhupendra.nitt?source=rss-8e07e761ed19------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Tw6-pBdxw4uiV-hRHHawgg.png</url>
            <title>Stories by Bhupendra Singh on Medium</title>
            <link>https://medium.com/@bhupendra.nitt?source=rss-8e07e761ed19------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:56:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bhupendra.nitt/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[React hooks: useState]]></title>
            <link>https://medium.com/@bhupendra.nitt/react-hooks-usestate-b8e7d950b9ad?source=rss-8e07e761ed19------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8e7d950b9ad</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Bhupendra Singh]]></dc:creator>
            <pubDate>Fri, 12 Apr 2019 06:13:12 GMT</pubDate>
            <atom:updated>2019-04-12T06:13:12.765Z</atom:updated>
            <content:encoded><![CDATA[<p># Getting started with React hooks</p><p>I recently started reading about react hooks and want to congratulate team behind react hooks. The possibilites and power which hooks bring is really impressive.</p><p>This series is just to get started with react hooks and I will show you a very simple example how to use useState hook. I will be covering other hooks in coming posts.</p><p>In this example we will create a simple form which accepts Name and age in a form and validates if those values are present or not.</p><p>Let’s first take initial states:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38d5573515dc47a8412d3931b9f14ce4/href">https://medium.com/media/38d5573515dc47a8412d3931b9f14ce4/href</a></iframe><p>Initial value of value when this component is fresehly mounted is an empty string, setName is the function which will update state of `name`, this is equivalent of `setState({})`.</p><p>Similarly, we have initial values for `age` and `error`.</p><p>Our view is looks something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99ef970caabe71a5f5cef3bb0e302e08/href">https://medium.com/media/99ef970caabe71a5f5cef3bb0e302e08/href</a></iframe><p>We can enter values, we will see that new states are being set. We can also click on submit which will validate if `name` and `age` are present or not and set error message to be displayed.</p><p>Our simple form for validating a form looks like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/368eeadd5eb1d5a8ce90200437c5a008/href">https://medium.com/media/368eeadd5eb1d5a8ce90200437c5a008/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*4BgRGDgEleBsmUsrrOdvDQ.png" /><figcaption>End Result</figcaption></figure><p>This was a very simple example of useState hook.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8e7d950b9ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proxy server to bypass CORS.]]></title>
            <link>https://medium.com/@bhupendra.nitt/proxy-server-to-bypass-cors-106c1884ef04?source=rss-8e07e761ed19------2</link>
            <guid isPermaLink="false">https://medium.com/p/106c1884ef04</guid>
            <category><![CDATA[express]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[proxy-server]]></category>
            <dc:creator><![CDATA[Bhupendra Singh]]></dc:creator>
            <pubDate>Sun, 09 Dec 2018 04:25:50 GMT</pubDate>
            <atom:updated>2018-12-09T04:25:50.511Z</atom:updated>
            <content:encoded><![CDATA[<p>As a web-developer I have to daily work with APIs and a lot of time I want to use some APIs in my application but there’s always something which doesn’t allow me to access those requests, CORS. Cross Origin Requests are not allowed by a lot of servers and also browsers doesn’t support that.</p><p>Normally a request flow looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2y0zorHeRya0aPGISRd4w.png" /></figure><p>To overcome this barrier I created a proxy server which will work something like the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*itwotCKNPdTPMRJ2GTvi7A.png" /></figure><p>## What is happening here?</p><p>I have a proxy server. All reuqests from client will go to the proxy server. Proxy server will take request *massage* it with required data, like setting custom headers. Now Proxy server hits the main server and as the request is in correct format the main server accepts it in responds with whatever data is required. And voila it works.</p><p>Here’s the code snippet of proxy server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/deb4788cba428d88f5e59a9c9ce68715/href">https://medium.com/media/deb4788cba428d88f5e59a9c9ce68715/href</a></iframe><ul><li>One question how to set custom headers for the request at proxy server. I use a very simple technique which is analyzing the cURL request and based on that set up the custom header.</li></ul><p>A sample cURL request.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf04524f9f7fc949e1fdbdc866e3035a/href">https://medium.com/media/bf04524f9f7fc949e1fdbdc866e3035a/href</a></iframe><p>This is the very beginning of this project which does very specific task for me. It’s not robust enough to handle all type of requests(I will add support for that in due time). Feel free to suggest changes.</p><p>The working sample can be found below.</p><p><a href="https://github.com/bhupendra-nitt/node-proxy">bhupendra-nitt/node-proxy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=106c1884ef04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Replacing KeyMirror with 7 lines of code]]></title>
            <link>https://medium.com/@bhupendra.nitt/replacing-keymirror-with-7-lines-of-code-91825def7d15?source=rss-8e07e761ed19------2</link>
            <guid isPermaLink="false">https://medium.com/p/91825def7d15</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Bhupendra Singh]]></dc:creator>
            <pubDate>Tue, 09 Oct 2018 05:53:54 GMT</pubDate>
            <atom:updated>2018-10-11T06:58:19.172Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I got this hunch of replacing all the libraries/tools with my own custom made libraries/tools.</p><p>This is first one of many to follow. I am replacing keyMirror npm module which is essentially used to create an object with value as its key. While using React I used to declare constants with value as key itself.</p><p>For Example:</p><pre>{ MY_ACTION_ONE: &#39;MY_ACTION_ONE&#39;, MY_ACTION_TWO: &#39;MY_ACTION_TWO&#39; }</pre><p>This was tedious thing to do, which invoved a lot of copy paste until I came across this npm package called KeyMirror which essentially lets you create an object with values equal to its key names and much more. My use case was simple to have keys as values and having a npm package for that doesn’t make much sense especially if it is just few lines of code. So I spent 5 minutes to write this down and remove one npm package from my codebase.</p><p>Here’s the code which will help you with mirror your keys into its values.</p><pre>const keyMirror = (list) =&gt; {<br>  let newList= {};<br>  Object.keys(list).map(element =&gt; {<br>    var key = String(element);<br>    newList[key] = element<br>  });<br>return newList<br>}</pre><p>That’s it. You just need to pass the object with keys assigned `null` to them and you will receive you whole new object with keys having values as themselves.</p><p>Here’s an example how it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRXXV432B1a7CkQpzgOU-A.png" /></figure><p>Pretty straightforward. Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91825def7d15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost your GraphQL/Relay React app with Redux]]></title>
            <link>https://medium.com/scripbox-engineering/boost-your-graphql-relay-react-app-with-redux-f83a33faf871?source=rss-8e07e761ed19------2</link>
            <guid isPermaLink="false">https://medium.com/p/f83a33faf871</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[relay]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Bhupendra Singh]]></dc:creator>
            <pubDate>Tue, 13 Feb 2018 07:48:11 GMT</pubDate>
            <atom:updated>2018-02-13T07:48:11.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c391-6gexK2_-UIQjZRIeg.png" /></figure><p>At <a href="https://scripbox.com/">Scripbox</a>, we’ve been experimenting with <a href="http://graphql.org/">GraphQL</a> for internal purposes. We are huge fans of Redux. However, there is not much written about using the awesomeness of Redux alongside GraphQL. We have taken a stab at documenting our experience in marrying the development agility of GraphQL with painless state-management of Redux.</p><p>This post assumes we are fairly familiar with <a href="https://github.com/facebook/react">React</a> and <a href="https://github.com/reactjs/redux">Redux</a>.</p><h4>Why GraphQL?</h4><p>Clients often face the issue of over-fetching or under-fetching data. We need to have backing API endpoints for different representations of the same resource entity. This complexity is what GraphQL aims to solve.</p><p>GraphQL has inverted the equation in that, instead of a server dictating what attributes need to be served, the client gets to ask for information<br>that it needs.</p><p>As of now, Relay and Apollo Client are the prominent JS clients that can converse with a GraphQL backend.</p><p>We decided to go with <a href="https://facebook.github.io/relay/docs/en/prerequisites.html">Relay</a> as the framework API looked quite straight-forward.</p><h4>Relay</h4><p>There are 3 key parts of integrating Relay with React:</p><ol><li>Fetching the schema from server</li><li>Relay Environment</li><li>QueryRenderer</li></ol><h4>Schema</h4><p>GraphQL works on the basis of a shared schema between the server and client. We’re assuming we have the GraphQL server up and running. We need to ensure that we have the schema created as well.</p><p>Let us retrieve schema from the server.</p><pre>$ npm install -g get-graphql-schema<br>$ get-graphql-schema __RELAY_API_ENDPOINT__ &gt; ./schema.graphql</pre><p>Now that we have the schema, let’s setup the Relay environment.</p><h4>Environment</h4><pre><em>// src/createRelayEnvironment.js</em></pre><pre>const {<br>  Environment,<br>  Network,<br>  RecordSource,<br>  Store<br>} = require(&#39;relay-runtime&#39;);</pre><pre>function fetchQuery(operation, variables) {<br>  return fetch(___RELAY_API___, {<br>    method: &#39;POST&#39;,<br>    body: JSON.stringify({<br>      query: operation.text,<br>      variables,<br>    }),<br>  }).then(response =&gt; {<br>    return response.json();<br>  });<br>}<br>const network = Network.create(fetchQuery);<br>const source = new RecordSource();<br>const store = new Store(source);<br>export default new Environment({ network, store });</pre><p>We can observe that Network and Store are parameters used to initialise the environment. The environment orchestrates API requests and manages resource state within the Relay boundary.</p><h4>QueryRenderer</h4><p>The QueryRenderer will be solely responsible for bridging the environment and our views. QueryRenderer is React-aware as it resides in views. It is also schema-aware, in that, the actual attributes to be fetched for a resource is<br>defined in the QueryRenderer.</p><p>Here is the QueryRenderer inside our LikeComponent.</p><pre>import {<br>  QueryRenderer,<br>  GraphQL<br>} from &#39;react-relay&#39;;<br>import environment from &#39;../src/createRelayEnvironment&#39;;</pre><pre>class LikeComponent extends Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;QueryRenderer<br>          environment={environment}<br>          query={GraphQL`<br>            query LikeQuery() {<br>            user {<br>                  count<br>                  liked<br>                }<br>              }<br>          `}<br>          render={({ error, props }) =&gt; {<br>            if (error) {<br>              return &lt;div&gt;{ error.message }&lt;/div&gt;;<br>            } else if (props) {<br>              JSON.stringify(props.user)<br>              /&gt;;<br>            }<br>            return &lt;div className=&#39;loader&#39;/&gt;;<br>          }}<br>        /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><p>We are interested in fetching only count and liked for a user. Thanks to GraphQL, we don’t need to make any changes in the server to facilitate this as the schema created in the server already accounts for these attributes.</p><p>We need a way to tell the QueryRenderer what query to fire and how to handle the response. To address the former, we need to use a Query. We can notice the LikeQuery usage inside our QueryRenderer.</p><p>The Query abstraction prepares the attributes to be send across the network as required by GraphQL. This abstraction sits on top of Relay artefacts.</p><p>Relay artefacts are generated stubs that aids Query in preparing and sending the request payload. These artefacts are created by combing through the source files looking for *Query references and the schema.</p><p>Let us compile our Relay artefacts.</p><pre>$ npm install relay-compiler<br>$ relay-compiler — src ./src — schema ./schema.GraphQL</pre><p>At this point, we will find the artefacts under the __generated__ folder along with our QueryRenderer. We can inspect the artifacts to see how the GraphQL query is constructed.</p><h4>State, state, more state!</h4><p>Relay works well when managing client-server interactions; but not all interactions fall in this scope. We need state management for user-client interactions that might involve purely view changes where Relay has no<br>part to play. We can use the vanilla state given by React but that breaks the <a href="http://blog.mgechev.com/2015/05/15/flux-in-depth-overview-components">Flux philosophy</a>.</p><h3>Enter Redux</h3><p>Redux helps us manage state in an immutable fashion and adheres to the Flux philosophy. As immutability is baked in, there are fewer chances of our application ending up in an invalid state. Let us see how we can make Redux play well with GraphQL.</p><pre><em>// src/LikeComponent.js</em></pre><pre><a href="http://twitter.com/connect">@connect</a>(state =&gt; ({<br>  counter: state.SampleReducer.get(&#39;counter&#39;),<br>}))<br>class LikeComponent extends Component {<br>  static propTypes = {<br>    counter: PropTypes.number.isRequired,<br>   // from react-redux connect<br>    dispatch: PropTypes.func.isRequired,<br>  }<br>  render() {<br>    const {<br>    counter,<br>    dispatch,<br>    } = this.props;<br>    return (<br>      &lt;div&gt;<br>        &lt;QueryRenderer<br>          environment={environment}<br>          variables={{ after: (batchSize * (currentPage - 1)), first: batchSize }}<br>          query={GraphQL`<br>            query LikeQuery() {<br>             user {<br>                   userId<br>                   count<br>                   liked<br>                 }<br>              }<br>          `}<br>          render={({ error, props }) =&gt; {<br>            if (error) {<br>              return &lt;div&gt;{ error.message }&lt;/div&gt;;<br>            } else if (props) {<br>              { disptach(SampleAction.updateCounterValueWithServerValue(props.user.count)) }<br>              &lt;div className=&#39;Example&#39;&gt;<br>                &lt;p&gt;Like: { counter }&lt;/p&gt;<br>                &lt;button onClick={ () =&gt; dispatch(SampleActions.handleLikeButtonClick(props.user.liked))}&gt;<br>                   Like<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br>           /&gt;;<br>          }<br>            return &lt;div className=&#39;loader&#39;/&gt;;<br>          }}<br>        /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><p>When our Component is initialised it invokes QueryRenderer to get state of liked and the count. When we click the Like button the reducers are called via the Actions which mutate the state of the View Component and calls the render function.</p><pre>// src/LikeAction.js</pre><pre>updateCounterValueWithServerValue(count) {<br>  return {<br>    type: UPDATE_COUNTER,<br>    count<br>  }<br>}</pre><pre>handleLikeButtonClick(liked) {<br>  return {<br>    type: UPDATE_LIKE_UNLIKE,<br>    liked<br>  }<br>}</pre><pre>// <em>src/LikeReducer.js </em></pre><pre>const initialState = Map({<br>  counter: 0,<br>  liked: false<br>});</pre><pre>const actionsMap = {<br>  [UPDATE_LIKE_UNLIKE]: (state, action) =&gt; {<br>    const counter = action.liked ? state.get(&#39;counter&#39;) - 1 : state.get(&#39;counter&#39;) + 1;<br>    return state.merge(Map({<br>      counter,<br>    }));<br>  },<br>  [UPDATE_COUNTER]: (state) =&gt; {<br>    const counter = state.get(&#39;count&#39;);<br>    return state.merge(Map({<br>      counter<br>    }));<br>  }<br>};</pre><p>We have omitted the mutation call that updates the value in the server for brevity.</p><h4>Conclusion</h4><p>Our exploration is still in a nascent stage but we are optimistic about this approach. Please do let us know if we can improve this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f83a33faf871" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scripbox-engineering/boost-your-graphql-relay-react-app-with-redux-f83a33faf871">Boost your GraphQL/Relay React app with Redux</a> was originally published in <a href="https://medium.com/scripbox-engineering">scripbox-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>