<?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 Abhijeet Singh Khangarot on Medium]]></title>
        <description><![CDATA[Stories by Abhijeet Singh Khangarot on Medium]]></description>
        <link>https://medium.com/@abhi_khangarot?source=rss-310ba239dbe5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TJkw-Zrv8InP_-9i5xO_oA.jpeg</url>
            <title>Stories by Abhijeet Singh Khangarot on Medium</title>
            <link>https://medium.com/@abhi_khangarot?source=rss-310ba239dbe5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 18:24:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhi_khangarot/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[Building a hackernews clone with Hasura GraphQL Engine and React]]></title>
            <link>https://medium.com/@abhi_khangarot/building-a-hackernews-clone-with-hasura-graphql-engine-and-react-71a740f8af4?source=rss-310ba239dbe5------2</link>
            <guid isPermaLink="false">https://medium.com/p/71a740f8af4</guid>
            <dc:creator><![CDATA[Abhijeet Singh Khangarot]]></dc:creator>
            <pubDate>Sat, 04 Jan 2025 02:11:58 GMT</pubDate>
            <atom:updated>2025-01-04T02:11:58.762Z</atom:updated>
            <content:encoded><![CDATA[<p>Note: This is an old article that I published on Hasura blog <a href="https://hasura.io/blog/hackernews-tutorial-using-graphql-react-hasura-part1/">here</a>.</p><p>Here is how I used <strong>Hasura GraphQL Engine</strong> and <strong>React</strong> to build custom error pages in . The final code is hosted <a href="https://github.com/abhi40308/hackernews-clone">here</a>. Visit the Live demo <a href="https://hackernews-1919.herokuapp.com/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uj5oRbU1XoHpvpTlNR550g.png" /></figure><h3>Introduction</h3><p>We will be building a clone of the popular news website <a href="https://news.ycombinator.com/">HackerNews</a>. App will have the following features:</p><ul><li>Display a list of all posts</li><li>Users can create account (using Auth0 authentication)</li><li>Authenticated users can create new posts</li><li>Authenticated users can upvote posts</li><li>Realtime updates when other users upvote a post or create a new one (updating apollo cache)</li></ul><p><strong>Let’s Begin (Setup):</strong></p><p>First we will be building the frontend of our app using react. React is an open-source javascript library developed by facebook and open-source contributors.</p><p>To quickly start, we will create a basic react app with no build configuration using <a href="https://github.com/facebook/create-react-app"><strong>create-react-app</strong></a>. Run the following commands in terminal:</p><pre>$ npx create-react-app hackernews-clone<br>$ cd hackernews-clone<br>$ npm start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yAArr-4Yk28n46Sg" /></figure><p>Server will start and you should be able to see a welcome to react screen on <a href="http://localhost:3000/">http://localhost:3000</a>.</p><blockquote><strong>Note : npx</strong> is a <strong>npm</strong> package runner. The typical use is to download and run a package temporarily <strong>or</strong> for trials. create-react-app is an <strong>npm </strong>package that is expected to be run only once in a project’s lifecycle. Hence, it is preferred to use <strong>npx</strong> to install and run it in a single step. (<a href="https://stackoverflow.com/questions/50605219/difference-between-npx-and-npm">source</a>)</blockquote><p>To improve the project structure, let’s create two directories, both inside the src folder. The first is called components and will hold all our React components. Second one styles, that is for all the CSS files you’ll use.</p><p>Move the required jsx and css files to appropriate directories and change the references to these files in both index.js and App.js accordingly. Your directory structure should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*3R1_dJvTmBjRSkZOuOGtKA.png" /></figure><p>I’ll be using <a href="https://react-bootstrap.github.io/getting-started/introduction/"><strong>react-bootstrap</strong></a> package for the styling. Install the package using:</p><pre>$ npm install react-bootstrap bootstrap</pre><p>Make sure to add the CDN links to stylesheets in /public/index.html. Copy the links from <a href="https://react-bootstrap.github.io/getting-started/introduction/"><strong>here</strong></a>.</p><p>Also install <a href="https://github.com/apollographql/react-apollo"><strong>react-apollo</strong></a> GraphQL Client using the following command:</p><pre>$ npm install apollo-boost apollo-link-context @apollo/react-hooks @apollo/react-hoc graphql</pre><p><strong>Apollo Client</strong> helps you consume a <strong>GraphQL API </strong>from front-end. It’s designed to let you build UI components and write GraphQL queries/mutations/subscriptions, then pass it to our backend server and receive the incoming data. This will be more clear once we jump into the code.</p><p>Finally, we need the backend for our app. We are going to use <a href="https://hasura.io/"><strong>Hasura GraphQL Engine</strong></a><strong> </strong>to set up our backend without actually writing any backend code. It allows us to create tables in <a href="https://www.postgresql.org/"><strong>Postgres</strong></a> database and directly query and mutate the data using instant realtime GraphQL API. It’s that simple!</p><p>See <a href="https://docs.hasura.io/1.0/graphql/manual/getting-started/heroku-simple.html">this</a> guide to quickly get started with <strong>Hasura GraphQL engine</strong> and <strong>Postgres</strong> running on <strong>heroku</strong> with one click deployment.</p><p>Enough of context, let’s write some code!</p><h3>Setting up backend:</h3><p>Our Postgres Database structure :</p><pre>type Post {<br><strong>id</strong> - <em>integer, primary key<br></em><strong>description</strong> - <em>text<br></em><strong>url</strong> - <em>text<br></em><strong>created_at</strong> - <em>timestamp with time zone<br></em><strong>user_id</strong> - <em>text<br>}</em></pre><pre>type Users {<br><strong>name</strong> - <em>text<br></em><strong>last_seen</strong> - <em>timestamp with time zone<br></em><strong>id</strong> - <em>text, primary key<br></em>}<br><br>type Point {<br><strong>id</strong> - <em>integer, primary key<br></em><strong>user_id</strong> - <em>text<br></em><strong>post_id</strong> - <em>integer<br></em>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*ZMRb0Fkkt9disa_hz0AI_Q.png" /><figcaption>Database Structure</figcaption></figure><p><strong>Creating tables:</strong></p><p>Create the following tables : users table (id has type text)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*5fm6gppB61S-e-PjTB1NmA.png" /><figcaption>users table</figcaption></figure><p>post table (id has type integer(autoincrement)):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*ag3YzxUzCuSWfwCYE85zSw.png" /><figcaption>post table</figcaption></figure><p>Add the foreign key constraint from user_id column to users.id . Set Update and Delete Violation as restrict.</p><p>Create and object relationship by jumping to relationship section of post table, between user_id of posts and id of users table. This will let you query the information of user who created the post in a single fetch query. See <a href="https://docs.hasura.io/1.0/graphql/manual/schema/relationships/create.html#step-1-add-foreign-key-constraint">this</a> link for creating relationships through foreign key in hasura.</p><p>point table (id has type integer(autoincrement)):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*Lc5ZF5U8OCvJoHap9oeanA.png" /><figcaption>point table</figcaption></figure><p>Add foreign key and unique key as shown. user_id, post_id is a unique key as one user can upvote a post only once. It has foreign key relationship with both post table and users table.</p><p>Also add the object relationships in post table as shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*DVATHIXFBhqsuzFgyR5TUw.png" /></figure><p>These relationships will help us query the number of points for each post.</p><p>Now we will set up the permissions for the tables, so that only logged in users can do certain things. Set up the permissions as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*pxQnHBKVJeve8HHv6H2beQ.png" /><figcaption>point table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*PVTjD-5aHMt-vaM5Yyg5KA.png" /><figcaption>users table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*rzsmwNp7zsJg7wQkLydH3w.png" /><figcaption>post table</figcaption></figure><p>See <a href="https://docs.hasura.io/1.0/graphql/manual/auth/authorization/basics.html">access control basics</a> if you are not much familiar with access control and how it works in hasura.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*fMW5tiKHTyFw4udUE6Z9uQ.png" /><figcaption>Permissions</figcaption></figure><p>To make it less complicated, I have given all the row level permissions as without any checks and column level as all columns and aggregation queries (used to count number of points for a post). That’s it for now.</p><h3><strong>Implementing User Authentication :</strong></h3><p>We will firstly implement user authentication. We will be using JWT (JSON web tokens) for authentication. Let’s first create some basic header in our react app for showing login button.</p><p>Replace the contents of styles/index.css file as shown:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88c0b093387308f7427a0a1d56cf0a83/href">https://medium.com/media/88c0b093387308f7427a0a1d56cf0a83/href</a></iframe><p>These styles will be used throughout our app so you don’t have to worry about the styling.</p><p><strong>Setup Apollo GraphQL Client:</strong></p><p>Replace contents of App.js to use apollo graphQL client as shown below. (<a href="https://github.com/apollographql/react-apollo">See apollo github repository for more help</a>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09c323c95298e0ae35ccfa2285c852f0/href">https://medium.com/media/09c323c95298e0ae35ccfa2285c852f0/href</a></iframe><p>In line 15 change the uri to your GraphQL Endpoint on hasura, which you can find on hasura console (remember where you created tables). Here we have imported the header component which we will implement now.</p><p><strong>Create header component and use react-routes:</strong></p><p>We will use <a href="https://reacttraining.com/react-router/web/guides/quick-start">react-router</a> to implement single-page application behaviour. Install react-router using:</p><pre>$ npm install react-router-dom</pre><blockquote>React Router, and dynamic, client-side routing, allows us to build a single-page web application with navigation without the page refreshing as the user navigates. React Router uses component structure to call components, which display the appropriate information.</blockquote><blockquote>By preventing a page refresh, and using Router or Link, the flash of a white screen or blank page is prevented. This is one increasingly common way of having a more seamless user experience. (<a href="https://medium.com/@marcellamaki/a-brief-overview-of-react-router-and-client-side-routing-70eb420e8cde">source</a>)</blockquote><p>For using react-router in our app, we have to wrap whole app in BrowserRouter It is a context provider for routing, which provides several props necessary for routing (like match, location, history). See <a href="https://reactjs.org/docs/context.html">this</a> if you are unfamiliar with context. Replace the contents of index.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2629475d839b0e2906a0695474eccaa3/href">https://medium.com/media/2629475d839b0e2906a0695474eccaa3/href</a></iframe><p>Next, we will create a header component for navigation within app. Create a header.js file in components directory. The contents of header.js should be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e8cb4e4103720162bb2d5c74114f98f/href">https://medium.com/media/7e8cb4e4103720162bb2d5c74114f98f/href</a></iframe><p>Here we are creating a navbar similar to HackerNews navbar. Later we will add some routes to it for navigation. That’s it! We have successfully created a header navbar and used react-routes in our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qfQF5VUgdZe8-qL7NxPr8w.png" /><figcaption>Right now your app should look like this</figcaption></figure><h4><strong>Using Auth0 JWT for Authentication</strong></h4><p>The following figure quickly explains how JWT authentication works. Here, Application Server (our backend) needs to be configured to verify that the incoming JWT are created by the authentication server (Auth0).(<a href="https://medium.com/vandium-software/5-easy-steps-to-understanding-json-web-tokens-jwt-1164c0adfcec"><em>source</em></a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*K7fCPpaZiIeO5x5NVPMR4w.png" /></figure><p>We are using Auth0 as authentication server. It will create a JWT and pass to our react app. Then, using apollo client, we will send the auth_token (access_token in our case)to our backend (application server), i.e. Hasura GraphQL Engine. Hasura is needed to be configured to verify that incoming JWT is created by Auth0 authentication server.</p><p>Logging with Auth0 using hasura can be a cumbersome process, as it will require all three parts : apollo-client, hasura, and auth0. Unfortunately, apollo-client has pretty confusing docs at this time as they migrate from apollo-react to @apollo/react-hooks. Same with Auth0 , they are making new react-auth0-wrapper, @auth0/auth0-spa-js replacing the old sdk’s for auth0 (auth0-js), and some of the functionalities are no longer available (Ex. idToken cannot be accessed directly using new sdk for auth0, so we have to use accessToken, but hasura docs have not yet made the required changes)</p><p>So I will be assisting you with the whole login process with Auth0, using @apollo/react-hooks and @auth0/auth0-spa-js. We have to follow these steps:</p><p><strong>Auth0 JWT integration with Hasura</strong> : See <a href="https://docs.hasura.io/1.0/graphql/manual/guides/integrations/auth0-jwt.html">this</a> guide for Auth0 JWT Integration with Hasura and get the JWK (key for validation of incoming JWT). In Auth0 dashboard, set Allowed Callback URLs, Allowed Web Origins, Allowed Logout URLs to <a href="http://localhost:3000/">http://localhost:3000</a> and save changes.</p><p>You may also need to disable OIDC Conformant in Auth0 &gt; Applications &gt; Your_app &gt; Settings &gt; Advanced Settings. Once you have the key, next step is to activate the JWT mode in Hasura. Go to your heroku dashboard, choose our app and go to settings. Here you can see some Config Vars which we will set-up now. Add the config vars as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*TlJi8K1MQVp3qWo5Ga47fA.png" /></figure><p>Here, HASURA_GRAPHQL_ADMIN_SECRET key for the JWT mode to work. Put the key in HASURA_GRAPHQL_JWT_SECRETenvironment variable. Once you have added this, the GraphQL endpoints can only be queried using Authorization header or X-Hasura-Admin-Secret header.</p><p>Finally, set HASURA_GRAPHQL_UNAUTHORIZED_ROLE to anonymous because we do allow unauthenticated users to read some data.</p><blockquote><strong>Unauthorized role:</strong> used when access-key is not sent in access-key only mode or “Authorization” header is absent in JWT mode. Example: <strong>anonymous</strong>. Now whenever “Authorization” header is absent, request’s role will default to “anonymous”.</blockquote><p>Next step is to add rules in our Auth0 app. We will add 2 more rules to Auth0 app as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba4a803a99026a15ace908c47269f815/href">https://medium.com/media/ba4a803a99026a15ace908c47269f815/href</a></iframe><p>Here we are replacing idToken with accessToken . Basically, auth0 provides different types of tokens and the auth0-spa-js does not expose the idToken anymore, so we will use accessToken.</p><blockquote>Read more about tokens <a href="https://auth0.com/docs/tokens">here</a>.</blockquote><blockquote>The new SPA SDK only uses Authorization Code Grant + PKCE (not Implicit Grant anymore) Thus we have to use accessTokens in place of idTokens.(See <a href="https://community.auth0.com/t/how-to-obtain-id-token-with-auth0-spa-js/27574/3">this</a> thread).</blockquote><p>Add one more rule for keeping our postgres database and Auth0 users in sync:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/337ce63cbcbbc5c4e2ec2d01f75c3c51/href">https://medium.com/media/337ce63cbcbbc5c4e2ec2d01f75c3c51/href</a></iframe><p>Change admin_secret and url accordingly. Now, whenever a new user signs up or a user logs in, our hasura postgres database will be updated automatically to store the user information in our users table. See <a href="https://learn.hasura.io/graphql/hasura/authentication/4-user-sync-rule">this</a> for more details.</p><blockquote>Note: Here we are just doing a post request with graphql mutation queries, and we have x-hasura-admin-secret in header, thus the incoming request have full access to mutate the database.</blockquote><p>We also need to create a custom API in Auth0 Dashboard &gt; APIs which will point to our Hasura GraphQl API. Create a new api as shown below and give it any name. Change Identifier with your graphql endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*UHQPY0nudlodrN2-mfrFzA.png" /></figure><p><strong>Auth0 JWT integration with React App</strong>: Follow along with <a href="https://auth0.com/docs/quickstart/spa/react/01-login#configure-auth0">Auth0-react-quickstart</a> guide as reference to include Auth0 in react app. Configure Auth0 client by setting Allowed Callback URLs, Allowed Web Origins, Allowed Logout URLs to <a href="http://localhost:3000/">http://localhost:3000</a> and add the custom API if you haven’t done already. Now install auth0-spa-js :</p><p>$ npm install @auth0/auth0-spa-js</p><p>Now we will include react-auth0-wrapper in our app, which is a set of custom <a href="https://reactjs.org/docs/hooks-intro.html">react-hooks</a> that enable you to work with the Auth0 SDK. Create a new directory src/auth and add file react-auth0-wrapper.js populate it with code from <a href="https://auth0.com/docs/quickstart/spa/react/01-login#install-the-auth0-react-wrapper">here</a>.</p><p>Now add another file as auth/auth_config.json in src/auth . Populate auth_config.json with following code (change the values accordingly):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/136e186502b0eeed10f8c1f03ba2010b/href">https://medium.com/media/136e186502b0eeed10f8c1f03ba2010b/href</a></iframe><p>Now we are ready to include login functionality in our react app. Basically, we will be including a login button in header. This button will lead to login through Auth0 with redirect to our localhost once login/signup is completed. At the same time login/signup data will be updated in our users table in hasura backend due to the Auth0 rules we added earlier. Once the login is done, we will get the accessToken in JWT format using functions provided by Auth0 SDK in App.js . This accessToken will then be used as a authorization header in apollo client queries to backend, thus every query which goes to backend will have authorization header.</p><p>Firstly, change the contents of index.js to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0cb05e8b6c8b7c9c568007ba1a3bf42/href">https://medium.com/media/f0cb05e8b6c8b7c9c568007ba1a3bf42/href</a></iframe><p>Here, we are using the Auth0Provider which is a context provider for Auth0 client. Any children components will now have access to the Auth0 client.</p><p>Having provided the Auth0 client to our app, we now replace the contents of components/header.js file to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59e374eb09ab3f84a3ed01190e1ec95f/href">https://medium.com/media/59e374eb09ab3f84a3ed01190e1ec95f/href</a></iframe><p>We are using useAuth0 hook (line 8) to make use of various functions provided by Auth0. isAuthenticated is used to check if user is logged in or not. loginWithRedirect is used to login and redirect after login to specified redirect-url. user object has information about the current logged in user.</p><p>Here, if the user is logged in, we are showing the user info and logout button. If the user is logged out, we will just show login button. There is also submit button (line 33) which doesn’t do anything for now. We will use this to create new posts later. We have also given the link to user profile (line 38) which we will set up later.</p><p>Now we will make changes in our App.js to include Auth0 functionality. Change the contents of App.js to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b1432257d9a0877d884f28777cb38ce/href">https://medium.com/media/3b1432257d9a0877d884f28777cb38ce/href</a></iframe><p>We are using useState hook(line 20) to set initial accessToken value to empty string. If the user is logged in, the token is fetched from the Aut0 SDK client using getTokenSilently() (line 31). Notice that this function returns a Promise and is asynchronous. This function attempts to return the current access token. If the token is invalid, the token is refreshed silently before being returned from the function. If thetry block successfully gets executed, accessToken value is set to the JWT access-token from Auth0 (line 32).</p><p>The component re-renders when we get accessToken value. Thus after the async function has finished executing, we store the value of accessToken in state. The component re-renders and apollo-client gets the token value, thus re-rendering the whole ApolloProvider (context-provider) with new token value and the authentication header.</p><p>Once we have accessToken, we will use this to make requests to our backend using apollo client. See <a href="https://www.apollographql.com/docs/react/recipes/authentication/#header">apollo-docs</a> for apollo authentication using headers. Basically, we are passing the accessToken as authorization header(line 50), in our apollo queries. This client is then used inside the ApolloProvider (context provider) to provide the child elements access to apollo client created here.</p><p>Now, you should be able to login and logout of our app. Clear cache and login. You must be asked to give access to your auth0 tenant by our hasura backend. Give the access and you’re good to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FS70Pod9GMAnQQE-JtacA.png" /></figure><blockquote>Note : If you are facing errors, remember to not keep any dependency on <em>react-apollo</em> . <em>@apollo/react-hooks</em> must be used instead.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2GcSjZRIc2CJe_e-rlasXg.png" /><figcaption>Now, our app looks like this</figcaption></figure><h3>Implementing Post List and Upvote/Points(realtime updates of upvotes):</h3><p>We will implement a list of post and upvote post button. Create a new component components/PostList.js as :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abbd12db226cb34f4475c30d1f36d4f8/href">https://medium.com/media/abbd12db226cb34f4475c30d1f36d4f8/href</a></iframe><p>POSTS_LIST query(line 10) is being used to fetch details from post table in our database. We can fetch post description, url, id, user details who created the post, and also the number of upvotes/points in that post all in just one query. This is due to the object and array relationships we created on our post table earlier. useQuery (line 31) is a custom <a href="https://www.apollographql.com/docs/react/api/react-hooks/">apollo-client react hook</a>. We get the query data in data object (line 31) which is then passed as a prop to the Post component, which we will implement now.</p><p>Create a new component components/Post.js as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f11de545c192fd400a99893aa52b4fe/href">https://medium.com/media/3f11de545c192fd400a99893aa52b4fe/href</a></iframe><p>Two things are happening here: we are displaying the post information using props passed by parent component, and we are writing a GraphQl mutation to upvote posts.</p><p>Firstly, we are getting post information in props (line 18). This is used to display post description, url , points count and created_at .</p><p>Secondly, we are making a mutation UPVOTE_POST using useMutation hook. For upvoting a post, we need current logged in user’s userId and postId . userId is present in user object we get from useAuth0 hook (line19), which is being stored in loggedUserId variable (line 23). Once we get userId we will use it as variable in our mutation. See <a href="https://www.apollographql.com/docs/react/essentials/mutations/">apollo mutation</a> if you are unfamiliar with passing variables in mutation. The other variable in useMutation hook, refetchQueries is used to refetch the specified query after the mutation results have arrived. Thus, upvotes/points will be recorded and shown in real-time.</p><p>The mutation will insert a row in our point table, recording the upvote. Now, the same user cannot vote the given post again as (post_id + user_id) is the unique key for our point table, which we set earlier.</p><p>Finally, we need to import PostList component in App.js. Change your App.js file to make the following changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cadde821a403f7921c14783e7cab3324/href">https://medium.com/media/cadde821a403f7921c14783e7cab3324/href</a></iframe><p><a href="https://reacttraining.com/react-router/web/guides/basic-components">Switch</a> is a part of react-router which is used to match components with their paths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*093XKzBflfYuI4gIL07pbg.png" /><figcaption>Now, our react-app looks like this:</figcaption></figure><p>Try upvoting posts, and see the real-time updates in upvotes, thanks to refetchQueries . We haven’t yet implemented the user-profile and create-post functionality, so the submit button and user-profile links do not work. Next we will implement the same.</p><h3>Implementing Submit Post functionality :</h3><p>Create a new file as components/SecuredRoute.js as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/001f14b304a817ee9f2d55d5018f1b0d/href">https://medium.com/media/001f14b304a817ee9f2d55d5018f1b0d/href</a></iframe><p>This will help us to create some secured routes which can only be accessed if the user is logged-in. We will use secured routes while routing. Using secured route, if someone tries to access the url’s without logging-in, user will be redirected to login automatically.</p><p>Now, let’s create component components/NewPost.js as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecf1a8975408fe35adf52c9e7011654a/href">https://medium.com/media/ecf1a8975408fe35adf52c9e7011654a/href</a></iframe><p>This component will be used to submit a post. We have a form which has two input fields for description and url. We are using react state to store values of description, url and error (if mutation is not successful). The mutation accepts three variables which are being passed using variables parameter (line 34). If the mutation succeeds, we are using refetchQueries to refetch POSTS_LISTS query, thus implementing real-time updates of the list of post on the home page. If the mutation is successful, data in our backend postgres database gets updated with the new post data.</p><p>Let’s include route to new-post in our App.js :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55064c8eaa0b69310eee4288b6e7f157/href">https://medium.com/media/55064c8eaa0b69310eee4288b6e7f157/href</a></iframe><p>It is a secured route, so if we try to access localhost:3000/new-post without logging-in, we will be redirect to login screen.</p><p>Now, you can try submitting a post and see that the home page will be updated with the latest post. In case of any error in mutation, the error message will be shown on screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ggOvNuBlSsv9I0tNunq9Q.png" /><figcaption><a href="http://localhost:3000/new-post">http://localhost:3000/new-post</a> should look like this:</figcaption></figure><h3>Implementing User Profile :</h3><p>Let’s now implement user-profile. Create a new component components/Profile.js as :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c3866dd80d4c2e7a9d7980fe7ad10c2/href">https://medium.com/media/3c3866dd80d4c2e7a9d7980fe7ad10c2/href</a></iframe><p>We are getting user_id as props which will be used to query our backend database for user info, for the given user_id. The data is then rendered in return() . The props (user_id) here is being passed in form of url, and we are using props.match.params.id to get that prop. These props are provided by the react-router BrowserRouter context provider, which is included in our index.js file.</p><p>We need to now update App.js to redirect user to profile section:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c3373f39135d2fde8ac38d9c20d2b53/href">https://medium.com/media/4c3373f39135d2fde8ac38d9c20d2b53/href</a></iframe><p>Here, we are passing id as props (path={“/user/:id”}), which is accessed via props.match.params.id . This is a react-router way of passing prop. See <a href="https://reacttraining.com/react-router/web/example/url-params">this</a> example for more details.</p><p>Finally, we have our app ready with user-profiles section. You can navigate to user-profiles, create new posts and see real-time updates of new-posts, upvote posts and see real-time updates of upvotes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71a740f8af4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling GraphQL Errors with Hasura & React]]></title>
            <link>https://medium.com/@abhi_khangarot/handling-graphql-errors-with-hasura-react-3a15c4936aa9?source=rss-310ba239dbe5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a15c4936aa9</guid>
            <dc:creator><![CDATA[Abhijeet Singh Khangarot]]></dc:creator>
            <pubDate>Sat, 04 Jan 2025 02:11:09 GMT</pubDate>
            <atom:updated>2025-01-04T02:11:09.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*l-QNgKhyWkQODkK0RwzlMQ.png" /></figure><p>Note: This is an old article that I published on Hasura blog <a href="https://hasura.io/blog/handling-graphql-hasura-errors-with-react">here</a>.</p><p>Here is how I used <a href="https://hasura.io/"><strong>Hasura GraphQL Engine</strong></a> and <a href="https://github.com/apollographql/react-apollo"><strong>react-apollo</strong></a><strong> </strong>for error handling and to build custom error pages in a react app. The final code is hosted <a href="https://github.com/abhi40308/custom-error-pages-graphQL">here</a>.</p><h4>What you’ll learn</h4><p>This post explains different kinds of errors developers may encounter while working with <strong>Hasura, </strong>and how to handle those errors / show custom error pages on client side <strong>react app.</strong></p><h3>Introduction</h3><p><strong>REST</strong> API’s use various API response codes which are returned with every API request to tell the users/developers what happened to their request. This is kind of obvious to someone working with <strong>REST</strong>, but <strong>GraphQL</strong> doesn’t work that way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*PKSsyutJw1hIPztdbiZQgA.png" /><figcaption>Rest api response codes</figcaption></figure><p>GraphQL responses only contain status code 200 <em>by default</em>, and in case of an error, return an errors array with description of what went wrong. Non-200 response codes indicate that some issue occurred at the HTTP transport layer, not the GraphQL layer. See the sample errors array below:</p><pre>&quot;errors&quot;: [{<br>      &quot;message&quot;: &quot;Name for character with ID 1002 could not be fetched.&quot;,<br>      &quot;locations&quot;: [ { &quot;line&quot;: 6, &quot;column&quot;: 7 } ],<br>      &quot;path&quot;: [ &quot;hero&quot;, &quot;heroFriends&quot;, 1, &quot;name&quot; ]<br>  }]</pre><p>The <a href="https://graphql.github.io/graphql-spec/"><strong>GraphQL spec</strong></a> generally <a href="https://graphql.github.io/graphql-spec/June2018/#sec-Errors">discourages adding properties to error objects</a>, but does allow for it by nesting those entries in an extensions object.</p><blockquote>GraphQL services may provide an additional entry to errors with key extensions. This entry, if set, must have a map as its value. This entry is reserved for implementers to add additional information to errors however they see fit, and there are no additional restrictions on its contents. (<a href="https://graphql.github.io/graphql-spec/June2018/#sec-Errors">docs</a>).</blockquote><p>This extensions object is used by GraphQL servers (including Hasura) to add additional properties to the errors object. For example, sample errors array returned by hasura looks like this:</p><pre>“errors”: [{<br> “extensions”: {<br>   “path”: “$.selectionSet.post.selectionSet.name”,<br>   “code”: “validation-failed”<br> },<br>   “message”: “field \”name\” not found in type: ‘post’”<br> }]</pre><p>Hasura returns a extensions.code object which can be used to classify errors and show appropriate response on the client side. This post will use the same to show custom error-pages on react client using react-apollo. But first let’s learn about the common GraphQL errors and how they are handled in Hasura.</p><h3>GraphQL Errors</h3><p>Error handling is mainly done for the end users, for production apps. So while developers can understand the vague errors array returned by GraphQL API, end users cannot. Thus, it is important to show appropriate response to end users in case of errors.</p><p><strong>GraphQL Errors</strong> fall into the following types :</p><ul><li><strong>Server errors: </strong>These include errors like 5xx HTTP codes and 1xxx WebSocket codes. Whenever server error occurs, server is generally aware that it is on error or is incapable of performing the request. Server errors may also occur due to closing of websocket connection between client and server, which may happen due to various reasons (see <a href="https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent">CloseEvent</a> for different types of 1xxx error codes). No data is returned in this case as GraphQL endpoint is not reached.</li><li><strong>Client errors:</strong> These include errors like malformed headers sent by client, unauthorized client, request timeout, rate-limited api, request resource deleted, etc. All the client errors return 4xx HTTP codes. Same with server errors, no data is returned.</li><li><strong>Error in parse/validation phase of query</strong>: These include errors while parsing the GraphQL query. For example, if client sends malformed GraphQL request, i.e. syntax error. Or if the query does not pass GraphQL internal validation, i.e. client sent inputs that failed GraphQL type checking. In both these cases, no partial data can be returned. In case of <a href="https://graphql.org/learn/validation/">validation error</a>, errors array is returned showing what went wrong, while queries with syntax errors are usually not sent to GraphQL endpoint and are caught at the client side.</li><li><strong>Errors thrown within the resolvers</strong>: Resolver errors may occur due to lots of reasons, depending on the implementation of resolver functions. For example, errors like poorly written database queries, or errors thrown on purpose like restricting users from particular countries to access some data. Most importantly, these kind of errors can return partial data/fields that are resolved successfully alongside an error message.</li></ul><p>Some of these errors do not apply for <strong>Hasura GraphQL Engine</strong>. For example, resolver errors (unless you are writing custom resolvers, in which case you have to take care of the code being error-free).</p><p>Also, Hasura GraphQL engine may not work as expected and will throw unexpected errors if the tables/views tracked by the GraphQL engine are altered using <strong>psql</strong> or any other PostgreSQL client. For troubleshooting those errors, see <a href="https://docs.hasura.io/1.0/graphql/manual/troubleshooting/index.html">hasura docs</a>.</p><p>One more point to note, GraphQL queries/mutations can return partial data in case of errors depending on implementation (in case of resolver errors). But in Hasura, partial data is returned only if the query/mutation deals with <strong>remote schema</strong>, depending on the resolvers written by developers.</p><p>Now let’s jump into implementation of error pages.</p><h3>Custom Error Pages</h3><p>For implementing error pages, I will use <a href="https://github.com/abhi40308/hackernews-clone">this</a> boilerplate code to start with, which is a hackernews-clone app build by me. You can easily follow along and add error pages in your app accordingly. The final code is hosted <a href="https://github.com/abhi40308/custom-error-pages-graphQL">here</a>.</p><h4>404 resource not found error:</h4><p>Let’s first start by simply adding a 404 resource not found error page, which is shown when user goes to any unspecified route. This can be simply achieved using routing alone. In <a href="https://github.com/abhi40308/custom-error-pages-graphQL/blob/master/src/components/App.js">App.js</a>, we have to make the following changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3376140c56b3d6dcf46df8e8c319a674/href">https://medium.com/media/3376140c56b3d6dcf46df8e8c319a674/href</a></iframe><p>Notice that you just have to add a wild card Route with and asterisk(‘*’) in the end, which matches if any other routes does not match.</p><p>Now we can create the NotFound component as :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d110f150dd9a61f67f7fcbf3c3759598/href">https://medium.com/media/d110f150dd9a61f67f7fcbf3c3759598/href</a></iframe><p>We get a 404 error whenever user enters an unspecified route/url:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dyBJ8MYCAFDXF0PCh7yj5w.png" /><figcaption>Any unspecified route is matched with asterisk(*) and 404 page is shown</figcaption></figure><h4>Network Errors / Server Errors:</h4><p>Network Errors are errors that are thrown outside of your resolvers. If networkError is present in your response, it means your entire query was rejected, and therefore no data was returned. Any error during the link execution or server response is network error.</p><p>For example, the client failed to connect to your GraphQL endpoint, or some error occurred within your request middleware.</p><p>The best way to catch network errors is to do it on top-level using the <a href="https://www.npmjs.com/package/apollo-link-error"><strong>apollo-link-error</strong></a><strong> </strong>library. apollo-link-error can be used to catch and handle server errors, network errors, and GraphQL errors. apollo-link-error can also be used to do some custom logic when a GraphQL or Network error occurs.</p><p>Now let’s implement network-error page using apollo-link-error. In <a href="https://github.com/abhi40308/custom-error-pages-graphQL/blob/master/src/components/App.js">App.js</a>, we have to make the following changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0db90626a98e61899d5a9951458c1a66/href">https://medium.com/media/0db90626a98e61899d5a9951458c1a66/href</a></iframe><p>Note that in line 8, we have intentionally changed the GraphQL endpoint uri to replicate a network error. We defined onError which catches both graphQLErrors and networkErrors and allows us to do custom logic when error occurs. Every time networkError occurs, the if statement in line 18 is executed, and we redirect the user to a network-error page using react-router history prop (see line 20). In most simple terms, <a href="https://reacttraining.com/react-router/web/api/history">history</a> object stores session history, which is used by react-router to navigate to different paths.</p><p>We push the path network-error on history object, and we have defined the path in routes (line 32). Thus, when the if statement executes, the user is automatically redirected to /network-error url.</p><blockquote>See <a href="https://stackoverflow.com/questions/53539314/what-is-withrouter-for-in-react-router-dom">this</a> thread to better understand react-router and history object. Note that we are using withRouter in App.js to get access to the history object through props.</blockquote><p>We will now create NetworkError component as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9b9ae848001f3b403a73f9dcddd4d45/href">https://medium.com/media/f9b9ae848001f3b403a73f9dcddd4d45/href</a></iframe><p>We get a network error, whenever the client cannot connect to the server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlV-aup8Ev8zgXPgeX7Tvw.png" /><figcaption>Whenever a network error occurs, user is redirected to /network-error</figcaption></figure><h4>GraphQL Errors:</h4><p>Hasura provides <a href="https://docs.hasura.io/1.0/graphql/manual/api-reference/index.html">various API’s</a>, but our react client will make requests to the GraphQL API.</p><p><strong>Hasura GraphQL API</strong></p><p>All GraphQL requests for queries, subscriptions and mutations are made to the <a href="https://docs.hasura.io/1.0/graphql/manual/api-reference/graphql-api/index.html"><strong>Hasura GraphQL API</strong></a><strong>. </strong>All requests are <strong>POST</strong> requests to the <strong>/v1/graphql</strong> endpoint.</p><blockquote>The <strong><em>/v1/graphql</em></strong> endpoint returns HTTP 200 status codes for all responses.(<a href="https://docs.hasura.io/1.0/graphql/manual/api-reference/graphql-api/index.html">docs</a>)</blockquote><p>Any error that is thrown by the Hasura GraphQL API, will fall under <strong>GraphQL Errors. </strong>Hasura GraphQL API throws errors, returning an errors array having errors[i].extensions.code field with pre-defined codes. These codes can be used to classify errors and do custom logic accordingly.</p><blockquote>Note: Hasura GraphQL APIerrors-codes are not documented currently, see this <a href="https://github.com/hasura/graphql-engine/issues/2920">open issue</a> for more information.</blockquote><p><a href="https://www.npmjs.com/package/apollo-link-error">Apollo-link-error</a> and <a href="https://www.apollographql.com/docs/react/api/react-hooks/">apollo/react-hooks</a> make GraphQL error handling easy for us. By default, we want our app to display global error pages (for example, a page with message “oops something went wrong”) whenever we encounter some query-validation errors or data-exception errors. But we also want the flexibility to be able to handle an error in a specific component if we wanted to.</p><p>For example, if a user was trying to upvote an already upvoted post, we want to display an error message in-context with some notification bar, rather than flash over to an error page.</p><p><strong>Handling errors at top level:</strong></p><p>Top level errors can be handled using <strong>apollo-link-error</strong> library. For example, if we are trying to query a field which is not present, a validation-failed error would be returned by Hasura GraphQL API. Or trying to mutate a field with string value but the field accepts an integer, data-exception error will be thrown.</p><p>Example error responses returned by Hasura GraphQL API:</p><pre>{<br> “errors”: [{<br>    “extensions”: {<br>    “path”: “$.selectionSet.dogs.selectionSet.name”,<br>    “code”: “validation-failed”<br>   },<br>   “message”: “field \”name\” not found in type: ‘dogs’”<br> }]<br>}</pre><pre>{<br>  &quot;errors&quot;: [{<br>      &quot;extensions&quot;: {<br>        &quot;path&quot;: &quot;$.selectionSet.insert_dogs.args.objects&quot;,<br>        &quot;code&quot;: &quot;data-exception&quot;<br>      },<br>      &quot;message&quot;: &quot;invalid input syntax for integer: \&quot;a\&quot;&quot;<br>    }]<br>}</pre><p>These are errors for which developer is at fault, and the end-users will probably not understand what went wrong, if shown the above error messages. In other words, these error messages are meant to help developers. In such cases, it’s a good idea to use top-level error pages which shows a “something went wrong” message. We will implement the same using apollo-link-error.</p><p>In <a href="https://github.com/abhi40308/custom-error-pages-graphQL/blob/master/src/components/App.js">App.js</a>, we have to make the following changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59db6b424c185e518b70ee8abdfc050c/href">https://medium.com/media/59db6b424c185e518b70ee8abdfc050c/href</a></iframe><p>Every time a graphQLError occurs, if block in line 7 gets executed, which triggers the switch case with extensions.code as the switch expression, thus we can map error-codes to logic we want to perform. Note that I haven’t put a break statement after data-exception (line 10) as I want to show same error-page on both data-exception and validation-failed errors. We redirect end-user to /something-went-wrong route in case of these errors.</p><p>We will now create SomethingWentWrong component as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8dbe195752e3b629676a31f8bf2a42c/href">https://medium.com/media/f8dbe195752e3b629676a31f8bf2a42c/href</a></iframe><p>On validation-failed error, we get a “something went wrong” page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N1znO_eQwoawy8TYCSLg2w.png" /></figure><p><strong>Custom logic on certain errors:</strong></p><p>We can also do some custom logic in case of certain error rather than redirecting to error-pages.</p><p>For example, if the error occurs while validating JWT (jwt’s are used for authentication), or if the JWT has expired, we can write custom logic to refetch the JWT, and send back the api request. Errors array:</p><pre>{<br>  &quot;errors&quot;: [{<br>        &quot;extensions&quot;: {<br>        &quot;path&quot;: &quot;$&quot;,<br>        &quot;code&quot;: &quot;invalid-jwt&quot;<br>      },<br>      &quot;message&quot;: &quot;Could not verify JWT: JWSError (JSONDecodeError  \&quot;protected header contains invalid JSON\&quot;)&quot;<br>  }]<br>}</pre><pre>{<br>  &quot;errors&quot;: [{<br>        &quot;extensions&quot;: {<br>        &quot;path&quot;: &quot;$&quot;,<br>        &quot;code&quot;: &quot;invalid-jwt&quot;<br>      },<br>      &quot;message&quot;: &quot;Could not verify JWT: JWTExpired&quot;<br>  }]<br>}</pre><p>We will now write custom logic to handle these errors. In <a href="https://github.com/abhi40308/custom-error-pages-graphQL/blob/master/src/components/App.js">App.js</a>, we will make the following changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/140ca335e9578ae5370e24d606262f39/href">https://medium.com/media/140ca335e9578ae5370e24d606262f39/href</a></iframe><p>If the error-code is invalid-jwt, we refetch the JWT and try the API request again with new authorization header.</p><p>Here is a diagram of how the request flow looks like now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ude1Aln26EqKaW6RG11T_w.png" /><figcaption><a href="https://github.com/apollographql/apollo-link/tree/master/packages/apollo-link-error">source</a></figcaption></figure><p><strong>Handling Errors at component level:</strong></p><p>Errors can also be handled at component level, using functions provided by <a href="https://www.apollographql.com/docs/react/api/react-hooks">apollo-react-hooks</a>. There may be many reasons why we would want to handle errors at component level, for example, you may want to do some component-level logic, or display notifications if some particular error happens.</p><p>Here, we will be handling unique key constraint violation error, which is preventing a user to upvote an already upvoted post. Error array returned by Hasura GraphQL API:</p><pre>{<br>  “errors”:[{<br>      “extensions”: {<br>      “path”:”$.selectionSet.insert_point.args.objects”,<br>      ”code”:”constraint-violation”<br>    },<br>    ”message”:”Uniqueness violation. duplicate key value violates unique constraint \”point_user_id_post_id_key\””<br>  }]<br>}</pre><p>We have a post component which is using apollo/react-hooks function useMutation to mutate data on the server. When the above error is thrown, we catch the error and check for error-code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d9544bf9ad61c88110a9b6fe2d0679b/href">https://medium.com/media/5d9544bf9ad61c88110a9b6fe2d0679b/href</a></iframe><p>We can access errors array returned by Hasura using error.graphQLErrors. Note that the errors array may contain more than one error, so we are iterating over the array to check if the error code constraint-violation is present. If a match is found, we show a toast notification with error message.</p><p>I am using <a href="https://github.com/fkhadra/react-toastify">react-toastify</a> to show error notifications. Now, whenever user tries to upvote a post already upvoted by him/her, error notification pops up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WKL_uPWr43nS9osgQ_woyQ.gif" /><figcaption>Whenever user tries to upvote already upvoted post, error notification is shown</figcaption></figure><p><strong>Error policies ( apollo client )</strong></p><p>At last, if you are writing custom resolvers and using remote schemas with Hasura, your queries/mutation may return partial data with errors depending on implementation of the resolvers. In that case, apollo errorPolicy may come handy.</p><p>You can simply set errorPolicy on each request like so:</p><pre>const { loading, error, data } = useQuery(MY_QUERY, { errorPolicy: &#39;all&#39; });</pre><p>Now, if server returns partial data and error, both data and error can be recorded and shown to user. Check out <a href="https://www.apollographql.com/docs/react/data/error-handling/#error-policies">this</a> link to know more about errorPolicy.</p><h4>Acknowledgements:</h4><ul><li><a href="https://itnext.io/the-definitive-guide-to-handling-graphql-errors-e0c58b52b5e1">The Definitive Guide to Handling GraphQL Errors</a></li><li><a href="https://blog.apollographql.com/full-stack-error-handling-with-graphql-apollo-5c12da407210">Full Stack Error Handling with GraphQL + Apollo 🚀</a></li><li><a href="https://www.apollographql.com/docs/react/features/error-handling/">Error handling</a></li></ul><p>Error images: <a href="https://dribbble.com/mayankdhawan/projects/567197-UrbanClap-Empty-States">https://dribbble.com/mayankdhawan/projects/567197-UrbanClap-Empty-States</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a15c4936aa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a instagram clone with Hasura GraphQL Engine and React]]></title>
            <link>https://medium.com/@abhi_khangarot/building-a-instagram-clone-with-hasura-graphql-engine-and-react-65dfa842007f?source=rss-310ba239dbe5------2</link>
            <guid isPermaLink="false">https://medium.com/p/65dfa842007f</guid>
            <dc:creator><![CDATA[Abhijeet Singh Khangarot]]></dc:creator>
            <pubDate>Sat, 04 Jan 2025 02:07:57 GMT</pubDate>
            <atom:updated>2025-01-04T02:08:51.533Z</atom:updated>
            <content:encoded><![CDATA[<p>Note: This is an old article that I published on Hasura blog <a href="https://hasura.io/blog/instagram-clone-react-graphql-hasura-part1">here</a>.</p><p>Here is how I used <strong>Hasura GraphQL Engine</strong> and <strong>React</strong> to build a Instagram clone. The final code is hosted <a href="https://github.com/abhi40308/instagram-clone">here</a>. See live demo of the app <a href="https://instagram-1919.herokuapp.com/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*k0S607aazVPPJJt3A3cG0g.png" /></figure><h3>Introduction</h3><p>We will be building a clone of the popular website <a href="https://www.instagram.com/">Instagram</a>. App will have the following features:</p><ul><li>Users can create account (using Auth0 authentication)</li><li>Authenticated users can upload new posts</li><li>Authenticated users can like posts</li><li>Authenticated users can follow user accounts</li><li>Display posts in feed</li><li>Realtime updates when other users upvote a post, create a new post or follow user profile (using react state management and updating apollo cache)</li></ul><p><strong>Let’s Begin (Setup):</strong></p><p>First we will be building the frontend of our app using react. React is an open-source javascript library developed by facebook and open-source contributors.</p><p>To quickly start, we will create a basic react app with no build configuration using <a href="https://github.com/facebook/create-react-app"><strong>create-react-app</strong></a>. Run the following commands in terminal:</p><pre>$ npx create-react-app instagram-clone<br>$ cd instagram-clone<br>$ npm start</pre><p>Server will start and you should be able to see a welcome to react screen on <a href="http://localhost:3000/">http://localhost:3000</a>.</p><p>To improve the project structure, let’s create two directories, both inside the src folder. The first is called components and will hold all our React components. Second one styles, that is for all the CSS files you’ll use.</p><p>Move the required jsx and css files to appropriate directories and change the references to these files in both index.js and App.js accordingly. Your directory structure should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*3R1_dJvTmBjRSkZOuOGtKA.png" /></figure><p>I’ll be using <a href="https://react-bootstrap.github.io/getting-started/introduction/"><strong>react-bootstrap</strong></a> package for the styling. Install the package using:</p><pre>$ npm install react-bootstrap bootstrap</pre><p>Make sure to add the CDN links to stylesheets in /public/index.html. Copy the links from <a href="https://react-bootstrap.github.io/getting-started/introduction/"><strong>here</strong></a>.</p><p>Also install <a href="https://github.com/apollographql/react-apollo"><strong>react-apollo</strong></a> GraphQL Client using the following command:</p><pre>$ npm install apollo-boost apollo-link-context @apollo/react-hooks @apollo/react-hoc graphql</pre><p><strong>Apollo Client</strong> helps you consume a <strong>GraphQL API </strong>from front-end. It’s designed to let you build UI components and write GraphQL queries/mutations/subscriptions, then pass it to our backend server and receive the incoming data. This will be more clear once we jump into the code.</p><p>Finally, we need the backend for our app. We are going to use <a href="https://hasura.io/"><strong>Hasura GraphQL Engine</strong></a><strong> </strong>to set up our backend without actually writing any backend code. It allows us to create tables in <a href="https://www.postgresql.org/"><strong>Postgres</strong></a> database and directly query and mutate the data using instant realtime GraphQL API. It’s that simple!</p><p>See <a href="https://docs.hasura.io/1.0/graphql/manual/getting-started/heroku-simple.html">this</a> guide to quickly get started with <strong>Hasura GraphQL engine</strong> and <strong>Postgres</strong> running on <strong>heroku</strong> with one click deployment.</p><p>Enough of context, let’s write some code!</p><h3>Setting up backend:</h3><p>Our Postgres Database structure :</p><pre>type Post {<br>id - integer, primary key<br>caption - text<br>url - text<br>created_at - timestamp with time zone<br>user_id - text<br>}<br> <br>type User {<br>name - text<br>last_seen - timestamp with time zone<br>avatar - text<br>email - text<br>id - text, primary key<br>}</pre><pre>type Like {<br>id - integer, primary key<br>user_id - text<br>post_id - integer<br>}</pre><pre>type Follow {<br>id - integer, primary key<br>follower_id - text<br>following_id - text<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*0LE16wjtCcGKLywQ_VWloA.png" /><figcaption>Database Structure</figcaption></figure><p><strong>Creating tables:</strong></p><p>Create the following tables : User table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*rYD2kH2kNqZk7nsxRuRGxg.png" /><figcaption>User Table</figcaption></figure><p>Post table (id has type integer(autoincrement)):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*bzGWvQP0vsZXcFT3no_Oiw.png" /><figcaption>Post table</figcaption></figure><p>Add the foreign key constraint from user_id column to User.id . Set Update and Delete Violation as restrict.</p><p>Like table (id has type integer(autoincrement)):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*d9O9X7RJW_ZEMkocwkJieA.png" /><figcaption>Like table</figcaption></figure><p>Follow table (id has type integer(autoincrement)):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*dK9g8LMHPpegdXbR5OjskQ.png" /></figure><p>Create and object relationships by jumping to relationship section of tables. These relationships will help us to query data in a single query and also perform various kinds of aggregate functions like getting number of posts for every user. See <a href="https://docs.hasura.io/1.0/graphql/manual/schema/relationships/create.html#step-1-add-foreign-key-constraint">this</a> link for creating relationships through foreign key in hasura. We just need the following relationships.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*A6WctYDiZ-pugvZ4S-WXhQ.png" /><figcaption>User table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*E-LNfRlBFkzYm7NyHzlDVA.png" /><figcaption>Post table</figcaption></figure><p>Now we will set up the permissions for the tables, so that only logged in users can do certain things. Set up the permissions as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*CyTx8U_wALYn8tkWlsljLA.png" /><figcaption>User table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*KW1uvPNtnso4YoNDXP0-gw.png" /><figcaption>Post table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*8z0aVXzqjuZGXCjgTE4VfQ.png" /><figcaption>Like table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*fsUvezYibhYvhyLFXpul5A.png" /><figcaption>Follow table</figcaption></figure><p>See <a href="https://docs.hasura.io/1.0/graphql/manual/auth/authorization/basics.html">access control basics</a> if you are not much familiar with access control and how it works in hasura.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/0*eJ57QDwMr3xAaGvt.png" /></figure><p>To make it less complicated, I have given all the row level permissions as without any checks and column level as all columns and aggregation queries (used to count number of points for a post). That’s it for now.</p><h3>Implementing User Authentication :</h3><p>We will firstly implement user authentication. We will be using JWT (JSON web tokens) for authentication. Let’s first create some basic header in our react app for showing login button.</p><p>Replace the contents of styles/App.css file with <a href="https://github.com/abhi40308/instagram-clone/blob/master/src/styles/App.css">this</a> file. These styles will be used throughout our app so you don’t have to worry about the styling. Also download <a href="https://github.com/abhi40308/instagram-clone/blob/master/src/styles/sprite.png">this</a> file and place it in your styles/ directory. We will use this to show various buttons within our app.</p><p><strong>Setup Apollo GraphQL Client:</strong></p><p>Replace contents of App.js to use apollo graphQL client as shown below. (<a href="https://github.com/apollographql/react-apollo">See apollo github repository for more help</a>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7d422f8b296ee37d0438874da4d8ac3/href">https://medium.com/media/e7d422f8b296ee37d0438874da4d8ac3/href</a></iframe><p>In line 15 change the uri to your GraphQL Endpoint on hasura, which you can find on hasura console (remember where you created tables). Here we have imported the header component which we will implement now.</p><p><strong>Create header component and use react-routes:</strong></p><p>We will use <a href="https://reacttraining.com/react-router/web/guides/quick-start">react-router</a> to implement single-page application behaviour. Install react-router using:</p><pre>$ npm install react-router-dom</pre><blockquote><em>React Router, and dynamic, client-side routing, allows us to build a single-page web application with navigation without the page refreshing as the user navigates. React Router uses component structure to call components, which display the appropriate information.</em></blockquote><blockquote><em>By preventing a page refresh, and using Router or Link, the flash of a white screen or blank page is prevented. This is one increasingly common way of having a more seamless user experience. (</em><a href="https://medium.com/@marcellamaki/a-brief-overview-of-react-router-and-client-side-routing-70eb420e8cde"><em>source</em></a><em>)</em></blockquote><p>For using react-router in our app, we have to wrap whole app in BrowserRouter It is a context provider for routing, which provides several props necessary for routing (like match, location, history). See <a href="https://reactjs.org/docs/context.html">this</a> if you are unfamiliar with context. Replace the contents of index.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2629475d839b0e2906a0695474eccaa3/href">https://medium.com/media/2629475d839b0e2906a0695474eccaa3/href</a></iframe><p>Next, we will create a Header component for navigation within app. Create a Header.js file in components directory. The contents of Header.js should be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a91a6b989cdf68183e63b32d22e1f36/href">https://medium.com/media/4a91a6b989cdf68183e63b32d22e1f36/href</a></iframe><p>Here we are creating a navbar similar to Instagram navbar. Later we will add some routes to it for navigation. That’s it! We have successfully created a header navbar and used react-routes in our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LsBt6j6cztY6VnIMwpj2Mw.png" /><figcaption>Right now your app should look like this</figcaption></figure><h3>Using Auth0 JWT for Authentication</h3><p>The following figure quickly explains how JWT authentication works. Here, Application Server (our backend) needs to be configured to verify that the incoming JWT are created by the authentication server (Auth0).(<a href="https://medium.com/vandium-software/5-easy-steps-to-understanding-json-web-tokens-jwt-1164c0adfcec"><em>source</em></a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Ti0T7Y83xQeSWUkG.png" /></figure><p>We are using Auth0 as authentication server. It will create a JWT and pass to our react app. Then, using apollo client, we will send the auth_token(access_token in our case)to our backend (application server), i.e. Hasura GraphQL Engine. Hasura is needed to be configured to verify that incoming JWT is created by Auth0 authentication server.</p><p>Logging with Auth0 using hasura can be a cumbersome process, as it will require all three parts : apollo-client, hasura, and auth0. Unfortunately, apollo-client has pretty confusing docs at this time as they migrate from apollo-react to @apollo/react-hooks. Same with Auth0 , they are making new react-auth0-wrapper, @auth0/auth0-spa-js replacing the old sdk’s for auth0 (auth0-js), and some of the functionalities are no longer available (Ex. idToken cannot be accessed directly using new sdk for auth0, so we have to use accessToken, but hasura docs have not yet made the required changes)</p><p>So I will be assisting you with the whole login process with Auth0, using @apollo/react-hooks and @auth0/auth0-spa-js. We have to follow these steps:</p><p><strong>Auth0 JWT integration with Hasura</strong> : See <a href="https://docs.hasura.io/1.0/graphql/manual/guides/integrations/auth0-jwt.html">this</a> guide for Auth0 JWT Integration with Hasura and get the JWK (key for validation of incoming JWT). In Auth0 dashboard, set Allowed Callback URLs, Allowed Web Origins, Allowed Logout URLs to <a href="http://localhost:3000/">http://localhost:3000</a> and save changes.</p><p>You may also need to disable OIDC Conformant in Auth0 &gt; Applications &gt; Your_app &gt; Settings &gt; Advanced Settings. Once you have the key, next step is to activate the JWT mode in Hasura. Go to your heroku dashboard, choose our app and go to settings. Here you can see some Config Varswhich we will set-up now. Add the config vars as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/0*dFNjPuod0wOskB0Y.png" /></figure><p>Here, HASURA_GRAPHQL_ADMIN_SECRET key for the JWT mode to work. Put the key in HASURA_GRAPHQL_JWT_SECRETenvironment variable. Once you have added this, the GraphQL endpoints can only be queried using Authorization header or X-Hasura-Admin-Secret header.</p><p>Finally, set HASURA_GRAPHQL_UNAUTHORIZED_ROLE to anonymous because we do allow unauthenticated users to read some data.</p><blockquote><strong><em>Unauthorized role:</em></strong><em> used when access-key is not sent in access-key only mode or “Authorization” header is absent in JWT mode. Example: </em><strong><em>anonymous</em></strong><em>. Now whenever “Authorization” header is absent, request’s role will default to “anonymous”.</em></blockquote><p>Next step is to add rules in our Auth0 app. We will add 2 more rules to Auth0 app as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad5517ef0c3878695e3d01a66a8f8754/href">https://medium.com/media/ad5517ef0c3878695e3d01a66a8f8754/href</a></iframe><p>Here we are replacing idToken with accessToken . Basically, auth0 provides different types of tokens and the auth0-spa-js does not expose the idToken anymore, so we will use accessToken.</p><blockquote>Read more about tokens <a href="https://auth0.com/docs/tokens">here</a>.</blockquote><blockquote>The new SPA SDK only uses Authorization Code Grant + PKCE (not Implicit Grant anymore) Thus we have to use accessTokens in place of idTokens.(See <a href="https://community.auth0.com/t/how-to-obtain-id-token-with-auth0-spa-js/27574/3">this</a> thread).</blockquote><p>Add one more rule for keeping our postgres database and Auth0 users in sync:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20db411f610842e214f37241d24b9cfd/href">https://medium.com/media/20db411f610842e214f37241d24b9cfd/href</a></iframe><p>Change admin_secret and url accordingly. Now, whenever a new user signs up or a user logs in, our hasura postgres database will be updated automatically to store the user information in our users table. See <a href="https://learn.hasura.io/graphql/hasura/authentication/4-user-sync-rule">this</a> for more details.</p><blockquote><em>Note: Here we are just doing a post request with graphql mutation queries, and we have </em><em>x-hasura-admin-secret in header, thus the incoming request have full access to mutate the database.</em></blockquote><p>We also need to create a custom API in Auth0 Dashboard &gt; APIs which will point to our Hasura GraphQl API. Create a new api as shown below and give it any name. Change Identifier with your graphql endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*4MHkkdiDPV6gVmYk8LDvVw.png" /></figure><p><strong>Auth0 JWT integration with React App</strong>: Follow along with <a href="https://auth0.com/docs/quickstart/spa/react/01-login#configure-auth0">Auth0-react-quickstart</a> guide as reference to include Auth0 in react app. Configure Auth0 client by setting Allowed Callback URLs, Allowed Web Origins, Allowed Logout URLs to <a href="http://localhost:3000/">http://localhost:3000</a> and add the custom API if you haven’t done already. Now install auth0-spa-js :</p><p>$ npm install @auth0/auth0-spa-js</p><p>Now we will include react-auth0-wrapper in our app, which is a set of custom <a href="https://reactjs.org/docs/hooks-intro.html">react-hooks</a> that enable you to work with the Auth0 SDK. Create a new directory src/auth and add file react-auth0-wrapper.js populate it with code from <a href="https://auth0.com/docs/quickstart/spa/react/01-login#install-the-auth0-react-wrapper">here</a>.</p><p>Now add another file as auth/auth_config.json in src/auth . Populate auth_config.json with following code (change the values accordingly):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/136e186502b0eeed10f8c1f03ba2010b/href">https://medium.com/media/136e186502b0eeed10f8c1f03ba2010b/href</a></iframe><p>Now we are ready to include login functionality in our react app. Basically, we will be including a login button in header. This button will lead to login through Auth0 with redirect to our localhost once login/signup is completed. At the same time login/signup data will be updated in our User table in hasura backend due to the Auth0 rules we added earlier. Once the login is done, we will get the accessToken in JWT format using functions provided by Auth0 SDK in App.js . This accessToken will then be used as a authorization header in apollo client queries to backend, thus every query which goes to backend will have authorization header.</p><p>Firstly, change the contents of index.js to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0cb05e8b6c8b7c9c568007ba1a3bf42/href">https://medium.com/media/f0cb05e8b6c8b7c9c568007ba1a3bf42/href</a></iframe><p>Here, we are using the Auth0Provider which is a context provider for Auth0 client. Any children components will now have access to the Auth0 client.</p><p>Having provided the Auth0 client to our app, we now replace the contents of components/Header.js file to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcb0a39ae5b9c103f4161a88fa70d6d3/href">https://medium.com/media/dcb0a39ae5b9c103f4161a88fa70d6d3/href</a></iframe><p>We are using useAuth0 hook (line 7) to make use of various functions provided by Auth0. isAuthenticated is used to check if user is logged in or not. loginWithRedirect is used to login and redirect after login to specified redirect-url. user object has information about the current logged in user.</p><p>Here, if the user is logged in, we will take user to user-profile, which we will implement later. If the user is logged out, we will just show login button.</p><p>Now we will make changes in our App.js to include Auth0 functionality. Change the contents of App.js to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55c064a4fc9cf9fb8c26bdd696ecd5ba/href">https://medium.com/media/55c064a4fc9cf9fb8c26bdd696ecd5ba/href</a></iframe><p>We are using useState hook(line 22) to set initial accessToken value to empty string. If the user is logged in, the token is fetched from the Auth0 SDK client using getTokenSilently() (line 33). Notice that this function returns a Promise and is asynchronous. This function attempts to return the current access token. If the token is invalid, the token is refreshed silently before being returned from the function. If thetry block successfully gets executed, accessToken value is set to the JWT access-token from Auth0 (line 34).</p><p>The component re-renders when we get accessToken value. Thus after the async function has finished executing, we store the value of accessToken in state. The component re-renders and apollo-client gets the token value, thus re-rendering the whole ApolloProvider (context-provider) with new token value and the authentication header.</p><p>Once we have accessToken, we will use this to make requests to our backend using apollo client. See <a href="https://www.apollographql.com/docs/react/recipes/authentication/#header">apollo-docs</a> for apollo authentication using headers. Basically, we are passing the accessToken as authorization header(line 52), in our apollo queries. This client is then used inside the ApolloProvider(context provider) to provide the child elements access to apollo client created here.</p><p>Now, you should be able to login in our app. Clear cache and login. You must be asked to give access to your auth0 tenant by our hasura backend. Give the access and you’re good to go.</p><blockquote><em>Note : If you are facing errors, remember to not keep any dependency on </em><em>react-apollo . </em><em>@apollo/react-hooks must be used instead.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*qK0ak5CRf5fp-XNgUzPrUA.png" /><figcaption>Now our app looks like this</figcaption></figure><h3>Implementing Feed and Likes(realtime updates of Likes):</h3><p>We will implement a list of posts (feed) and a like button. Create a new component components/Feed.js as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/feb849e6338a4a5e50b10b9c52af2e46/href">https://medium.com/media/feb849e6338a4a5e50b10b9c52af2e46/href</a></iframe><p>POSTS_LIST query(line 8) is being used to fetch details from Post table in our database. We are querying the id of the post.useQuery (line 18) is a custom <a href="https://www.apollographql.com/docs/react/api/react-hooks/">apollo-client react hook</a>. We get the query data in data object (line 18) which is then passed as a prop to the Post component, which we will implement now.</p><p>Create a new component components/Post.js as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b46a7574b802abc57cd5c7d94cad2581/href">https://medium.com/media/b46a7574b802abc57cd5c7d94cad2581/href</a></iframe><p>Here, we are getting the props passed by Feed.js component and using the id prop, we are getting the complete post data using POST_INFO query. We are then rendering the data with styling in return statement. We are using function timeDifferenceForDate (line 68) for converting post.created_at to instagram style time. Now we need to implement this function. We are also importing Like component which takes care of like functionality, which we will implement later.</p><p>Create a new directory src/utils and create a new file TimeDifference.js as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa0d54752a02008ac1f8ecca972dc7f4/href">https://medium.com/media/fa0d54752a02008ac1f8ecca972dc7f4/href</a></iframe><p>It is just a utility function to convert the date-time data into our required format.</p><p>Now we will implement the Like component. Create a new file components/Like.js as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e146dee91bd12d5880e878d9ab0dd362/href">https://medium.com/media/e146dee91bd12d5880e878d9ab0dd362/href</a></iframe><p>Like components gets the post_id through props. Here we are writing two mutations and one query. FETCH_LIKES is used to fetch the number of likes from Post table. Also we are fetching whether the currently logged in user has already liked the post (line 15). LIKE_POST and DELETE_LIKE are used to insert a like in Like table and delete from Like table respectively.</p><p>We are storing countLikes (number of likes) and liked (if the user like the post) in state variables. As the state changes, the Like component re-renders which gives us updated view if user likes the post. If the user likes the post, we are showing a red heart, otherwise a white heart in UI. To implement this, we are checking value of liked (line 104) and rendering buttons accordingly. As the user likes the post, state changes (line 109), component re-renders, and like mutation occurs (line 108) which records the like in database, and number of likes is increased (line 110).</p><p>We have two mutations, submitting the like (line 58) and deleting the like(line 69). Both mutations uses refetchQueries argument (line 60) which is used to refetch the query FETCH_LIKES, thus updating the apollo cache with new values. This implements real-time likes.</p><p>We now have all the components in place to implement post feed. We need to change App.js to include Feed.js. Make following changes in your App.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/875c198c0f835303422871af1144390d/href">https://medium.com/media/875c198c0f835303422871af1144390d/href</a></iframe><p><a href="https://reacttraining.com/react-router/web/guides/basic-components">Switch</a> is a part of react-router which is used to match components with their paths. Insert some random data (posts) from Hasura Console in Post table try the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1qChvqhL2NB6BUhzAHUl9Q.png" /><figcaption>Now, our app looks like this</figcaption></figure><p>Try liking posts, and see the real-time updates in likes, thanks to refetchQueries . We haven’t yet implemented the user-profile, so the user profile links won’t work. Next we will implement the same.</p><h3>Implementing User Profile :</h3><p>Our user profile will have instagram style UI with user information on top and grid of posts uploaded by user at bottom. We will implement profile in two components, one will take care of rendering the main UI and the other will handle follow functionality.</p><p>Create a new component components/Profile.js as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc06a024df7571a9ac313a8355ecf086/href">https://medium.com/media/cc06a024df7571a9ac313a8355ecf086/href</a></iframe><p>We have three different queries, which will fetch all the basic data of user to be displayed. Notice that we could have called all the queries in one go, but while refetching the queries in case of follow mutation, we will have to refetch all the data to update cache, but only follow data would have changed. Thus we have made two separate queries for NUMBER_OF_FOLLOWERS(line 41) and NUMBER_OF_FOLLOWING(line 31). We have exported these queries, thus while implementing Follow component, we will be able to import and refetch the queries. This will become more clear once we start implementing follow functionality.</p><p>We are getting user_id as props which will be used to query our backend database for user info, for the given user_id. The data is then rendered in return() . The props (user_id) here is being passed in form of url, and we are using props.match.params.id to get that prop. These props are provided by the react-router BrowserRouter context provider, which is included in our index.js file.</p><p>Query USER_INFO is used to fetch data from table User and Post. In line 103, we are checking if currently displayed profile is same as the user currently logged-in. In that case we will show a Logout button. If the profile is of other users, we will show a Follow button instead. isLoggedUser function is used to check this condition. Follow button is implemented in Follow component which we will implement next.</p><p>Also we are using react-bootstrap rows to implement posts grid at the bottom of user profile, with three items per row (line 147). Each post item in the grid is a clickable link which leads to the respective post. Here, we are passing id as props through the url (to={“/post/” + post.id}) in line 148, which is accessed via props.match.params.id in the receiving component. This is a react-router way of passing prop. See <a href="https://reacttraining.com/react-router/web/example/url-params">this</a> example for more details.</p><p>Now, we will implement Follow component. Create a new file component/Follow.js as :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26e0ad4a8d2e3c719b54bf15c9f93f0b/href">https://medium.com/media/26e0ad4a8d2e3c719b54bf15c9f93f0b/href</a></iframe><p>This is identical to Like component. It is being fetched whether the currently logged in user follows the currently rendered profile using FETCH_FOLLWERS query. If data returned by FETCH_FOLLWERS is not empty, we will initially set followed state to true (line 115). Here, we are using a state followed(line 49) to check whether current user follows the displayed profile and a ref variable firstRun(line 52) which checks if the component is being rendered for the first time, which is useful as we want to do certain operations(line 112) on first time rendering of the component only, like setting the state followed to true or false initially depending on data returned from query FETCH_FOLLWERS.</p><p>Also we are using two mutations FOLLOW_USER and UNFOLLOW_USER which are inserting and deleting data from Follow table in our backend. Notice that both these mutations refetch three queries (line 66) in order to update apollo cache with correct data after the mutation. This automatically implements real-time data updates, where as soon as the mutation is performed, the number of followers of the displayed profile, and the number of following of the logged-in user updates.</p><p>Now, we will make the required changes in App.js. But firstly create a new file as components/SecuredRoute.js as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/001f14b304a817ee9f2d55d5018f1b0d/href">https://medium.com/media/001f14b304a817ee9f2d55d5018f1b0d/href</a></iframe><p>This will help us to create some secured routes which can only be accessed if the user is logged-in. We will use secured routes while routing. Using secured route, if someone tries to access the url’s without logging-in, user will be redirected to login automatically.</p><p>Now make the following changes in App.js :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3df61167a305e3fa4fcffa9bb34e43f9/href">https://medium.com/media/3df61167a305e3fa4fcffa9bb34e43f9/href</a></iframe><p>Now, you should be able to visit user profiles. Insert some sample data from Hasura console, and see the user profiles and follow functionality. See the real-time update in follow functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0xg-xmIeTbiGWz4MhA9Ulg.png" /><figcaption>User profile looks like this</figcaption></figure><h3>Implementing Submit Post functionality :</h3><p>Create a new file components/Upload.js as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fe9dfd9e3525518171fdaa0f0445f47/href">https://medium.com/media/1fe9dfd9e3525518171fdaa0f0445f47/href</a></iframe><p>SUBMIT_POST mutation is used to make a entry in our database table Post. We are using react-bootstrap modal to show a popup box to enter values of url and caption. Currently, image uploading is not supported, as we are not implementing any storage service to store images.</p><p>We have a form (line 48) which has two input fields for caption and url. We are using react state to store values of caption, url and error (if mutation is not successful). If the form is submitted, submitPost mutation is called which changes the data and refetchQueries updates data in apollo cache for queries POST_LIST and USER_INFO thus updating the feed and user profile respectively.</p><p>Now we will do the required changes in App.js :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/541086b27592a99e47bbf62f372f5e20/href">https://medium.com/media/541086b27592a99e47bbf62f372f5e20/href</a></iframe><p>If the user is authenticated, we will show a upload button which will open the following popup when clicked:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*N4HMEzfpxUPh8SiVnSMQWQ.png" /></figure><p>Finally, we have our app ready with upload post functionality. You can navigate to user-profiles, create new posts and see real-time updates of new-posts, likes and follows.</p><h4><strong>Acknowledgements</strong> :</h4><p>TimeDifference function: <a href="https://github.com/howtographql/react-apollo">https://github.com/howtographql/react-apollo</a></p><p>Few Styles taken from : <a href="https://pusher.com/tutorials/instagram-clone-part-1">https://pusher.com/tutorials/instagram-clone-part-1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65dfa842007f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brain MRI Segmentation using Deep Learning]]></title>
            <link>https://medium.com/kuzok/brain-mri-segmentation-using-deep-learning-217eb1bb5e82?source=rss-310ba239dbe5------2</link>
            <guid isPermaLink="false">https://medium.com/p/217eb1bb5e82</guid>
            <category><![CDATA[image-segmentation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[vgg16]]></category>
            <category><![CDATA[tumor-prediction]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Abhijeet Singh Khangarot]]></dc:creator>
            <pubDate>Mon, 16 Sep 2019 07:48:08 GMT</pubDate>
            <atom:updated>2019-09-16T07:48:08.892Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEsUe7C9klUYuOb22RrEew.jpeg" /><figcaption>BraTS Dataset Validation set prediction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*08NaDw27RgRVDf1wxlwKag.png" /></figure><p>This project was a runner-up in <a href="https://www.sih.gov.in/sih2019"><strong>Smart India Hackathon 2019</strong></a>. The problem statement was <strong>Brain Image Segmentation using Machine Learning </strong>given by Department of Atomic Energy, Government of India, in the <em>complex</em> <em>problem</em> <em>statements</em> category.</p><p>You can find complete project <a href="https://github.com/vaibhavshukla182/Brain-MRI-Segmentation">here</a>.</p><blockquote>The method segments 3D brain MR images into different tissues using <strong>fully convolutional network (FCN)</strong> and <strong>transfer learning</strong>.</blockquote><p>A <strong>Fully Convolutional neural network (FCN)</strong> is a normal CNN, where the last fully connected layer is substituted by another convolution layer with a large “receptive field”. The idea is to capture the global context of the scene (Tell us what we have in the image and also give some very rough idea of the locations of things).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*TpRmBWTay1vjWsb2dokFTQ.png" /><figcaption>Fully Convolutional network</figcaption></figure><p><strong>Transfer learning</strong> make use of the knowledge gained while solving one problem and applying it to a different but related problem. For example, knowledge gained while learning to recognize cars can be used to some extent to recognize trucks.</p><p>As compared to existing deep learning-based approaches that rely either on 2D patches or on fully 3D <strong>FCN</strong>, this method is way much faster: it only takes a few seconds, and only a single <strong>modality (T1 or T2)</strong> is required. In order to take the 3D information into account, all 3 successive 2D slices are stacked to form a set of 2D “color” images, which serve as input for the <strong>FCN</strong> pre-trained on <strong>ImageNet </strong>(a popular image database)<strong> </strong>for natural image classification.</p><p><a href="https://casemed.case.edu/clerkships/neurology/Web%20Neurorad/MRI%20Basics.htm"><strong>Modalities T1 and T2</strong></a> are radiology terms depending on types of tissues. In the dataset, we have both T1 weighted images and T2 weighted images, and we will use just single modality images to predict the results.</p><h4><strong>Preprocessing:</strong></h4><p>In order to take the 3D information into account, all 3 successive 2D slices are stacked to form a set of 2D color images, which serve as input for the FCN pre-trained on ImageNet for natural image classification.</p><ol><li>Histogram equalization (only for T1 modality)</li><li>Stack 3 continue slices as a RGB image</li><li>Flip and rotate for [$0,\pm 5,\pm 10,\pm 15$] for data augmentation</li><li>Crop to reduce background in image and ensure width and height can be divided by 16</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eE5KT3BirI_Ex6dwQCMYkQ.png" /></figure><h4>Network Architecture:</h4><p>Before jumping in the network architecture, lets first understand <strong>VGG16</strong>:</p><p><strong>VGG16:</strong></p><p>VGG16 is a convolutional neural network model built using Convolutions layers (used only 3*3 size ), Max pooling layers (used only 2*2 size), and Fully connected layers at end having a total of 16 layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*HzxRI1qHXjiVXla-_NiMBA.png" /><figcaption>VGG16 architecture</figcaption></figure><p>The input to cov1 layer is of fixed size 224 x 224 RGB image. The image is passed through a stack of convolutional (conv.) layers, where the filters were used with a very small receptive field: 3×3 (which is the smallest size to capture the notion of left/right, up/down, center). In one of the configurations, it also utilizes 1×1 convolution filters, which can be seen as a linear transformation of the input channels (followed by non-linearity). The convolution stride is fixed to 1 pixel; the spatial padding of conv. layer input is such that the spatial resolution is preserved after convolution, i.e. the padding is 1-pixel for 3×3 conv. layers. Spatial pooling is carried out by five max-pooling layers, which follow some of the conv. layers (not all the conv. layers are followed by max-pooling). Max-pooling is performed over a 2×2 pixel window, with stride 2.</p><p>Three Fully-Connected (FC) layers follow a stack of convolutional layers (which has a different depth in different architectures): the first two have 4096 channels each, the third performs 1000-way ILSVRC classification and thus contains 1000 channels (one for each class). The final layer is the soft-max layer. The configuration of the fully connected layers is the same in all networks.</p><p>All hidden layers are equipped with the rectification (ReLU) non-linearity. It is also noted that none of the networks (except for one) contain Local Response Normalisation (LRN), such normalization does not improve the performance on the ILSVRC dataset, but leads to increased memory consumption and computation time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vz5n812l-J37a5wLxKbD8A.png" /></figure><p><strong>Our model:</strong></p><p>We rely on the 16 layers <strong>VGG</strong> network pre-trained on millions of natural images in <strong>ImageNet</strong> for image classification. For our application, we discard the fully connected layers at the end of VGG network, and keep the 5 stages of convolutional parts called “<em>base network</em>”. This base network is mainly composed of convolutional layers, Rectified Linear Unit (ReLU) layers for non linear activation function, and max pooling layers between two successive stages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*6wg7cSqVE3j-xdcQxk-Z3Q.png" /><figcaption>We discard the red-part(fully connected layers) of VGG16</figcaption></figure><p>The four max pooling layers divide the base network into five stages of fine to coarse feature maps. We add specialized convolutional layers (with a 3 × 3 kernel size) with K (e.g. K = 16) feature maps after the convolutional layers at the end of each stage. We resize all the specialized layers to the original image size, and concatenate them together. A last convolutional layer with kernel size 1 × 1 is appended at the end that combines linearly the fine to coarse feature maps in the concatenated specialized layers, to produce the final segmentation result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*K2uxoDX-OdHjch55JZcaKQ.png" /><figcaption>Model architecture</figcaption></figure><p>Simply put, we stack successive 2D slices of a 3D volume to form a set of 2D “color” images, these 2D images constitute the input of a <strong>FCN</strong> based on <strong>VGG</strong> network, pre-trained on the <strong>ImageNet</strong> dataset. We discard the fully connected layers, and we add specialized convolutional layers at the end of each of the five convolutional stages in <strong>VGG</strong> network. A linear combination of these specialized layers (i.e. fine to coarse feature maps) results in the final segmentation.</p><h3>Why our model?</h3><ul><li>Since we are using transfer learning, a novel approach in this field, so we do not need to train our model from scratch which makes it very fast in training in comparison to other models.</li><li>Stacking 3 successive 2D slices allows us to make a RGB image, another novel idea.This representation enables us to incorporate some 3D information, while avoiding the expensive computational and memory requirements of fully 3D FCN.</li><li>Using Transfer Learning we do not need many training images, so we could train our model very well only on a few training images.</li><li>We are also using traditional data augmentation methods like rotating, cropping and flipping the images in training set for improving our model.</li></ul><h3>Results:</h3><p>We used <a href="https://www.med.upenn.edu/sbia/brats2018/registration.html"><strong>BraTS 2018</strong></a> dataset. The dataset contains <strong>.nii</strong> files, which are basically 3d images having layers of stacked 2d images. We are using <a href="http://ric.uthscsa.edu/mango/papaya.html"><strong>Papaya viewer</strong></a><strong> </strong>integrated into <strong>django</strong> app for input and showing prediction. The app takes the input as zip file, unzips and runs the model on it and shows the prediction.</p><p>Giving input and prediction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_CXHPZUiJ2WlQUkLyuCORg.gif" /><figcaption>Giving input (upload a zip of .nii file)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lV2om7JFvxIaan-txvjGsA.png" /><figcaption>Output</figcaption></figure><p>Results comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ag8uT2Zxk7SPp7f4H0ZJg.jpeg" /><figcaption>Comparison between actual and predicted results</figcaption></figure><h4>Contributors and acknowledgements:</h4><p><a href="https://github.com/vaibhavshukla182/">Vaibhav Shukla</a><br><a href="https://github.com/abhi40308">Abhijeet Singh</a><br><a href="https://github.com/blackbird71SR">Omkar Ajnadkar</a><br><a href="https://github.com/govind51">Govind Singh Rajpurohit</a><br><a href="https://github.com/Ratna04priya">Ratna Priya</a><br><a href="https://github.com/Killer2499">Sanath Singavarapu</a></p><p>The method we use comes from this paper: <a href="https://www.lrde.epita.fr/wiki/Publications/xu.17.icip">From neonatal to adult brain mr image segmentation in a few seconds using 3d-like fully convolutional network and transfer learning</a></p><p>vgg16 architecture : <a href="https://neurohive.io/en/popular-networks/vgg16/">https://neurohive.io/en/popular-networks/vgg16/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=217eb1bb5e82" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kuzok/brain-mri-segmentation-using-deep-learning-217eb1bb5e82">Brain MRI Segmentation using Deep Learning</a> was originally published in <a href="https://medium.com/kuzok">Kuzok</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hand Gesture Recognition using Deep Learning]]></title>
            <link>https://medium.com/kuzok/hand-gesture-recognition-using-deep-learning-8435d11c548a?source=rss-310ba239dbe5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8435d11c548a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[hand-gesture]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Abhijeet Singh Khangarot]]></dc:creator>
            <pubDate>Sat, 14 Sep 2019 01:18:21 GMT</pubDate>
            <atom:updated>2019-09-15T15:11:08.274Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a03q5JdiJgovQ9Hp" /><figcaption>Hand gesture recognition application in gaming</figcaption></figure><p>As we know, the vision-based technology of hand gesture recognition is an important part of <strong>human-computer interaction (HCI)</strong>. In the last decades, keyboard and mouse have played a significant role in human-computer interaction. However, owing to the rapid development of hardware and software, new types of HCI methods have been required. In particular, technologies such as speech recognition and gesture recognition receive great attention in the field of HCI.</p><p><strong>Gesture</strong> is a symbol of physical behaviour or emotional expression. It includes body gesture and hand gesture. Gesture can be used as a tool of communication between computer and human.</p><p>Gesture recognition is greatly different from the traditional hardware based methods and can accomplish human-computer interaction. Gesture recognition determines the user intent through the recognition of the gesture or movement of the body or body parts. In the past decades, many researchers have strived to improve the hand gesture recognition technology. Hand gesture recognition has great value in many applications such as augmented reality (virtual reality), sign language interpreters for the handicapped, and robot control.</p><p>The process of hand gesture recognition is described as follows:</p><ol><li>First, the raw data is created using webcam. Images of hands are taken and stored.</li><li>This data is then preprocessed, converting it to 50X50X1 binary format. Images collected are converted to numpy arrays. Data augmentation is used to make more instances of data and make the data more scattered.</li><li>Model training consists of three parts:</li></ol><ul><li>Convolution</li><li>Polling</li><li>Flattening</li></ul><p>Finally model is trained and is ready for new data to be classified.</p><h4>The Proposed Method for Hand Gesture Recognition</h4><p><strong>Data creation:</strong></p><p>Data includes images of hand gestures those have been taken from webcam using a python script.</p><p>Each class has 1200 images</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*_8A906s32bMZpsyBd3IAxw.png" /><figcaption>Sample raw data image taken from webcam</figcaption></figure><p><strong>Data preprocessing:</strong></p><p>Collected images are now prepared for training. Size of each image is 50x50x1 in binary format. Image collected is converted to numpy arrays to make this suitable for tensor processing in training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*JunW_IMxD5UhQNi1E-WRrA.png" /></figure><p>Since training data is very less therefore data is augmented which is explained below.</p><p><strong>Data Augmentation:</strong></p><p>Data augmentation is a way we can reduce overfitting on models, where we increase the amount of training<strong> </strong>data using information only in our training data. The field of data augmentation is not new, and in fact, various data augmentation techniques have been applied to specific problems.</p><pre>datagen = ImageDataGenerator(featurewise_center=True,<br>featurewise_std_normalization=True,<br>rotation_range=20,<br>width_shift_range=0.2,<br>height_shift_range=0.2,<br>horizontal_flip=True)</pre><p><strong>Model Training:</strong></p><p>All the classes has been trained using deep learning.Libraries included:</p><pre>import keras<br>from keras.models import Sequential<br>from keras.layers.normalization import BatchNormalization<br>from keras.layers.convolutional import Conv2D<br>from keras.layers.core import Activation , Dense , Dropout , Flatten<br>from keras.layers import AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D, GlobalAveragePooling2D<br>from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img<br>from keras import backend as K<br>import numpy as np<br>from keras.utils import np_utils<br>from keras import optimizers<br>from keras.layers import BatchNormalization<br>from keras.callbacks import ModelCheckpoint<br>from keras.models import load_model<br>from utils import get_data , get_no_of_classes , get_image_size<br>import matplotlib.pyplot as plt<br>import math<br>import h5py as h5py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*BNmk5rkmZH4ENin-NIbu_A.png" /><figcaption>Network Architecture</figcaption></figure><p>It consists of three parts -</p><ul><li>Convolution</li><li>Polling</li><li>Flattening</li></ul><p>The primary purpose of Convolution is to extract features from the input image. Convolution preserves the spatial relationship between pixels by learning image features using small squares of input data.</p><pre>model.add(Conv2D(32, (5,5), input_shape=(input_size[0], input_size[1], 1), activation=’relu’))</pre><pre>keras.layers.Conv2D(filters,kernel_size,data_format=None,activation=None)</pre><ul><li><strong>filters</strong>: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution).</li><li><strong>kernel_size</strong>: An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions.</li></ul><p>Since every image can be considered as a matrix of pixel values. Consider a 5 x 5 image whose pixel values are only 0 and 1 (note that for a grayscale image, pixel values range from 0 to 255, the green matrix below is a special case where pixel values are only 0 and 1):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/127/1*vW8UV8I_-MciWPrlRgNzrg.png" /></figure><p>Also, consider another 3 x 3 matrix as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/74/1*Ikb3iFk1w3DQdW6lRQ6oWQ.png" /></figure><p>Then, the Convolution of the 5 x 5 image and the 3 x 3 matrix can be computed as shown in the animation below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*ZCjPUFrB6eHPRi4eyP6aaA.gif" /></figure><p>The obtained matrix is also known as the feature map. An additional operation called ReLU is used after every Convolution operation.</p><p>The next step is <strong>pooling</strong>.</p><p><strong>Pooling</strong> (also called subsampling or downsampling) reduces the dimensionality of each feature map but retains the most important information. In case of <strong>Max Pooling</strong>, we define a spatial neighbourhood (for example, a 2×2 window) and take the largest element from the rectified feature map within that window. Instead of taking the largest element we could also take the average (Average Pooling) or sum of all elements in that window. In practice, Max Pooling has been shown to work better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ciDgQEjViWLnCbmX-EeSrA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*yJ3Vjoro_gb-SJt284Yz4w.png" /><figcaption>max pooling</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*J4ZMfEO0G9hxF6CAeH2x_w.png" /><figcaption>Convolution then pooling</figcaption></figure><p>After pooling comes flattening. Here the matrix is converted into a linear array so that to input it into the nodes of our neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*DKwXUECUF8TC6lOmdEY9-A.png" /></figure><p>After that those linear outputs are converted to number of output classes.</p><p>Next step is <strong>training</strong> the model:</p><pre>Using TensorFlow backend.<br>preparing all images as numpy arrays …<br>total image available 7200<br>no of training images: 5760<br>no of test images: 720<br>no of validation images: 720<br>Train on 5760 samples, validate on 720 samples<br>Epoch 1/5<br>5728/5760 [============================&gt;.] — ETA: 0s — loss: 0.6663 — acc: 0.3317 — val_loss: 0.1562 — val_acc: 0.3317<br>Epoch 2/5<br>5728/5760 [============================&gt;.] — ETA: 0s — loss: 0.1008 — acc: 0.4288 — val_loss: 0.0487 — val_acc:0.4489<br>Epoch 3/5<br>5728/5760 [============================&gt;.] — ETA: 0s — loss: 0.0457 — acc: 0.5595 — val_loss: 0.0258 — val_acc:0.5433<br>Epoch 4/5<br>5728/5760 [============================&gt;.] — ETA: 0s — loss: 0.0282 — acc: 0.72000 — val_loss: 0.0167 — val_acc: 0.73000<br>Epoch 5/5<br>5728/5760 [============================&gt;.] — ETA: 0s — loss: 0.0203 — acc: 0.8498 — val_loss: 0.0120 — val_acc: 0.8555<br>accuracy : 85.55%</pre><p>Now the model is ready for giving output on new images.</p><p>This model can be connected to raspberry pi for glowing LED’s based on different hand gestures or doing other mechanical work as shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*_8MDC26L-yPeiLMMfzEifw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8435d11c548a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kuzok/hand-gesture-recognition-using-deep-learning-8435d11c548a">Hand Gesture Recognition using Deep Learning</a> was originally published in <a href="https://medium.com/kuzok">Kuzok</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[News documents clustering using python (latent semantic analysis)]]></title>
            <link>https://medium.com/kuzok/news-documents-clustering-using-python-latent-semantic-analysis-b95c7b68861c?source=rss-310ba239dbe5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b95c7b68861c</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Abhijeet Singh Khangarot]]></dc:creator>
            <pubDate>Sun, 24 Mar 2019 13:13:07 GMT</pubDate>
            <atom:updated>2019-09-13T23:56:32.515Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This post was published in </em><a href="https://mc.ai/news-documents-clustering-using-python-latent-semantic-analysis/"><em>mc.ai</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*t8UTVAEFMuW3tglAWzjsgA.png" /><figcaption>Result after clustering 10000 documents (each dot represents a document)</figcaption></figure><blockquote><strong>TLDR</strong>: News documents clustering using latent semantic analysis. Used LSA and K-means algorithms to cluster news documents and visualized the results using UMAP (Uniform Manifold Approximation and Projection).</blockquote><blockquote>Considering the frequency(tf-idf) of important words in the news documents, the news documents are clustered where the related documents are shown using the same color which can be seen in the screenshots in the end. The color is decided by using k-means(running k-means on data separately and giving integer values to each documents based on k-means similarity results) and the actual positioning of documents(each document is represented by a dot on the graph) is achieved by applying LSA, thus verifying the results obtained using k-means.</blockquote><p>In this article, I will explain how to cluster and find similar news documents from a set of news articles using <a href="https://en.wikipedia.org/wiki/Latent_semantic_analysis"><strong>latent semantic analysis</strong></a> (LSA), and comparing the results obtained by LSA vs results obtained by <a href="https://en.wikipedia.org/wiki/K-means_clustering"><strong>k-means</strong></a><strong>,</strong> and visualising the data using <a href="https://umap-learn.readthedocs.io/en/latest/"><strong>UMAP</strong></a>.</p><p><a href="https://en.wikipedia.org/wiki/Latent_semantic_analysis"><strong>Latent Semantic Analysis</strong></a> is a technique for creating a vector representation of a document. Having a vector representation of a document gives you a way to compare documents for their similarity by calculating the distance between the vectors. This in turn means you can do handy things like classifying documents to determine which of a set of known topics they most likely belong to.</p><p>You can see the final code on <a href="https://github.com/abhi40308/News-Documents-Clustering">github</a>.</p><h3><strong>Data Reading</strong></h3><p>Firstly importing some necessary modules:</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import sys<br>import nltk<br>nltk.download(&#39;stopwords&#39;)<br>from nltk.corpus import stopwords<br># from bs4 import BeautifulSoup as Soup <br># Beautiful soup can be used to parse xml/html data, depends on the type of data<br>import json</pre><p>Sample data available to me:</p><pre>{&quot;id&quot;: &quot;b2e89334-33f9-11e1-825f-dabc29fd7071&quot;, &quot;article_url&quot;: &quot;<a href="https://www.washingtonpost/">https://www.washingtonpost</a> ........ &quot;source&quot;: &quot;The Washington Post&quot;}<br>{&quot;id&quot;: &quot;749ec5b2-32f5-11e1-825f-dabc29fd7071&quot;, &quot;article_url&quot;: &quot;<a href="https://www.washingtonpos/">https://www.washingtonpos</a>  ........ &quot;source&quot;: &quot;The Washington Post&quot;}<br>{&quot;id&quot;: &quot;69654742-33d7-11e1-825f-dabc29fd7071&quot;, &quot;article_url&quot;: &quot;<a href="https://www.washingtonpost/">https://www.washingtonpost</a> ........ &quot;source&quot;: &quot;The Washington Post&quot;}<br>{&quot;id&quot;: &quot;d5966ad2-33f9-11e1-825f-dabc29fd7071&quot;, &quot;article_url</pre><p>This data contains &gt;50,000 python dicts. The following code is used for loading and storing the data in a list of strings:</p><pre>file = filename.txt<br>content = []<br>with open(file) as f:<br>    content = f.readlines()<br>content = [json.loads(x.strip()) for x in content]<br># print(content)<br>    <br>data = json.loads(json.dumps(content))<br><br># preprocessing ////////////////////////////////</pre><pre>content_list = []<br>for i in data:<br>    string_content = &quot;&quot;<br>    if &quot;contents&quot; in i:<br>       for all in i[&quot;contents&quot;]:<br>          if &quot;content&quot; in all:<br>             string_content = string_content + str(all[&quot;content&quot;])<br>       content_list.append(string_content)</pre><p>content_list contains the complete data in a list of strings. So if there are 45000 articles, content_list has 45000 strings.</p><h3>Data Preprocessing</h3><p>Now we will use python <a href="https://en.wikipedia.org/wiki/Pandas_(software)">pandas</a> library to apply some preprocessing techniques. To start with, we will try to clean our text data as much as possible. The idea is to remove the punctuations, numbers, and special characters all in one step using the regex replace(“[^a-zA-Z#]”, ” “), which will replace everything, except alphabets with space. Then we will remove shorter words because they usually don’t contain useful information. Finally, we will make all the text lowercase to nullify case sensitivity.</p><pre>news_df = pd.DataFrame({&#39;document&#39;:content_list})<br>    <br># removing everything except alphabets`<br>news_df[&#39;clean_doc&#39;] = news_df[&#39;document&#39;].str.replace(&quot;[^a-zA-Z#]&quot;, &quot; &quot;)</pre><pre># removing null fields<br>news_df = news_df[news_df[&#39;clean_doc&#39;].notnull()]<br># removing short words<br>news_df[&#39;clean_doc&#39;] = news_df[&#39;clean_doc&#39;].apply(lambda x: &#39; &#39;.join([w for w in x.split() if len(w)&gt;3]))</pre><pre># make all text lowercase<br>news_df[&#39;clean_doc&#39;] = news_df[&#39;clean_doc&#39;].apply(lambda x: x.lower())</pre><p>Now we will remove the stopwords from data. First, I load <a href="http://www.nltk.org/">NLTK’s</a> list of English stop words. <a href="http://en.wikipedia.org/wiki/Stop_words">Stop words</a> are words like “a”, “the”, or “in” which don’t convey significant meaning.</p><pre>stop_words = stopwords.words(&#39;english&#39;)<br>    stop_words.extend([&#39;span&#39;,&#39;class&#39;,&#39;spacing&#39;,&#39;href&#39;,&#39;html&#39;,&#39;http&#39;,&#39;title&#39;, &#39;stats&#39;, &#39;washingtonpost&#39;])<br># data is from washingtonpost, and it occurs heavily in every article, thus added to stop words</pre><pre># tokenization<br>tokenized_doc = news_df[&#39;clean_doc&#39;].apply(lambda x: x.split())</pre><pre># remove stop-words<br>tokenized_doc = tokenized_doc.apply(lambda x: [item for item in x if item not in stop_words])<br># print(tokenized_doc)</pre><pre># de-tokenization<br>detokenized_doc = []<br>for i in range(len(tokenized_doc)):<br>    if i in tokenized_doc:<br>        t = &#39; &#39;.join(tokenized_doc[i])<br>        detokenized_doc.append(t)</pre><pre># print(detokenized_doc)</pre><h3>Applying Tf-idf to create Document-Term Matrix</h3><p>Now, we have our data ready. We will apply <a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf"><strong>tf-idf</strong></a> vectoriser to create a document-term matrix. <strong>tf-idf</strong> short for <strong>term frequency–inverse document frequency</strong>, is a numerical statistic that is intended to reflect how important a word is to a document in a collection.</p><p><strong>Tf-idf</strong> value is directly proportional to the number of appearances of a word in a document, and is offset by the number of documents containing that word, which compensates for the fact that some words appear more commonly than others in general.</p><p>We will use <a href="https://scikit-learn.org/stable/"><strong>sklearn’s</strong></a> <em>TfidfVectorizer</em> to create a <strong>tf-idf</strong> matrix with 10,000 terms.</p><pre>from sklearn.feature_extraction.text import TfidfVectorizer</pre><pre># tfidf vectorizer of scikit learn<br>    vectorizer = TfidfVectorizer(stop_words=stop_words,max_features=10000, max_df = 0.5, use_idf = True, ngram_range=(1,3))</pre><pre>X = vectorizer.fit_transform(detokenized_doc)</pre><pre>print(X.shape) # check shape of the document-term matrix</pre><pre>terms = vectorizer.get_feature_names()</pre><p>(X.shape gives (22618, 10000) number of documents = 22618, number of words=10000)</p><p><strong>ngram_range</strong>: this just means I’ll look at unigrams, bigrams and trigrams. See <a href="http://en.wikipedia.org/wiki/N-gram">n-grams</a>.</p><p>This document-term matrix will be used in LSA, as well as for applying k-means for clustering the documents.</p><h3>Clustering text documents using k-means</h3><p>In this step we will cluster the text documents using <strong>k-means</strong> algorithm. <strong><em>K</em>-means</strong> clustering is a type of unsupervised learning, which is used when you have unlabeled data (i.e., data without defined categories or groups). The goal of this algorithm is to find groups in the data, with the number of groups represented by the variable <em>K</em>. The algorithm works iteratively to assign each data point to one of <em>K</em> groups based on the features that are provided. Data points are clustered based on feature similarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*40mAyNQduiiFQQLeIplefA.jpeg" /><figcaption>Example results of k-means</figcaption></figure><p>This clustering is being used purely for plotting purposes here.</p><pre>from sklearn.cluster import KMeans</pre><pre>num_clusters = 10</pre><pre>km = KMeans(n_clusters=num_clusters)</pre><pre>km.fit(X)</pre><pre>clusters = km.labels_.tolist()</pre><p>clusters array will be used for plotting. clusters is a list containing numbers 1 to 10, classifying each documents in 10 clusters. Read more about scikit k-means <a href="https://scikit-learn.org/stable/auto_examples/text/plot_document_clustering.html">here</a>. Based on values of clusters array, we will assign each document a unique color at the time of plotting. This will become more clear as we move forward.</p><h3>Topic Modeling</h3><p>The next step is to represent each and every term and document as a vector. We will use the document-term matrix and decompose it into multiple matrices. This is basically the LSA part.</p><p>We will use sklearn’s randomized_svd to perform the task of matrix decomposition. You need some knowledge of <strong>LSA</strong> and <a href="https://en.wikipedia.org/wiki/Singular_value_decomposition"><strong>Singular Value Decomposition (SVD)</strong></a><strong> </strong>to understand the below part. SVD is basically a factorisation of a matrix.</p><p>In the definition of SVD, an original matrix <strong>A</strong> is approximated as a product <strong>A</strong> ≈ <strong>UΣV*</strong> where <strong>U</strong> and <strong>V </strong>have orthonormal columns, and <strong>Σ</strong> is non-negative diagonal.</p><p>Read more about LSA <a href="https://en.wikipedia.org/wiki/Latent_semantic_analysis">here</a> and scikit’s randomized_svd <a href="https://scikit-learn.org/stable/modules/generated/sklearn.utils.extmath.randomized_svd.html">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*_Sec45RW1zm4FcJxcfSxkQ.png" /><figcaption>k=number of topics/concepts, m=number of documents, n=number of words</figcaption></figure><pre># applying lsa //////////////////////////////</pre><pre><br>from sklearn.utils.extmath import randomized_svd</pre><pre>U, Sigma, VT = randomized_svd(X, n_components=10, n_iter=100,<br>                              random_state=122)</pre><pre>#printing the concepts</pre><pre>for i, comp in enumerate(VT):<br>        terms_comp = zip(terms, comp)<br>        sorted_terms = sorted(terms_comp, key= lambda x:x[1], reverse=True)[:7]<br>        print(&quot;Concept &quot;+str(i)+&quot;: &quot;)<br>        for t in sorted_terms:<br>            print(t[0])<br>        print(&quot; &quot;)</pre><p>Here, U, sigma and VT are 3 matrices which are obtained after decomposing the matrix X (document-term matrix obtained by tf-idf). VT is a term-concept matrix, U is document-concept matrix and Sigma is concept-concept matrix.</p><p>In above code, we take 10 concepts/topics ( n_components=10). Then we print those concepts. Example concepts are printed below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*aJDD2WIQvokYlukb9m5uOQ.png" /></figure><h3>Topics Visualization</h3><p>To find out how distinct our topics are, we should visualize them. Of course, we cannot visualize more than 3 dimensions, but there are techniques like PCA and t-SNE which can help us visualize high dimensional data into lower dimensions. Here we will use a relatively new technique called UMAP (Uniform Manifold Approximation and Projection).</p><pre>import umap</pre><pre>X_topics=U*Sigma<br>embedding = umap.UMAP(n_neighbors=100, min_dist=0.5, random_state=12).fit_transform(X_topics)</pre><pre>plt.figure(figsize=(7,5))<br>    plt.scatter(embedding[:, 0], embedding[:, 1], <br>    c = clusters,<br>    s = 10, # size<br>    edgecolor=&#39;none&#39;<br>    )<br>    plt.show()</pre><p>Here, i have used c=clusters, which will be helpful in showing different colors in documents. <a href="https://umap-learn.readthedocs.io/en/latest/">Read</a> the official docs of UMAP to learn more about all the parameters.</p><p>Here, I am showing the output of 2500 news articles:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*xNI4nLtN4qkI1JGz6s50Jg.png" /></figure><p>Another output with 10,000 news articles:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*t8UTVAEFMuW3tglAWzjsgA.png" /></figure><p>Here, each dot represents a document and the colours represent the different clusters which were found out using k-means. Our LSA model seems to have done a good job as same colors(obtained by k-means) are clustered together(using LSA). Feel free to play around with the parameters of UMAP to see how the plot changes its shape.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b95c7b68861c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kuzok/news-documents-clustering-using-python-latent-semantic-analysis-b95c7b68861c">News documents clustering using python (latent semantic analysis)</a> was originally published in <a href="https://medium.com/kuzok">Kuzok</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What the heck is Haskell]]></title>
            <link>https://medium.com/@abhi_khangarot/what-the-heck-is-haskell-9176ee499922?source=rss-310ba239dbe5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9176ee499922</guid>
            <category><![CDATA[haskell]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Abhijeet Singh Khangarot]]></dc:creator>
            <pubDate>Thu, 10 May 2018 18:36:01 GMT</pubDate>
            <atom:updated>2018-05-10T18:36:01.677Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This article is an overview of Haskell and functional programming languages, particularly written for those who have heard both of these concepts for the first time today.</blockquote><p>Basically, <strong>Haskell is a functional programming language</strong>. Haskell is the purest functional programming language. Haskell programs are a series of high-level generalizable functions that define what the program is intended to do, letting lower layers (compiler, runtime, and libraries) handle mundane low-level details such as iteration. ( Didn’t get it, see the example below ).</p><p>For understanding Haskell, you need to know about functional programming first. The <em>functional programming</em> paradigm was explicitly created to support a pure functional approach to problem solving. It means programs written in functional programming languages consists of set of functions to be executed. ( Kind of encapsulation in object oriented programming — dividing a program into functions ).</p><p>Basically, functional programming is a form of <em>declarative programming</em>. In contrast, most mainstream languages, including object-oriented programming (OOP) languages such as C#, Visual Basic, C++, and Java, were designed to primarily support <em>imperative</em> (procedural) programming.</p><p>If you have done programming before, chances are that you have done imperative programming, not functional programming. With an imperative approach, a developer writes code that describes in exacting detail the steps that the computer must take to accomplish the goal. This is sometimes referred to as <em>algorithmic </em>programming.</p><p>On the other hand, in functional programming approach, you use high-level generalizable functions that define what the program is intended to do, letting lower layers (compiler, runtime, and libraries) handle mundane low-level details such as iteration.</p><p>Let’s take an example: Create a list of all even numbers up to 100, and another list omitting the first five of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*qlGaX5-XaRAgOXSOYARpoQ.png" /></figure><p>Here in Haskell you don’t have to write loops as they are implemented by lower layers (compiler, runtime, and libraries).</p><p><strong>Where it came from?</strong></p><p>Haskell was designed by a committee which published the Haskell 1.0 specification in 1990. It named the language after Haskell Curry, an influential logician.</p><p><strong>Where it can be used?</strong></p><p>Haskell is good for <strong>graphics, networking, systems programming, data structures, databases, development, text processing</strong>.</p><p>Haskell is really strong at areas and problems where correctness matters, domain specific languages, and parallel and concurrent programming.</p><p><strong>What are the advantages of learning?</strong></p><p>If you know any of the mainstream languages ( imperative and object oriented languages ) for example C, Java, python, etc. it will be a new and different experience learning Haskell or any functional programming language in general. It will improve your programming skills for the better. Thinking “functionally” lets you write more efficient code even in imperative languages, since you essentially decompose your algorithms into blocks that are easy to reason about. So even if you never end up using functional programming, learning it <strong>teaches you new ways to think</strong>.</p><p>It is not used at very large scale in industry so it might not get you a job but it is definitely worth learning.</p><p><strong>Industry adoption</strong></p><p>In industry it is being used for various areas like DSLs, web apps, compiler design, networking, analysis, systems programming, etc.</p><p>Haskell has a diverse range of use commercially, from aerospace and defense, to finance, to web startups, hardware design firms and lawnmower manufacturers.</p><p>Haskell has various other features like it is statically typed and lazy.</p><p>Made your mind to learn Haskell or want to know more about it, head over to : <a href="https://www.haskell.org/">http<strong>s://www.haskell.org/</strong></a><strong> .</strong></p><p><strong>Thanks.</strong></p><p>Thanks for reading! If you like this, please clap or comment or both.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9176ee499922" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>