<?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 suhas murthy on Medium]]></title>
        <description><![CDATA[Stories by suhas murthy on Medium]]></description>
        <link>https://medium.com/@murthy-suhas?source=rss-a50fbe23201d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*uXr76xq7s6wDFJ1j1xOiQA.jpeg</url>
            <title>Stories by suhas murthy on Medium</title>
            <link>https://medium.com/@murthy-suhas?source=rss-a50fbe23201d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 21:31:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@murthy-suhas/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[GitHub Copilot: how it started, how it went, what challenges I’m facing]]></title>
            <link>https://levelup.gitconnected.com/github-copilot-how-it-started-how-it-went-what-challenges-im-facing-a4f74295a8ac?source=rss-a50fbe23201d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4f74295a8ac</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[github-copilot]]></category>
            <dc:creator><![CDATA[suhas murthy]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 05:34:03 GMT</pubDate>
            <atom:updated>2026-06-22T15:43:55.037Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Or: how a credit-based billing shock forced our team to stop treating AI tooling like a black box</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MPoYTIccwXM19xWRKM7MlQ.png" /></figure><p>I didn’t want to use GitHub Copilot.</p><p>Not in the “I have concerns about AI” way — I just didn’t see the point. I’d been writing React and TypeScript for over a decade. Autocomplete that finishes my useState line wasn&#39;t going to change how I worked. I used it the way most skeptical developers do: half-heartedly, mostly ignoring the suggestions, occasionally annoyed when it guessed wrong.</p><p>Initially, the suggestions were just annoying. They’d come in mid-type, rarely what I actually wanted — I’d end up adding throwaway comments just to coax a decent suggestion out of it. That changed when I started using agent mode. I could put my actual thought into it and get real output back. That’s what drew me in.</p><h3>The reckless phase</h3><p>I won’t pretend my early agent-mode usage was disciplined. It wasn’t. I was throwing half-formed thoughts at it — vague, underspecified, whatever was in my head at the moment — and asking it to just go. Some of it worked. A lot of it didn’t.</p><p>And I reacted exactly like you’d expect: when it worked, I was impressed. When it didn’t, my reaction wasn’t “I gave it a bad prompt” — it was “these AI tools will never work.” <strong>Appreciating it one moment, writing it off the next.</strong></p><p>What pulled me out of it wasn’t a tutorial or a course. It was necessity. Our team hit a wall on a legacy migration project — moving a sprawling VB.NET/ASP.NET Web Forms system to a modern React SPA — and the volume of work made it obvious we couldn’t keep going at manual pace. If AI was ever going to earn its place, this was the test.</p><h3>From vague prompts to a real system</h3><p>The first real shift was small: predefined, reusable prompts instead of retyping context every time. We built three — a senior React developer prompt, a unit test engineer prompt, a frontend architect prompt — mostly because I’m a developer and retyping the same context repeatedly felt like a problem worth solving.</p><p>It helped. But it also exposed the next ceiling. Predefined prompts gave us consistency, not leverage. On anything that counted as a real feature, we were still doing a lot of manual work around the edges. The output was better. The bottleneck hadn’t moved.</p><p>That’s what pushed us toward agents — and toward a structure that ended up being the actual unlock: splitting complex feature work into three distinct phases, each with its own agent.</p><p><strong>Plan.</strong> Understand the feature, map the blast radius, figure out what’s actually being touched. <strong>Generate.</strong> Turn the plan into an implementation spec. <strong>Implement.</strong> Execute it.</p><p>We paired this with deliberate model selection — Opus for the planning and generation work, where reasoning quality mattered most, and a faster, cheaper model for implementation, where the work was closer to disciplined execution than judgment. We even built a fourth agent on top of this — a React/legacy parity checker, specifically for the migration, that compared old VB.NET behaviour against the new React implementation and flagged gaps.</p><p>This is where it stopped feeling like a chat tool and started feeling like infrastructure. Migration velocity improved. Bottlenecks that used to take a day to even locate got surfaced in an hour.</p><p>For a while, it felt solved.</p><h3>Then the billing model changed</h3><p>GitHub Copilot moved to credit-based, usage-billed consumption. And the plan/generate/implement workflow we’d built — the one running Opus across two of three phases, on every feature, regardless of size — got expensive fast.</p><p>We had built something that worked, and then the economics underneath it changed. Suddenly the question wasn’t does this help — it was what does this actually cost, per feature, per developer, per month, and can we justify it.</p><p>That question is what turned this from a tooling story into an engineering problem.</p><h3>Treating the AI config like production code</h3><p>The instinct when costs spike is to just use the tool less. We didn’t want that — the workflow was genuinely good. So instead we audited it like we’d audit any other system that got expensive: find the waste, not the value.</p><p>A few things stood out immediately once we actually looked:</p><p><strong>The global instructions file was loading on every single request, for every developer, regardless of relevance.</strong> It had grown to 185 lines — code-heavy blocks for RTK Query and Zod validation, a commands table that already existed in package.jsonbranch-naming conventions. None of that applied to most requests, but all of it got paid for every time. We cut it to roughly 28 lines, kept only the architecture map and core rules, and moved the specialized content into path-scoped instruction files that only load when relevant files are actually open. That single change cut per-request instruction tokens by <strong>close to 90%</strong>.</p><p><strong>Our most-used prompt repeated itself.</strong> The approval workflow — understand, propose, preview, approve, implement — was written out in full across four separate sections instead of defined once. Beyond the token waste, two near-identical instruction blocks is a quality risk: it gives the model two slightly different versions of the same instruction to reconcile, which is exactly the kind of ambiguity that produces inconsistent output. Collapsing it to one definition cut tokens by <strong>roughly two-thirds</strong> and made behavior more predictable.</p><p><strong>The plan agent treated every feature as equally complex.</strong> A two-file tweak was running the same Opus-powered research subagent as a nine-file architectural change. That was the real cost driver, and the fix wasn’t trimming text — it was restructuring the workflow so the plan agent classifies complexity <em>first</em>, as a near-zero-cost step, before any research runs at all. Research depth and model choice now scale to that classification: light models for low complexity, Sonnet for medium, Opus reserved for the high-complexity work where it’s actually earning its cost.</p><p>The result, roughly: <strong>75% fewer tokens</strong> across the optimized artifacts, and <strong>up to 6x cheaper cost per run</strong> on the plan/generate steps through model-matching alone. We didn’t use AI less — we just used the right model for the job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*BEmt_cU9J9S6TPlxuqnvDA.png" /></figure><h3>What this actually changed in how I think about AI tooling</h3><p>The instructions file lesson is the one I keep coming back to: the most expensive part of an AI workflow usually isn’t the hard reasoning step. It’s the boilerplate getting silently reloaded on every single interaction. That’s not an AI-specific insight, honestly — it’s the same lesson as any system with a hot path. We just hadn’t been looking at our Copilot config that way. It took a billing shock to make us look.</p><p>I realised Copilot isn’t just a chat application — <strong>it should be treated like an engineering problem.</strong> You constantly improve the architecture, watch the pricing, keep it cost-effective, but never compromise on the output it produces.</p><p>I’m still early in figuring out where this goes next. We’re mid-rollout on the optimized config, monitoring credits per PR over the next few weeks to see if the projected savings hold in practice, and I expect there’s another round of this once the agents and instructions drift again — they always do. We’re still figuring out how to balance cost against output — that part isn’t solved. But one thing’s clear: <strong>don’t wait for a billing shock to force the audit. Do it before you have to.</strong></p><p><em>I’m a Senior Product Engineer leading frontend architecture and AI-native tooling adoption for a team migrating a legacy enterprise system to React. If you’re working through similar AI-tooling-at-scale problems, I’d like to hear how you’re approaching it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4f74295a8ac" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/github-copilot-how-it-started-how-it-went-what-challenges-im-facing-a4f74295a8ac">GitHub Copilot: how it started, how it went, what challenges I’m facing</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let's migrate redux to redux toolkit: A Three-Part Series]]></title>
            <link>https://levelup.gitconnected.com/lets-migrate-redux-to-redux-toolkit-a-three-part-series-11bb34ac6a28?source=rss-a50fbe23201d------2</link>
            <guid isPermaLink="false">https://medium.com/p/11bb34ac6a28</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[migrate]]></category>
            <dc:creator><![CDATA[suhas murthy]]></dc:creator>
            <pubDate>Thu, 27 Jun 2024 16:25:40 GMT</pubDate>
            <atom:updated>2024-06-30T17:37:01.947Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2: Moving an existing redux application to the redux toolkit incrementally</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0uDxgZsu_fpRWwCiqLCzA.png" /></figure><p><a href="https://levelup.gitconnected.com/migrating-from-redux-to-redux-toolkit-a-three-part-series-564b858de3fe">In the previous part, we set up a GitHub profile finder application using React, Redux, and TypeScript</a>. Now, it’s time to take things up a notch by migrating it to Redux Toolkit.</p><blockquote>Spoiler alert: we’ll be deleting a lot of code!</blockquote><p>Don’t believe me? Just look at this committed image!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*XuGqmzKlqMyhXxXq3_bexQ.png" /><figcaption>Deleted files</figcaption></figure><p><strong>Why Redux toolkit?</strong></p><p>Link for an explanation on <a href="https://redux-toolkit.js.org/introduction/why-rtk-is-redux-today#how-redux-toolkit-is-different-from-the-redux-core">official site</a></p><p>Let me put it in my own words. In the <a href="https://medium.com/gitconnected/migrating-from-redux-to-redux-toolkit-a-three-part-series-564b858de3fe">previous article</a>, we covered the basics of Redux and its usage. Now, let’s delve into understanding Redux Toolkit, often referred to as RTK.</p><p>Imagine you’re coding a complex application, and managing the state feels like solving a giant jigsaw puzzle. Traditional Redux is like trying to put the puzzle together without a picture: setting up actions, reducers, and middleware from scratch. It works, but it’s time-consuming, repetitive, and leaves plenty of room for errors.</p><p>Now, Redux Toolkit is like having GitHub Copilot by your side. It automatically suggests the best code snippets, completes functions for you and ensures you’re following best practices without you even asking. It streamlines your coding process, reduces boilerplate, and helps you avoid common mistakes.</p><ol><li><strong>Simplified</strong> <strong>Setup and Configuration</strong></li></ol><ul><li>Just like GitHub Copilot sets up your coding environment, Redux Toolkit provides configureStore which sets up your Redux store with sensible defaults, including useful middleware and DevTools support.</li></ul><p>2. <strong>Automatic Code Generation</strong></p><ul><li>Redux Toolkit’s createSlice function automatically generates action creators and action types, similar to how Copilot generates code snippets. This reduces boilerplate and simplifies your Redux logic.</li></ul><p>3. <strong>Best Practices by Default</strong></p><ul><li>Copilot suggests code following best practices. Similarly, Redux Toolkit encourages best practices by default, ensuring your code is clean, efficient, and maintainable.</li></ul><p>4. <strong>Built-in Middleware</strong></p><ul><li>Like Copilot handling repetitive tasks, Redux Toolkit includes useful middleware like redux-thunk out of the box, so you don&#39;t have to set it up manually.</li></ul><p>4. <strong>Efficient and Predictable State Management</strong></p><ul><li>Redux Toolkit uses Immer for immutable state updates under the hood, making state management more predictable and efficient, much like how Copilot makes code suggestions that follow a logical, predictable pattern.</li></ul><blockquote>Enough with the drama let&#39;s see some action</blockquote><p><strong>Previously on </strong><a href="https://levelup.gitconnected.com/migrating-from-redux-to-redux-toolkit-a-three-part-series-564b858de3fe"><strong>“Migration to Redux Toolkit”</strong></a></p><p>We built a GitHub profile finder with two reducers: users and repos, along with their respective action creators and actions. Now, let&#39;s see how we can move this to Redux Toolkit and make our lives a whole lot easier.</p><blockquote>Starter code: <a href="https://github.com/suhas86/git-clone-react-redux/tree/feature/old-redux">https://github.com/suhas86/git-clone-react-redux/tree/feature/old-redux</a></blockquote><p><strong>Migrating the foundation of Redux state — the store</strong></p><p>As mentioned in the first point, Redux Toolkit offers a straightforward setup and configuration. It bundles DevTools, Redux Thunk, and Immer right out of the box, making store setup a breeze.</p><p>Install redux toolkit npm install @reduxjs/toolkit</p><p>Below, you can see how we’ve eliminated the manual setup of rootReducer DevTools and done away with the need to set up redux-thunk middleware.</p><pre>import { configureStore } from &quot;@reduxjs/toolkit&quot;;<br>import { reposReducer } from &quot;../reducers/reposReducer&quot;;<br>import { usersReducer } from &quot;../reducers/usersReducer&quot;;<br><br>export const store = configureStore({<br>    reducer: {<br>        users: usersReducer,<br>        repos: reposReducer,<br>    }<br>})<br><br>export type ApplicationState = ReturnType&lt;typeof store.getState&gt;;<br>export type ApplicationDispatch = typeof store.dispatch;</pre><blockquote>Before and After</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z8-Lspeuq8DFbX-zWOw47Q.png" /><figcaption>Before</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tM8zCPDZS49Kf4GXrTXJbQ.png" /><figcaption>After</figcaption></figure><p>🚨<strong>Note:</strong> You will see a TypeScript error in the store file. The error message suggests that unknown is not a valid type for the Action type from Redux, which expects a string as its type parameter. This string should represent the type of action.</p><p>In Redux, every action should have a type property that is a string. This type property is used to identify the action.</p><p>You can ignore this as this will be handled once we create a slice. If you’re incrementally moving your application to Redux Toolkit and wish to address this issue beforehand:</p><p>Define UnknownAction as an action type with a type property that is a string in your type definitions. Here&#39;s how you can do it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*fgSI-OerBnBUyxl-kGdIEg.png" /><figcaption>type UnknownAction = Action&lt;string&gt;;</figcaption></figure><blockquote>Reference commit: <a href="https://github.com/suhas86/git-clone-react-redux/commit/93361311ecb0c825e4dddf610eff13c3f0b53881">https://github.com/suhas86/git-clone-react-redux/commit/93361311ecb0c825e4dddf610eff13c3f0b53881</a></blockquote><p>🚨 <strong>One more error:</strong></p><p>In the home page, we will see an error</p><p><em>No overload matches this call. The last overload gave the following error. Argument of type ‘ToggleUserLikeAction’ is not assignable to parameter of type ‘UnknownAction’. Index signature for type ‘string’ is missing in type ‘ToggleUserLikeAction’.</em></p><p>This is because ApplicationDispatch expects ThunkDispatch but toogleUserLike doesn&#39;t require redux thunk.</p><p>To fix this, I will add a workaround for now, as this error will be automatically resolved when we migrate to the user actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wo2HHiNHan7xR0R5bJf3Dg.png" /></figure><blockquote>Reference Commit: <a href="https://github.com/suhas86/git-clone-react-redux/commit/aaf9aa0197d9a3216bf12903ebb990737250cdee">https://github.com/suhas86/git-clone-react-redux/commit/aaf9aa0197d9a3216bf12903ebb990737250cdee</a></blockquote><p>Alright, with a few hiccups, since we’re migrating from Redux to Redux Toolkit, we’ve set up our store. Now, let’s talk about slices. Not the pizza kind, but the function kind.</p><p><strong>Creating a Slice</strong> 🍕</p><p>As mentioned earlier, createSlice in Redux Toolkit acts like a multitool for defining Redux actions and reducers in one shot. It automagically generates action creators and reducers from your slice reducers, cutting down on repetitive code and making your Redux setup cleaner and easier to manage.</p><p>Instead of modifying existing files, let’s create a new folder under Redux called features and add slices there. We&#39;ll start with userSlice.</p><p>createSlice accepts an object that defines:</p><ul><li>name: A string that specifies the slice name.</li><li>initialState: The initial state value of the slice.</li><li>reducers: An object where each key represents a Redux action type, and the corresponding value is a reducer function that updates the state in response to that action.</li><li>extraReducers is an optional configuration in createSlice provided by Redux Toolkit. It allows you to handle actions from other slices or outside sources without defining additional action types or action creators explicitly within the slice.</li></ul><pre>import { ActionReducerMapBuilder, createAsyncThunk, createSlice } from &#39;@reduxjs/toolkit&#39;;<br>import { Users } from &#39;../types/usersTypes&#39;;<br>import { fetchTopUsersBySize, fetchUserBySearch } from &#39;../services&#39;;<br>import { AsyncThunk, AsyncThunkConfig } from &#39;@reduxjs/toolkit/dist/createAsyncThunk&#39;;<br><br>interface UsersState {<br>    loading: boolean;<br>    users: Users | null;<br>    error: string | null;<br>}<br><br>const initialState: UsersState = {<br>    loading: false,<br>    users: null,<br>    error: null,<br>};<br><br>export const getTopUsersBySize = createAsyncThunk(<br>    &#39;users/getTopUsers&#39;,<br>    async (size: number = 30): Promise&lt;Users&gt; =&gt; {<br>        const users = await fetchTopUsersBySize(size);<br>        return users;<br>    }<br>);<br><br>export const getUsersBySearch = createAsyncThunk(&#39;users/getUsersBySearch&#39;, async (userName: string): Promise&lt;Users&gt; =&gt; {<br>    const users = await fetchUserBySearch(userName);<br>    return users<br>})<br><br>// TODO: To make this generic<br>// eslint-disable-next-line @typescript-eslint/no-explicit-any<br>const handleAsyncActions = (builder: ActionReducerMapBuilder&lt;UsersState&gt;, asyncThunk: AsyncThunk&lt;Users, any, AsyncThunkConfig&gt;) =&gt; {<br>    builder<br>        .addCase(asyncThunk.pending, (state) =&gt; {<br>            state.loading = true;<br>            state.error = null;<br>        })<br>        .addCase(asyncThunk.fulfilled, (state, action) =&gt; {<br>            state.users = action.payload;<br>            state.loading = false;<br>            state.error = null;<br>        })<br>        .addCase(asyncThunk.rejected, (state, action) =&gt; {<br>            state.loading = false;<br>            state.error = action.error.message || &#39;Oops something went wrong&#39;;<br>        });<br>};<br><br><br><br>const userSlice = createSlice({<br>    name: &#39;users&#39;,<br>    initialState,<br>    reducers: {<br>        toogleUserLike: (state, action) =&gt; {<br>            const userId = action.payload;<br>            if (!state.users) {<br>                return; // If users data is null, return state as is<br>            }<br>            const updatedUsers = state.users.items.map((user) =&gt; {<br>                if (user.id === userId) {<br>                    return {<br>                        ...user,<br>                        isLiked: !user.isLiked, // Toggle the liked property<br>                    };<br>                }<br>                return user;<br>            });<br>            state.users.items = updatedUsers;<br>        },<br>    },<br>    extraReducers: (builder) =&gt; {<br>        handleAsyncActions(builder, getTopUsersBySize);<br>        handleAsyncActions(builder, getUsersBySearch);<br>    },<br>});<br><br>export const usersReducer = userSlice.reducer;<br>export const { toogleUserLike } = userSlice.actions;<br>export default userSlice;</pre><ol><li><strong>Initial State and Async Thunks Setup</strong>:</li></ol><ul><li>We define an initial state (UsersState) that includes properties for loading status, user data, and error handling.</li><li>createAsyncThunk functions (getTopUsersBySize and getUsersBySearch) are created to fetch user data asynchronously from backend services (fetchTopUsersBySize and fetchUserBySearch).</li></ul><p><strong>2. Handling Async Actions</strong>:</p><ul><li>The handleAsyncActions function is defined to manage state updates for pending, fulfilled, and rejected states of async thunks. It uses ActionReducerMapBuilder from Redux Toolkit to add cases for each async action&#39;s lifecycle events (pending, fulfilled, rejected).</li></ul><p><strong>3. Creating the Slice</strong>:</p><ul><li>createSlice is used to define a slice of the Redux state named &#39;users&#39;. It includes:</li><li>name: Identifies the slice in the Redux store.</li><li>initialState: Sets the initial state for the &#39;users&#39; slice.</li><li>reducers: Defines additional synchronous actions (toggleUserLike) that update the state based on user interaction, such as toggling a user&#39;s like status.</li></ul><p><strong>4. Integrating Async Actions with </strong><strong>extraReducers</strong>:</p><ul><li>The extraReducers property in createSlice integrates the async action handlers (handleAsyncActions) with the slice. This ensures that state updates for async actions (getTopUsersBySize and getUsersBySearch) are managed alongside the synchronous actions (toggleUserLike).</li></ul><p><strong>5. Exporting Slice Reducer and Actions</strong>:</p><ul><li>The userSlice.reducer and userSlice.actions are exported for use in configuring the Redux store and connecting with React components, respectively.</li></ul><p>This approach using createSlice and createAsyncThunk from Redux Toolkit simplifies Redux setup by reducing boilerplate code and enhancing readability, making it easier to manage complex state and async operations in React applications.</p><p>Now that our slice has generated action creators and reducers magically, let’s update the store to use the reducer from the slice and the home page to use action creators from the slice.</p><blockquote>Commit reference: <a href="https://github.com/suhas86/git-clone-react-redux/commit/8f0b0fd4d857a6cfbecbcb0cc4cf11a0ab0b8f16">https://github.com/suhas86/git-clone-react-redux/commit/8f0b0fd4d857a6cfbecbcb0cc4cf11a0ab0b8f16</a></blockquote><p>If you run the application, you will see our application working seamlessly with the home page using Redux Toolkit. You can also observe the actions generated by our slice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*K8-cOlYWxsXWPisNvtuzSQ.png" /></figure><p><strong>Alright, folks, it’s cleanup time </strong>🧹</p><p>Let’s get rid of all the unnecessary types, actions, and reducers cluttering our codebase.</p><blockquote>Commit reference: <a href="https://github.com/suhas86/git-clone-react-redux/commit/57aa1640f7531d981735f9dbc1cdf3b63c0db4fd">https://github.com/suhas86/git-clone-react-redux/commit/57aa1640f7531d981735f9dbc1cdf3b63c0db4fd</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*XuGqmzKlqMyhXxXq3_bexQ.png" /><figcaption>Deleted files</figcaption></figure><blockquote>Final code: <a href="https://github.com/suhas86/git-clone-react-redux/tree/feature/redux-toolkit">https://github.com/suhas86/git-clone-react-redux/tree/feature/redux-toolkit</a></blockquote><p>Feel free to play around with this code and challenge yourself to move the Repository page on your own.</p><blockquote>Entire migration code: <a href="https://github.com/suhas86/git-clone-react-redux/tree/feature/redux-toolkit-final">https://github.com/suhas86/git-clone-react-redux/tree/feature/redux-toolkit-final</a></blockquote><p>🎉 Congratulations, folks! With this, we’ve successfully migrated the entire application to Redux Toolkit. I hope this migration article has been as smooth as butter on toast for you. Stay tuned for the bonus Part Three, where we’ll dive into using RTK Query for data fetching. Get ready to level up your Redux game!</p><p>Happy Coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11bb34ac6a28" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/lets-migrate-redux-to-redux-toolkit-a-three-part-series-11bb34ac6a28">Let&#39;s migrate redux to redux toolkit: A Three-Part Series</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating from Redux to Redux Toolkit: A Three-Part Series]]></title>
            <link>https://levelup.gitconnected.com/migrating-from-redux-to-redux-toolkit-a-three-part-series-564b858de3fe?source=rss-a50fbe23201d------2</link>
            <guid isPermaLink="false">https://medium.com/p/564b858de3fe</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[redux-thunk]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[migration]]></category>
            <dc:creator><![CDATA[suhas murthy]]></dc:creator>
            <pubDate>Fri, 21 Jun 2024 09:11:03 GMT</pubDate>
            <atom:updated>2024-06-21T14:12:46.263Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1: Building an application using redux and Typescript</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*jF-_xMd8udBOGePHRcUYrQ.png" /></figure><p>Migrating a legacy codebase to React is like trying to teach an old dog new tricks — challenging but rewarding! In one of our applications, we’re using Redux without Redux Toolkit, and finding resources for this older approach is like searching for a needle in a haystack. Most modern apps now use Redux Toolkit, which Redux officially <a href="https://redux.js.org/introduction/getting-started">recommends</a>.</p><p>This inspired me to write a guide on migrating from Redux to Redux Toolkit. Think of it as giving your app a stylish upgrade! This tutorial will be a three-part series: first, we’ll build an app using traditional Redux; then, we’ll give it a makeover with Redux Toolkit.</p><p>Let&#39;s build a simple GitHub profile finder application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RS19sEfJCSOFeIRFaAJREQ.png" /></figure><p>In this application, we’ve curated a list of top users whose followers exceed 1000 — because, in the world of coding, popularity does count! Use our search feature to track down your coding heroes and dive into their public repositories with the ‘View Repos’ option. Additionally, we have a ‘Like’ feature (data presentation excluded) to help you bookmark your favourites</p><blockquote>Buckle up for this coding adventure</blockquote><p><strong>Prerequisites</strong></p><p>You should have a good understanding of React and TypeScript, along with basic knowledge of Redux and Tailwind CSS.</p><p>You can find the basic setup of our React app on <a href="https://github.com/suhas86/git-clone-react-redux.git">GitHub</a></p><p><strong>About This Repository:</strong><br>Within this repository, you’ll discover a basic React application built on the Vite build tool. We’ll be utilizing TypeScript for type safety and Tailwind CSS for styling.</p><blockquote>Alright, enough with the appetizers — let’s dig into building our app!</blockquote><p><strong>Let&#39;s install the libraries required for this application</strong></p><p>We’ll be using Axios for reaching out to the interwebs, React Router for navigating through the app, and of course, Redux for keeping our states in check. Let’s get these libraries installed!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l8UDPCWZoQvox1_Uha67tA.png" /><figcaption>npm install axios react-router-dom react-redux</figcaption></figure><p><strong>Folder structure</strong></p><p>This is the folder structure we’ll be sticking to throughout this application. If you want to follow along, check out the <a href="https://github.com/suhas86/git-clone-react-redux/tree/feature/old-redux">feature/old-redux</a> branch along with this tutorial. Let’s enjoy the journey together!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*ih1pgBvqi704cLV7zySGRA.png" /></figure><p><strong>First things first, let’s kick off with an easy task — setting up our API requests.</strong></p><p>Create a folder under ‘redux’ and name it ‘services’. Inside ‘services’, let’s craft a file called ‘index.ts’.</p><p>In this file, we’re going to work some magic with four handy methods:</p><ul><li>‘fetchTopUsersBySize’: Fetches the list of top users.</li><li>‘fetchUserBySearch’: Search users.</li><li>‘fetchReposByUserName’: Retrieves repositories for a given username.</li><li>‘fetchRepoBySearch’: Search repositories by name.</li></ul><pre>import api from &#39;../api&#39;;<br><br>export const fetchTopUsersBySize = async (size: number = 30) =&gt; {<br>  const response = await api.get(<br>    `/search/users?q=followers:&gt;1000&amp;sort=followers&amp;order=desc&amp;per_page=${size}`<br>  );<br>  return response.data;<br>};<br><br>export const fetchUserBySearch = async (text: string) =&gt; {<br>  const response = await api.get(`/search/users?q=${text}`);<br>  return response.data;<br>};<br><br>export const fetchReposByUserName = async (userName: string) =&gt; {<br>  const response = await api.get(<br>    `/users/${userName}/repos?sort=created&amp;direction=desc`<br>  );<br>  return response.data;<br>};<br><br>export const fetchRepoBySearch = async (userName: string, text: string) =&gt; {<br>  const response = await api.get(<br>    `/search/repositories?q=user:${userName}+${text}`<br>  );<br>  return response.data;<br>};</pre><blockquote>Time to get our state management game on point!</blockquote><p><strong>Key Redux Concepts Overview</strong></p><ul><li><strong>Store:</strong> The single source of truth that holds the entire state of your application.</li><li><strong>Actions: </strong>Plain JavaScript objects that describe what happened.</li><li><strong>Reducers:</strong> Pure functions that take the current state and an action, and return a new state.</li></ul><p><strong>Redux folder structure</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*yg50DmVzIgwd4g82wqqRcw.png" /></figure><p>I won’t be going into details of my folder structure, as different developers have different perspectives on setting up their folder structure. Feel free to refer to my <a href="https://github.com/suhas86/git-clone-react-redux/tree/feature/old-redux">GitHub repository</a> to see how I structure my code and what I might have accidentally missed explaining.</p><p><strong>First things first, let’s set up our actions</strong></p><p>Let’s set up our action types! We’ve split our action types into different sections to keep things neat and tidy</p><ol><li><strong>Enum for Action Types</strong>: We define an enumeration called UsersActionTypes that holds all our action type constants. This makes it easier to manage and avoid typos.</li><li><strong>Action Interfaces</strong>: We define interfaces for each action type.</li><li><strong>Union Types for Actions</strong>: We define union types to group related actions together.</li></ol><pre>import { Users } from &#39;../../types/usersTypes&#39;;<br><br>export enum UsersActionTypes {<br>  /** Fetch users */<br>  FETCH_TOP_USERS_REQUEST = &#39;FETCH_TOP_USERS_REQUEST&#39;,<br>  FETCH_TOP_USERS_SUCCESS = &#39;FETCH_TOP_USERS_SUCCESS&#39;,<br>  FETCH_TOP_USERS_FAILURE = &#39;FETCH_TOP_USERS_FAILURE&#39;,<br><br>  /** Fetch users by search */<br>  FETCH_USERS_BY_SEARCH_REQUEST = &#39;FETCH_USERS_BY_SEARCH_REQUEST&#39;,<br>  FETCH_USERS_BY_SEARCH_SUCCESS = &#39;FETCH_USERS_BY_SEARCH_SUCCESS&#39;,<br>  FETCH_USERS_BY_SEARCH_FAILURE = &#39;FETCH_USERS_BY_SEARCH_FAILURE&#39;,<br><br>  /** Toggle user like option */<br>  TOGGLE_USER_LIKE = &#39;TOGGLE_USER_LIKE&#39;,<br>}<br><br>export interface FetchTopUsersRequestAction {<br>  type: typeof UsersActionTypes.FETCH_TOP_USERS_REQUEST;<br>}<br><br>export interface FetchTopUsersSuccessAction {<br>  type: typeof UsersActionTypes.FETCH_TOP_USERS_SUCCESS;<br>  payload: Users;<br>}<br><br>export interface FetchTopUsersFailureAction {<br>  type: typeof UsersActionTypes.FETCH_TOP_USERS_FAILURE;<br>  payload: string;<br>}<br><br>export interface FetchUsersBySearchRequestAction {<br>  type: typeof UsersActionTypes.FETCH_USERS_BY_SEARCH_REQUEST;<br>}<br><br>export interface FetchUsersBySearchSuccessAction {<br>  type: typeof UsersActionTypes.FETCH_USERS_BY_SEARCH_SUCCESS;<br>  payload: Users;<br>}<br><br>export interface FetchUsersBySearchFailureAction {<br>  type: typeof UsersActionTypes.FETCH_USERS_BY_SEARCH_FAILURE;<br>  payload: string;<br>}<br><br>export interface ToggleUserLikeAction {<br>  type: typeof UsersActionTypes.TOGGLE_USER_LIKE;<br>  payload: number;<br>}<br><br>export type FetchTopUsersActions =<br>  | FetchTopUsersRequestAction<br>  | FetchTopUsersSuccessAction<br>  | FetchTopUsersFailureAction;<br><br>export type FetchUsersBySearchActions =<br>  | FetchUsersBySearchRequestAction<br>  | FetchUsersBySearchSuccessAction<br>  | FetchUsersBySearchFailureAction;<br><br>export type UserActions =<br>  | FetchTopUsersActions<br>  | FetchUsersBySearchActions<br>  | ToggleUserLikeAction;</pre><ul><li>FetchTopUsersRequestAction, FetchTopUsersSuccessAction, and FetchTopUsersFailureAction: Interfaces for actions related to fetching top users. FETCH_TOP_USERS_SUCCESS includes a payload of type Users containing the fetched user data, while FETCH_TOP_USERS_FAILURE includes a payload of type string for the error message.</li><li>FetchUsersBySearchRequestAction, FetchUsersBySearchSuccessAction, and FetchUsersBySearchFailureAction: Similar interfaces for fetching users by search.</li><li>ToggleUserLikeAction: Interface for the action that toggles the like option, with a payload of type number representing the user ID.</li></ul><p>Note: Before moving forward let&#39;s install redux-thunk</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*EMcLmcWh1C9h9wTpEwvIpg.png" /><figcaption>npm i redux-thunk</figcaption></figure><p>Redux Thunk is a middleware that allows you to write action creators that return a function instead of an action object. This function can perform asynchronous operations and dispatch regular synchronous actions when those operations are complete.</p><p>Now, let’s set up our action creators and thunk functions. These are the parts of our Redux setup that will handle the actual logic for fetching data and dispatching the necessary actions. Below is the code and a breakdown of what each part does.</p><pre>import { Users } from &#39;../../types/usersTypes&#39;;<br>import { fetchTopUsersBySize, fetchUserBySearch } from &#39;../../services&#39;;<br>import { ThunkAction } from &#39;redux-thunk&#39;;<br>import { ApplicationState } from &#39;../../store&#39;;<br>import {<br>  FetchTopUsersRequestAction,<br>  UsersActionTypes,<br>  FetchTopUsersSuccessAction,<br>  FetchTopUsersFailureAction,<br>  FetchUsersBySearchRequestAction,<br>  FetchUsersBySearchSuccessAction,<br>  FetchUsersBySearchFailureAction,<br>  FetchTopUsersActions,<br>  FetchUsersBySearchActions,<br>  ToggleUserLikeAction,<br>} from &#39;./types&#39;;<br><br>// Action Creators<br>export const fetchTopUsersRequest = (): FetchTopUsersRequestAction =&gt; ({<br>  type: UsersActionTypes.FETCH_TOP_USERS_REQUEST,<br>});<br><br>export const fetchTopUsersSuccess = (<br>  users: Users<br>): FetchTopUsersSuccessAction =&gt; ({<br>  type: UsersActionTypes.FETCH_TOP_USERS_SUCCESS,<br>  payload: users,<br>});<br><br>export const fetchTopUsersFailure = (<br>  error: string<br>): FetchTopUsersFailureAction =&gt; ({<br>  type: UsersActionTypes.FETCH_TOP_USERS_FAILURE,<br>  payload: error,<br>});<br><br>export const fetchSearchUsersRequest = (): FetchUsersBySearchRequestAction =&gt; ({<br>  type: UsersActionTypes.FETCH_USERS_BY_SEARCH_REQUEST,<br>});<br><br>export const fetchSearchUsersSuccess = (<br>  users: Users<br>): FetchUsersBySearchSuccessAction =&gt; ({<br>  type: UsersActionTypes.FETCH_USERS_BY_SEARCH_SUCCESS,<br>  payload: users,<br>});<br><br>export const fetchSearchUsersFailure = (<br>  error: string<br>): FetchUsersBySearchFailureAction =&gt; ({<br>  type: UsersActionTypes.FETCH_USERS_BY_SEARCH_FAILURE,<br>  payload: error,<br>});<br><br>export const toogleUserLike = (userId: number): ToggleUserLikeAction =&gt; ({<br>  type: UsersActionTypes.TOGGLE_USER_LIKE,<br>  payload: userId,<br>});<br><br>// Thunk Functions<br>export const getTopUsersBySize =<br>  (<br>    size: number = 30<br>  ): ThunkAction&lt;void, ApplicationState, unknown, FetchTopUsersActions&gt; =&gt;<br>  async (dispatch) =&gt; {<br>    dispatch(fetchTopUsersRequest());<br>    try {<br>      const users = await fetchTopUsersBySize(size);<br>      dispatch(fetchTopUsersSuccess(users));<br>    } catch (error) {<br>      if (error instanceof Error) {<br>        dispatch(fetchTopUsersFailure(error.message));<br>      } else {<br>        dispatch(fetchTopUsersFailure(&#39;Oops something went wrong!!!&#39;));<br>      }<br>    }<br>  };<br><br>export const getUsersBySearch =<br>  (<br>    userName: string<br>  ): ThunkAction&lt;void, ApplicationState, unknown, FetchUsersBySearchActions&gt; =&gt;<br>  async (dispatch) =&gt; {<br>    dispatch(fetchSearchUsersRequest());<br>    try {<br>      const users = await fetchUserBySearch(userName);<br>      dispatch(fetchSearchUsersSuccess(users));<br>    } catch (error) {<br>      if (error instanceof Error) {<br>        dispatch(fetchSearchUsersFailure(error.message));<br>      } else {<br>        dispatch(fetchSearchUsersFailure(&#39;Oops something went wrong!!!&#39;));<br>      }<br>    }<br>  };</pre><p><em>Note: </em><strong><em>import { ApplicationState } from ‘../../store’;</em></strong><em> will throw error. But don&#39;t worry we will fix this when we set up our code</em></p><ol><li><strong>Action Creators</strong>: These are functions that create actions to be dispatched to the Redux store.</li></ol><ul><li>fetchTopUsersRequest, fetchTopUsersSuccess, and fetchTopUsersFailure: These functions create actions for the different stages of fetching the top users (request, success, and failure).</li><li>fetchSearchUsersRequest, fetchSearchUsersSuccess, and fetchSearchUsersFailure: Similar functions for fetching users by search.</li><li>toggleUserLike: Creates an action to toggle the like status of a user.</li></ul><p>2. <strong>Thunk Functions</strong>: These are functions that handle asynchronous operations and dispatch actions based on the results.</p><ul><li>getTopUsersBySize: This thunk function fetches the top users based on a specified size. It first dispatches fetchTopUsersRequest to indicate that the request has started. Then, it attempts to fetch the users using fetchTopUsersBySize from the services. If successful, it dispatches fetchTopUsersSuccess with the retrieved users. If there&#39;s an error, it dispatches fetchTopUsersFailure with the error message.</li><li>getUsersBySearch: Similar to getTopUsersBySize, this thunk function handles fetching users based on a search term. It dispatches fetchSearchUsersRequest to start then attempts to fetch the users using fetchUserBySearch. On success, it dispatches fetchSearchUsersSuccess with the users, and on failure, it dispatches fetchSearchUsersFailure with the error message.</li></ul><p>These action creators and thunk functions are crucial for handling the logic of fetching data and managing state transitions in our Redux application. By organizing our actions and action types this way, we create a clear and manageable structure for handling different user-related operations in our Redux setup. With these in place, we can move on to setting up our reducers to handle these actions.</p><p><strong>Next up, let’s set up our reducers. This is where our state management gets its game on</strong></p><p>This piece of code is crucial as it defines how our application’s state will be updated in response to various actions dispatched to the Redux store. Let’s break down what each part does.</p><pre>import {<br>  UserActions,<br>  UsersActionTypes,<br>  FetchTopUsersSuccessAction,<br>  FetchTopUsersFailureAction,<br>  ToggleUserLikeAction,<br>} from &#39;../actions/users/types&#39;;<br>import { Users } from &#39;../types/usersTypes&#39;;<br><br>interface UsersState {<br>  loading: boolean;<br>  users: Users | null;<br>  error: string | null;<br>}<br><br>const initialState: UsersState = {<br>  loading: false,<br>  users: null,<br>  error: null,<br>};<br><br>export const usersReducer = (<br>  state = initialState,<br>  action: UserActions<br>): UsersState =&gt; {<br>  switch (action.type) {<br>    case UsersActionTypes.FETCH_TOP_USERS_REQUEST:<br>    case UsersActionTypes.FETCH_USERS_BY_SEARCH_REQUEST:<br>      return {<br>        ...state,<br>        loading: true,<br>        error: null,<br>      };<br>    case UsersActionTypes.FETCH_TOP_USERS_SUCCESS:<br>    case UsersActionTypes.FETCH_USERS_BY_SEARCH_SUCCESS:<br>      return {<br>        ...state,<br>        loading: false,<br>        users: (action as FetchTopUsersSuccessAction).payload,<br>        error: null,<br>      };<br>    case UsersActionTypes.FETCH_TOP_USERS_FAILURE:<br>    case UsersActionTypes.FETCH_USERS_BY_SEARCH_FAILURE:<br>      return {<br>        ...state,<br>        loading: false,<br>        error: (action as FetchTopUsersFailureAction).payload,<br>      };<br><br>    case UsersActionTypes.TOGGLE_USER_LIKE: {<br>      const userId = (action as ToggleUserLikeAction).payload;<br>      if (!state.users) {<br>        return state; // Return state as is if users data is null<br>      }<br>      const updatedUsers = state.users.items.map((user) =&gt; {<br>        if (user.id === userId) {<br>          return {<br>            ...user,<br>            isLiked: !user.isLiked, // Toggle the liked property<br>          };<br>        }<br>        return user;<br>      });<br>      return {<br>        ...state,<br>        users: {<br>          ...state.users,<br>          items: updatedUsers,<br>        },<br>      };<br>    }<br>    default:<br>      return state;<br>  }<br>};</pre><ol><li><strong>State Interface and initial :</strong></li></ol><ul><li>UsersState: Defines the shape of our Redux state for users, including loading to indicate if data is being fetched, users to hold user data or null if not fetched yet, and error to store any error messages.</li><li>initialState: Initializes our UsersState with default values.</li></ul><p>2. <strong>Reducer Function:</strong></p><ul><li>usersReducer: This function handles state updates based on dispatched actions. It takes state and action as parameters.</li><li>switch statement: Evaluates action.type to determine how to update state.</li><li>FETCH_TOP_USERS_REQUEST and FETCH_USERS_BY_SEARCH_REQUEST: Sets loading to true and clears any existing error.</li><li>FETCH_TOP_USERS_SUCCESS and FETCH_USERS_BY_SEARCH_SUCCESS: Updates state with fetched users data from payload and sets loading to false.</li><li>FETCH_TOP_USERS_FAILURE and FETCH_USERS_BY_SEARCH_FAILURE: Updates state with error message from payload and sets loading to false.</li><li>TOGGLE_USER_LIKE: Toggles the isLiked property of a user identified by userId. It maps through state.users.items to find the user, toggles isLiked, and returns a new array updatedUsers. Finally, it updates the state with updatedUsers. Why so much circus, you ask? Remember, state is immutable, so we have to create a new copy.</li></ul><p>3. <strong>Default case:</strong> Returns state as is if the action type doesn&#39;t match any case.</p><p>This reducer acts as the navigator for our state.</p><p>Let’s create a root reducer. We use combineReducers to create a rootReducer. combineReducers simplifies the management of the Redux state by allowing you to split the state management logic into separate, specialized reducers. By combining our reducers into a single rootReducer, we enable our Redux store to manage the state of different parts of our application in an organized and scalable way.</p><pre>import { combineReducers } from &#39;redux&#39;;<br>import { usersReducer } from &#39;./userReducer&#39;;<br><br>// Combine Reducers<br>const rootReducer = combineReducers({<br>  users: usersReducer,<br>});<br><br>// export type AppState = ReturnType&lt;typeof rootReducer&gt;;<br>export default rootReducer;</pre><p>Now that our actions and reducer are working together seamlessly, it’s time to build the foundation of our Redux state — the store!</p><p><strong>Next up, let’s dive into setting up the store.</strong></p><p>But before that let&#39;s export our application action types which we will be using in our application</p><pre>import { UserActions } from &#39;../actions/users/types&#39;;<br><br>export type AppActionTypes = UserActions ;</pre><p>Here’s the code that sets up our Redux store, where all the magic happens:</p><pre>import {<br>  applyMiddleware,<br>  compose,<br>  legacy_createStore as createStore,<br>} from &#39;redux&#39;;<br>import { thunk, ThunkDispatch } from &#39;redux-thunk&#39;;<br>import rootReducer from &#39;../reducers&#39;;<br>import { AppActionTypes } from &#39;../types/types&#39;;<br>import loggingMiddleware from &#39;../middlewares/logging&#39;;<br><br>declare global {<br>  interface Window {<br>    __REDUX_DEVTOOLS_EXTENSION_COMPOSE__?: typeof compose;<br>  }<br>}<br><br>// Define middleware array<br>const middleware = [thunk, loggingMiddleware];<br><br>const composeEnhancers =<br>  (typeof window !== &#39;undefined&#39; &amp;&amp;<br>    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) ||<br>  compose;<br><br>export const store = createStore(<br>  rootReducer,<br>  undefined,<br>  composeEnhancers(applyMiddleware(...middleware))<br>);<br><br>export type ApplicationState = ReturnType&lt;typeof rootReducer&gt;;<br>export type ApplicationDispatch = ThunkDispatch&lt;<br>  ApplicationState,<br>  unknown,<br>  AppActionTypes<br>&gt;;</pre><ul><li><strong>Window Declaration</strong>: We declare a global interface to make our store compatible with the Redux DevTools Extension, ensuring smooth communication between them.</li><li><strong>Middleware Setup</strong>: We assemble our middleware team including thunk and loggingMiddleware, ready to handle tasks like asynchronous actions and logging activities.</li><li><strong>Compose Enhancers</strong>: This function creates a composer that combines middleware and enhances our store, making sure everything works together smoothly. It also integrates with the Redux DevTools Extension if available, because even stores like to look good!</li><li><strong>Store Creation</strong>: Using createStore, we instantiate our Redux store. It takes rootReducer to manage our state starts with undefined as our initial state, and applies middleware to manage actions and state changes effectively.</li><li><strong>Types Definitions</strong>: Finally, we define ApplicationState as the type of our Redux state managed by rootReducer, and ApplicationDispatch as the type of our dispatch function, ensuring type safety throughout our Redux journey.</li></ul><pre>import { Middleware } from &#39;redux&#39;;<br>import { ApplicationState } from &#39;../store&#39;;<br><br>const loggingMiddleware: Middleware&lt;object, ApplicationState&gt; =<br>  (store) =&gt; (next) =&gt; (action) =&gt; {<br>    // Log the action<br>    console.log(&#39;Action:&#39;, action);<br><br>    // Get the current state before the action is dispatched<br>    const prevState = store.getState();<br><br>    // Dispatch the action<br>    const result = next(action);<br><br>    // Get the state after the action is dispatched<br>    const nextState = store.getState();<br><br>    // Log the state changes<br>    console.log(&#39;Prev State:&#39;, prevState);<br>    console.log(&#39;Next State:&#39;, nextState);<br><br>    return result;<br>  };<br><br>export default loggingMiddleware;</pre><p>With our store set up, our Redux state management is all set to handle the complexities of our application. Now, let’s watch our store and reducers work their magic as we bring our application to life!</p><p>Before we start building our pages, let’s wrap our entire application with &lt;Provider store={store}&gt;. This makes the Redux store available to all components in the component tree. The store is passed as a prop, representing your Redux store instance.</p><p><em>Add this code in main.tsx</em></p><pre>&lt;Provider store={store}&gt;<br>      &lt;div className=&quot;min-h-screen flex  justify-center bg-gray-100&quot;&gt;<br>        &lt;div className=&quot;w-full max-w-screen-lg m-4 p-4 bg-white rounded shadow-md&quot;&gt;<br>          &lt;h1 className=&quot;text-4xl font-bold text-blue-900 mb-4 tracking-wider uppercase&quot;&gt;<br>            GitHub Finder<br>          &lt;/h1&gt;<br>          &lt;RouterProvider router={router} /&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/Provider&gt;</pre><p>I know this article is getting a bit hefty, but hey, setting up our Redux state management takes some effort — hence why they invented the Redux Toolkit, which I’ll cover in the next series. Now that I’ve hopefully won back your trust, let’s dive into the application!</p><p><strong>useSelector and useDispatch hook</strong></p><p>In React Redux, useSelector and useDispatch hooks streamline how components interact with the Redux store.</p><p><strong>useSelector</strong>: This hook allows components to select specific slices of the Redux state, optimizing data access and minimizing unnecessary renders.</p><p><strong>useDispatch</strong>: Used for dispatching actions, useDispatch empowers components to trigger state changes and manage asynchronous operations within the application.</p><p>In our application, using the useSelector hook looks like this:</p><pre>const state = useSelector((state:ApplicationState) =&gt; state.users);</pre><p>Importing ApplicationState every time can be a bit tedious. So, instead, I prefer creating a custom hook that I can use across our application. This is how my custom hook will look:</p><pre>export const useAppSelector: TypedUseSelectorHook&lt;ApplicationState&gt; =<br>  useSelector;</pre><p>It’s like creating your own shortcut — because who doesn’t love shortcuts in coding, right?</p><p>Similarly, using the useDispatch hook in our application looks like this:</p><pre>const dispatch = useDispatch&lt;ApplicationDispatch&gt;();</pre><p>Again, dealing with ApplicationDispatch repeatedly can be a hassle. So, here&#39;s how my custom hook simplifies things:</p><pre>export const useAppDispatch: () =&gt; ApplicationDispatch = useDispatch;</pre><p>Now that we have our custom hooks in place, let’s dive into building our user list page. With useAppSelector for accessing the Redux state and useAppDispatch for dispatching actions, we&#39;re all set to create a seamless user experience. Let&#39;s get started!</p><pre>import React, { useEffect } from &#39;react&#39;;<br>import SearchBox from &#39;../components/SearchBox&#39;;<br>import {<br>  getTopUsersBySize,<br>  getUsersBySearch,<br>  toogleUserLike,<br>} from &#39;../redux/actions/users/actions&#39;;<br>import Loading from &#39;../components/Loading&#39;;<br>import Error from &#39;../components/Error&#39;;<br>import { NavLink } from &#39;react-router-dom&#39;;<br>import { useAppDispatch, useAppSelector } from &#39;../hooks/hooks&#39;;<br>import LikeButton from &#39;../components/LikeButton&#39;;<br><br>const Home: React.FC = () =&gt; {<br>  const { loading, users, error } = useAppSelector((state) =&gt; state.users);<br>  const dispatch = useAppDispatch();<br>  const handleSearch = (query: string) =&gt; {<br>    if (query) {<br>      dispatch(getUsersBySearch(query));<br>    } else {<br>      dispatch(getTopUsersBySize());<br>    }<br>  };<br>  useEffect(() =&gt; {<br>    dispatch(getTopUsersBySize());<br>  }, [dispatch]);<br><br>  return (<br>    &lt;div className=&quot;container mx-auto p-4 flex flex-col&quot;&gt;<br>      &lt;div className=&quot;flex justify-center mb-6&quot;&gt;<br>        &lt;div className=&quot;w-2/3&quot;&gt;<br>          &lt;SearchBox placeholder=&quot;Search user...&quot; onSearch={handleSearch} /&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;hr /&gt;<br>      &lt;h2 className=&quot;text-2xl text-blue-700 font-bold my-4&quot;&gt;<br>        Users - {users?.total_count}<br>      &lt;/h2&gt;<br>      {loading ? (<br>        &lt;Loading /&gt;<br>      ) : error ? (<br>        &lt;Error message={error} /&gt;<br>      ) : (<br>        &lt;div<br>          className=&quot;flex-grow  overflow-y-auto&quot;<br>          style={{ maxHeight: &#39;calc(100vh - 300px)&#39; }}<br>        &gt;<br>          &lt;ul className=&quot;grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6&quot;&gt;<br>            {users?.items.map((user) =&gt; (<br>              &lt;li<br>                key={user.login}<br>                className=&quot;flex items-center space-x-4 p-4 bg-white rounded shadow hover:shadow-lg transition-shadow&quot;<br>              &gt;<br>                &lt;img<br>                  src={user.avatar_url}<br>                  alt={`${user.login} avatar`}<br>                  className=&quot;w-16 h-16 rounded-full&quot;<br>                /&gt;<br>                &lt;div className=&quot;flex flex-col gap-0.5&quot;&gt;<br>                  &lt;span className=&quot;text-lg text-blue-950 font-medium&quot;&gt;<br>                    {user.login}<br>                  &lt;/span&gt;<br>                  &lt;div className=&quot;flex gap-2&quot;&gt;<br>                    &lt;NavLink<br>                      className=&quot;underline underline-offset-2 text-orange-500 hover:text-orange-600&quot;<br>                      to={`/${user.login}/repos`}<br>                    &gt;<br>                      View repos<br>                    &lt;/NavLink&gt;<br>                    &lt;div&gt;<br>                      &lt;LikeButton<br>                        liked={!!user.isLiked}<br>                        toggleLike={() =&gt; dispatch(toogleUserLike(user.id))}<br>                      /&gt;<br>                    &lt;/div&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              &lt;/li&gt;<br>            ))}<br>          &lt;/ul&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Home;</pre><ul><li><strong>State Management</strong>: The useAppSelector hook is used to access the Redux state, specifically state.users which contains the loading status (loading), user data (users), and error messages (error).</li><li><strong>Dispatch Function</strong>: useAppDispatch is used to get the dispatch function dispatch, allowing components to dispatch actions like getTopUsersBySize, getUsersBySearch, and toogleUserLike.</li></ul><p>You can find the routing code in my repository</p><p>If you run your application now, voila! Behold the User List page in all its glory. Congratulations, we made it! 🎉 Feel free to play around with this code and challenge yourself to implement a Repository page on your own. And remember, if you need a little nudge in the right direction, our <a href="https://github.com/suhas86/git-clone-react-redux/tree/feature/old-redux">repository </a>is there to lend a helping hand. Go ahead, dive in and enjoy exploring your new creation!</p><p>I know this article was quite lengthy, but setting up a traditional Redux application can indeed be time-consuming — something even this powerful library has faced criticism for. However, fear not! The Redux team has embraced this feedback with open arms and introduced the Redux Toolkit, a major update that addresses many of these pain points. It’s like Redux just got a makeover and we’re falling in love with it all over again!</p><p>Curious about how to migrate your application to Redux Toolkit? Stay tuned for part two. Cheers to simpler, more enjoyable state management!</p><p>Happy Coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=564b858de3fe" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/migrating-from-redux-to-redux-toolkit-a-three-part-series-564b858de3fe">Migrating from Redux to Redux Toolkit: A Three-Part Series</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build TODO APIs by learning Nest Framework]]></title>
            <link>https://levelup.gitconnected.com/build-todo-apis-by-learning-nest-framework-95a83979ce5a?source=rss-a50fbe23201d------2</link>
            <guid isPermaLink="false">https://medium.com/p/95a83979ce5a</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nestjs-tutorial]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[nest]]></category>
            <dc:creator><![CDATA[suhas murthy]]></dc:creator>
            <pubDate>Sun, 22 Aug 2021 09:40:33 GMT</pubDate>
            <atom:updated>2021-08-22T20:23:02.987Z</atom:updated>
            <content:encoded><![CDATA[<p>The key to build any application is its architecture. Working on Node.js architecture has always been my pain area and that’s one of the main reasons why I started exploring the Nest.JS framework. In this article, I will try to share my thoughts and experience about learning the Nest.Js framework (Hint: If you are an Angular developer you will love Nest 😎)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyEKW8WvT5-eeajWTD3Fvg.png" /></figure><p><strong>What is Nest (</strong><a href="https://docs.nestjs.com/"><strong>Documentation</strong></a><strong> covers it all </strong>😊)</p><blockquote>It’s a framework for building efficient, scalable Node.js server-side applications</blockquote><p>Nest.JS supports TypeScript. It makes use of Express.JS under the hood, But also supports Fastify 👏👏</p><p>More information can be found on their official website. So let&#39;s straight away dive into building the TODO app 💥💥💥</p><h3><strong>Setting up our TODO app</strong></h3><p>We can get started by either using NEST CLI or by cloning through <a href="https://github.com/nestjs/typescript-starter.git%20project">Github</a></p><p>In this example, we will be using CLI and I suggest you follow the same as we will see in future sections on how CLI helps us in generating files.</p><p>So first step is to install nest globally</p><pre>npm i -g @nestjs/cli</pre><p>After installing Nest CLI globally. Let&#39;s create our project</p><pre>nest new todo-api</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*lRcOnhq3QTUdOjOv5sUCuA.png" /><figcaption>select package manager you ❤️. For me its yarn 🙂</figcaption></figure><p>On successfully creating a project your application should look something similar to this on your IDE. Your initial setup is ready 🎊🎊🎊</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-dK7vJeF6bLWxGlzu9-jfg.png" /><figcaption>vscode editor</figcaption></figure><h3>Designing APIS</h3><p>Alright every API sends a request to a server and the server responds with a response (Obviously right? 😂)</p><p>But let&#39;s go one step further and try to understand what happens within the server 🤔</p><p>Let&#39;s assume we are requesting to get a list of todos for a given date</p><blockquote><strong><em>First step:</em></strong> The server should <strong>validate</strong> if the given date is valid say in our case it has to be current or future dates ✅✅</blockquote><blockquote><strong>Second step:</strong> The server should ensure that the request is coming from <strong>authenticated</strong> user 🔑🔑</blockquote><blockquote><strong><em>Third step:</em></strong><em> We can define many functions but our server has to make sure it </em><strong><em>routes</em></strong><em> to required function </em>🎯🎯</blockquote><blockquote><strong>Fourth step: </strong>We may need to run some <strong>business logic</strong> with the server to fetch data from database 🕴️🕴️</blockquote><blockquote><strong>Fifth step:</strong> Finally fetch the data from our <strong>database </strong>📊📊</blockquote><p>Now let&#39;s map how the nest framework solves these problems</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*LEwozjrm-QiRTeWVqLLrzg.png" /><figcaption>Tools available in nest framework ❤️</figcaption></figure><p>Ok Now, let&#39;s see how we can use these tools to build our todo app.</p><h3>Modules</h3><p>Let&#39;s set our data database. But before doing it we need to understand Nest uses <a href="https://docs.nestjs.com/modules"><strong>modules</strong></a>. Class with module annotation represents Modules. The module helps us group our code 🧱.</p><p>Every application will have a root module. In our application, it&#39;s called <strong>AppModule</strong>.</p><p>Every functionality or module can have its own modules. We can already see a major advantage of using the nest framework. By grouping code, it becomes loosely coupled and easy to read our application 🤩</p><p>In this application, we will have three modules</p><ol><li>AppModule: Root of our application</li><li>Todo: To include todo features</li><li>Auth: To include authentication feature(Will be covered in part 2)</li></ol><h3>Database</h3><p>For this example, we will be using the <a href="https://sqlite.org/index.html"><strong>SQLite</strong></a><strong> </strong>database and <a href="https://docs.nestjs.com/techniques/database"><strong>TypeOrmModule</strong></a></p><p>Let&#39;s install the dependency packages</p><pre>yarn add @nestjs/typeorm typeorm sqlite3</pre><p>We need to import modules that exports providers which are required</p><p>To set up the database we need TypeORmModule. So let’s add TypeOrm to imports and provide options required to set up SQLite database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5pGq2M51svLRb4tZl7Vdmg.jpeg" /></figure><p>Basically what we are doing is importing a TypeOrm module for root by passing database configuration. Please note synchronize true has to be used only for development. For production, we need to handle migration.</p><p>This should create a database when we launch our application on the root directory. You can use <a href="https://marketplace.visualstudio.com/items?itemName=alexcvzz.vscode-sqlite">this</a> extension to view SQLite</p><pre>yarn start:dev</pre><p>You can find the source code for the initial setup <a href="https://github.com/suhas86/nest-todo-api/tree/25690f8cac35526ab23b90bbb3f3b0a59ac0ac78">here</a></p><h3>Creating a module</h3><p>Let&#39;s start with the Todo module 🧱.</p><p>As I mentioned earlier modules are nothing but a grouping of our code.</p><p>Todo module will have <strong>controllers, service, and repository</strong> (Refer to designing API section to know why we require these things). We will be using Nest CLI to create controllers and service</p><p>So to create a todo module open the terminal and type nest g module todos</p><p>This will create a directory called todos and also create a file with boilerplate code. It also informs our root module that is AppModule by adding TodosModule to the imports array</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*GnmlOekTOwt743AdFUwruQ.jpeg" /></figure><p>Now let’s create a <strong>controller and service</strong>. Open terminal and type <strong>nest g controller todos</strong> to create a controller and <strong>nest g service todos</strong> to create a service. This will also add a TodosController to the controller&#39;s array in the todos module and TodosService to the provider’s array</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*hSNKpWqZMFtpddhKXcUnTg.png" /><figcaption>todos.module.ts</figcaption></figure><p>Code for this section can be downloaded <a href="https://github.com/suhas86/nest-todo-api/tree/feature/setup-todo-module">here</a></p><h3>Entity</h3><p>An entity is very similar to creating modals in typescript or any other language. An entity will tell all the properties that should be present in a particular module in our case it&#39;s the Todos module. NestJS will internally create repositories for these entities.</p><h4>Creating an Entity</h4><p>First, let&#39;s create an entity file with all the properties required for the todos module. So let&#39;s create todos.entity.ts inside the todos folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*_5okEx8lC8Ra7RYOyKqIqQ.png" /><figcaption>todos.entity.ts</figcaption></figure><p>Now let&#39;s speak about the decorators used. The<strong> Entity</strong> decorator is to create the Database schema for all classes decorated with it, and Repository can be retrieved and used for it.</p><p><strong>PrimaryGeneratedColumn</strong> is to tell that it&#39;s a primary key and it has to be auto-generated</p><p><strong>The Column</strong> is to tell that it&#39;s a table column.</p><p>The next step is to connect our entity to the parent module. This will make Nest create a repository behind the scenes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*Brc5MkeVZwXAai7oll3Fcg.jpeg" /><figcaption>todos.module.ts</figcaption></figure><p>Now the final step is to connect it to the app module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*7IZ0-L5mihWDBMyW-ZbXhQ.jpeg" /><figcaption>app.module.ts</figcaption></figure><p>Code for this section can be downloaded <a href="https://github.com/suhas86/nest-todo-api/tree/feature/entity">here</a>.</p><h3>Routes</h3><p>Now it&#39;s time to create routes. We create routes in the controller. For the todo module, we will have four routes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*GDbWc4o2LMSJYpXqK0uULg.png" /><figcaption>todos.controller.ts</figcaption></figure><p>It&#39;s very simple to add routes. You can define method type using Get, Post, Put, Patch, or delete annotations.</p><p>You define the route name by passing a string value to Controller annotation. You can also have a specified path to each route by setting the value to its equivalent routes.</p><p>You can test these API using postman or <a href="https://marketplace.visualstudio.com/items?itemName=humao.rest-client">Rest client extensions</a> in VS Code. I personally prefer Rest client extension. You can todos.http file under api-requests folder</p><p><strong>Note: </strong>We will get rid of any in our future section 🚨🚨</p><p>Code for this section can be found <a href="https://github.com/suhas86/nest-todo-api/tree/feature/routes">here</a></p><h3>Service</h3><p>We are very close to see APIs in action. I promise 😀</p><p>The first step is to add our todos repository to our todos service</p><p>We do that by injecting a repository in our todos.service.ts constructor</p><pre>constructor(@<em>InjectRepository</em>(Todos) <em>private</em> repo: Repository&lt;Todos&gt;) {}</pre><p>By injecting the repository we can find entities, insert, update, delete, etc.💥</p><p>Let&#39;s add service methods to the routes defined in the controller</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*OCKPeiCP7ZDlBNODC6mT9w.png" /><figcaption>todos.service.ts</figcaption></figure><p>Hope the inline comments will help in understanding what each method does 🤞</p><p>Now let&#39;s connect methods defined in service to their respective routes in the controller</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*nFpwb4t8X6osiDi5zXL8Gg.png" /><figcaption>todos.controller.ts</figcaption></figure><p><strong>Note:</strong> Have added default value to isCompleted our todo entity. You can find updated code in the git repository 🚨🚨</p><pre>@<em>Column</em>({ default: false })</pre><pre>isCompleted: boolean;</pre><p>Now try creating todo using Rest client or postman</p><pre><em>POST</em> http://localhost:3000/todos</pre><pre>content-type: application/json</pre><pre>{</pre><pre>&quot;todo&quot;:&quot;First todo&quot;,</pre><pre>&quot;description&quot;:&quot;First todo description&quot;</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*BYJGCO4Rh4rDlClynDUrLw.gif" /></figure><p>Finally 💥💥💥💥💥. You can also test other API and it should work</p><p>You can download code for this section <a href="https://github.com/suhas86/nest-todo-api/tree/feature/service">here</a></p><p>Everything looks great right? Let&#39;s add a final block to our todo module</p><h3>Validation Pipes</h3><p><a href="https://docs.nestjs.com/techniques/validation">Validating</a> incoming requests is very important to any API as it will minimize the security risks as well as unwanted errors when we try to fetch data from the database</p><p>Let&#39;s start by installing dependency to create a validation pipe ✅</p><pre>yarn add class-validator class-transformer</pre><p>In Nest, we create data transfer objects (DTOs) and use a class validator to validate our incoming data</p><p>Let&#39;s start with create-todo.dto.ts under dtos folder inside todos module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*DUh9mUmamfrTFrYp-tuHIQ.png" /><figcaption>create-todo.dto.ts</figcaption></figure><p>Now let&#39;s replace any from createTodo method body to use CreateTodoDto</p><pre>@<em>Post</em>()</pre><pre><em>createTodo</em>(@<em>Body</em>() body: CreateTodoDto) {</pre><pre><em>return</em> this<em>.todosService.create</em>(body);</pre><pre>}</pre><p>Let&#39;s repeat the same for service as well</p><pre><em>create</em>(body: CreateTodoDto) {</pre><pre>/**<em> We create todo object first and then save the record to our database </em>*/</pre><pre>const<em> todo </em>=<em> this.repo.create</em>(<em>body</em>);</pre><pre><em>return</em> this<em>.repo.save</em>(todo);</pre><pre>}</pre><p>And finally, we need to register validation pipe globally in main.ts file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*L2aRiiaGyuGwqvR0XT4AHQ.jpeg" /><figcaption>main.ts</figcaption></figure><p>Now if we remove we send an invalid request we should get response code 400 with validation errors.</p><p>Code for this section can be found <a href="https://github.com/suhas86/nest-todo-api/tree/feature/validations">here</a></p><h3>Conclusion</h3><p>🎊🎊🎊🎊🎊</p><p>This concludes the todo module. You can download the final code <a href="https://github.com/suhas86/nest-todo-api">here</a></p><p>I will extend this codebase and add authentication in Part 2 🔜.</p><p>I am enjoying learning NestJs and hope my experience will help you in some way. The framework really offers you so many features say for example handling errors. You need not have to define errors for every response code. NestJs does it for you. The Module structure makes it very easy to find any piece of code.</p><p>Of course like all frameworks, NestJs is challenging sometimes.👊👊</p><p>Especially when you are using decorators or when you inject dependency injection. But once we understand core functionalities it helps you build maintainable enterprise apps.</p><p>Personally, I may not opt for Nest if I am building a small scale or some hobby application but I would definitely prefer the Nest framework if I am building an enterprise application that requires maintenance and scalability</p><p>Some of the features I am excited to explore and learn in near future are GraphQl support, Websockets, and my favorite Microservices. 🤩🤩🤩</p><p>Hope you enjoyed my explanation of how to work with the Nest framework.</p><p>Happy Coding!!! Cheers !!! 🍻🍻🍻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95a83979ce5a" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/build-todo-apis-by-learning-nest-framework-95a83979ce5a">Build TODO APIs by learning Nest Framework</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overview of TypeScript and Types: Part 1]]></title>
            <link>https://medium.com/swlh/overview-of-typescript-and-types-part-1-e9fc5247388?source=rss-a50fbe23201d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9fc5247388</guid>
            <category><![CDATA[basic-types]]></category>
            <category><![CDATA[functions-typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[suhas murthy]]></dc:creator>
            <pubDate>Sun, 20 Dec 2020 10:54:20 GMT</pubDate>
            <atom:updated>2020-12-20T10:54:20.042Z</atom:updated>
            <content:encoded><![CDATA[<p>In the series of articles, I will try to share my learnings of TypeScript hoping it would help you to get an overview of TypeScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*RQqIUrGzxKnCqOSyfkj58w.png" /></figure><p>While using JavaScript how often we make mistakes referring variables with the wrong type. How many of us have experienced the famous undefined is not an object? 😀. How many times do we refer to API documentation or previously written code to know whats the key we need to refer to to get a value from the object? How many of us have experienced difficulties in maintaining code?</p><p><strong>Why I use TypeScript</strong></p><p>To avoid the above problems I started using TypeScript. It was invented to identify these issues before we run our code and minimize the bugs in our application. Like all programming, languages TypeScript doesn&#39;t solve creating bugs. We programmers create bugs 😊. TypeScript helps us minimizing these bugs.</p><p><strong>JavaScript to TypeScript?</strong> 🤔</p><p>TypeScript is a superset of JavaScript. So any Javascript code is also a valid TypeScript code. This gives us a considerable advantage if want to introduce TypeScript to our existing code. We need not have to rewrite everything or wait till we master everything in TypeScript. We can update our code gradually and apply whatever we learn in TypeScript slowly so that the productivity of our product is not compromised.</p><p>Browsers will not understand TypeScript but we do have developer tools like Babel or Webpack which can be used to configure and process our TypeScript code.</p><p><strong>How to configure TypeScript</strong></p><p>We can install TypeScript globally using</p><pre>npm install -g typescript</pre><p>Once TypeScript is installed run <strong><em>tsc </em></strong>command to run the TypeScript compiler</p><p>We can also run the above command using</p><pre>npx tsc</pre><p>We need to have a configuration file in our project which will tell Typescript how we want to run its compiler</p><pre>tsc --init</pre><p>This will create <strong>tsconfig.json</strong> file. tsc command will type check and compile our code to JavaScript. It will check <strong>tsconfig.json </strong>and pick the configuration option we set in this file.</p><p>tsconfig.json file comes with many configuration options I would suggest to go through the <a href="https://www.typescriptlang.org/tsconfig">official document </a>to know more. We need to be careful while changing the properties and make sure it doesn&#39;t take away the key properties of TypeScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*rezTy0jgx8VbzT_9y_CQBg.png" /></figure><p><strong>Basics of TypeScript</strong></p><p>Let&#39;s go through a few basics of TypeScript in this article</p><pre><strong>// JavaScript Snippet</strong></pre><pre>let name = &#39;suhas&#39;;</pre><pre>name = 1;</pre><pre>console.log(name);</pre><p>In the above Javascript code snippet, we have a variable called name. But we are able to assign both string and number. Now let&#39;s see how TypeScript solves this issue by using type checking</p><pre><strong>// TypeScript snippet</strong></pre><pre>let name:string;</pre><pre>name = &#39;suhas&#39;;</pre><pre>name =1;  // =&gt; Type Error: Type &#39;number&#39; is not assignable to type &#39;string&#39;.</pre><p>In TypeScript the same snippet throws an error because have added type annotation to the variable name.</p><p>TypeScript also supports implicit type checking. In the below example Typescript automatically reads our code and determines the type of the value string in our case.</p><pre>let name = &#39;suhas&#39;;</pre><p>Type annotations can also be used in functions. Below is one simple example</p><pre>function incrementByTwo(value:number) {<br>  return value + 2;<br>}</pre><pre>// TypeScript implicits the return type but we can add explicit to // ensure we do not return wrong type</pre><pre>function incrementByTwo(value:number):number {<br>  return value + 2;<br>}</pre><p>We do come across a situation where we have no way to figure out the type or it may complicate knowing the type. For such cases, Typescript has two types that can be used. That is <strong>any </strong>and<strong> unknown.</strong></p><p><strong><em>any </em></strong>type disables type checker and the variable can be of any type. Say we have to make a network call and we can&#39;t know the type the network call returns. We can use any in this situation. Below example, the type of users would be any</p><pre>async function getUsers() {<br>   const response = await fetch(&#39;http://xyz.com/users&#39;);<br>   const users = await response.json();<br>}</pre><p>Let&#39;s take another example where we have a function that will tell if the value passed to the function is even or odd</p><pre>function isOdd(value:any) {</pre><pre>return value % 2;</pre><pre>}</pre><pre>isOdd(&quot;suhas&quot;)</pre><p>If I pass a string value to this function. TypeScript doesn&#39;t throw any error because its value can be any. Now during these kinds of a scenario where we do not know the type but still want to give some type guarantee, we use <strong>unknown</strong> type</p><p><strong>unknown</strong> type describe the type of variables that we do not know when we are writing an application. Let&#39;s take a simple example</p><pre>let name:unknown = &#39;Suhas&#39;;<br>const fullname:string = name; // Type Error: Type &#39;unknown&#39; is not assignable to type &#39;string&#39;.</pre><p>You can assign any type of value to an unknown variable but we cannot assign an unknown value to any variables.</p><p>But as mentioned earlier unknown does give us some type of guarantee. Let&#39;s go back to the above example. for variable fullname, we can assign only type string. we can do that for unknown type variables using type narrowing.</p><pre>let name:unknown = &#39;Suhas&#39;;</pre><pre>if(typeof name === &#39;string&#39;) {</pre><pre>   const fullname:string = name;</pre><pre>}</pre><p>This concludes Part 1. In the next part, I will try to share my learning on Interface, Literal Types, Classes, Enums, Unions, and Intersections types.</p><p>Hope this article helped you with some overview of TypeScript</p><p>Happy Coding!!! Cheers !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9fc5247388" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/overview-of-typescript-and-types-part-1-e9fc5247388">Overview of TypeScript and Types: Part 1</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a demo E-commerce application using React.js]]></title>
            <link>https://medium.com/swlh/building-a-demo-e-commerce-application-using-react-js-a39494a10e9b?source=rss-a50fbe23201d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a39494a10e9b</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-material-ui]]></category>
            <category><![CDATA[react-context]]></category>
            <category><![CDATA[e-commerce-solution]]></category>
            <dc:creator><![CDATA[suhas murthy]]></dc:creator>
            <pubDate>Tue, 15 Sep 2020 14:31:48 GMT</pubDate>
            <atom:updated>2020-09-15T14:52:33.503Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oYJ3BSTLjodVYTsVQMXi4A.jpeg" /></figure><p>Most often we try to master the concepts we learn by building an application that will cover most of the scenarios required to build a real-world application and to showcase it in our profile.</p><p>E-commerce is one domain that we can relate to easily as we have used many e-commerce applications and have an overview of how it works.</p><p>Also, I feel building an e-commerce application is kind of exciting as we are surrounded by online selling these days.</p><p>But the problem for frontend developers is to explore building e-commerce they need APIs to make it look like a real app if the not complete real application.</p><p>While exploring options to build an e-commerce application without investing my time on APIs I came across <a href="https://fakestoreapi.com/">https://fakestoreapi.com/</a> where you can find all the fake API required to build an E-commerce app.</p><p>By using this I have built a basic e-commerce app using react.js which I would like to share hoping it would help others who want to build a demo e-commerce application for practice or to add it to their profile. The demo application has been hosted on GitHub. (<a href="https://suhas86.github.io/react-ecomm-sample/">https://suhas86.github.io/react-ecomm-sample/</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hPNIEIGsIAwr-Z3EldRU-w.png" /><figcaption><a href="https://suhas86.github.io/react-ecomm-sample/">https://suhas86.github.io/react-ecomm-sample/</a></figcaption></figure><h3><strong>A brief overview of how the application is built</strong></h3><p>The web application is built on the latest version of react.js and styling is done using <a href="https://material-ui.com/">material-ui</a>.</p><p>I have used <a href="https://fakestoreapi.com/">https://fakestoreapi.com/</a> to fetch a list of products and a single product</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvl2qCoZ6bJgE0h1xcYn9w.png" /></figure><p>The cart is built using the React context and it is not connected to any API so the data we see in the cart is cached data and will be deleted when we reload the page. If you are new to react context you can find my article on react context <a href="https://levelup.gitconnected.com/react-context-using-typescript-c717f1dee2d1">here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPRyEMmbHQuYTyNEUMStkQ.png" /></figure><p>For making API calls I have used Axios and a custom hook to make API calls which will help us reduce the effort in making calls inside our component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f811f30e970eb305490149fda250796/href">https://medium.com/media/9f811f30e970eb305490149fda250796/href</a></iframe><p>The checkout page is a dummy page built using <a href="https://material-ui.com/components/steppers/#stepper">Material-UI stepper</a> and useReducer hook to manage the state on the main component. Validations have not been handled in this application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Krj3db9ueR5OnScZpFtJQ.png" /></figure><p>The entire code of this application can be found in <a href="https://github.com/suhas86/react-ecomm-sample">GitHub</a> and a live link <a href="https://suhas86.github.io/react-ecomm-sample/">here</a></p><p><a href="https://github.com/suhas86/react-ecomm-sample">suhas86/react-ecomm-sample</a></p><p>Hope this helps you in some way building a sample e-commerce application.</p><p>Happy Coding!!! Cheers !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a39494a10e9b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/building-a-demo-e-commerce-application-using-react-js-a39494a10e9b">Building a demo E-commerce application using React.js</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlearning Agile(Scrum) to relearn it the right way [Part 1]]]></title>
            <link>https://medium.com/swlh/unlearning-agile-scrum-to-relearn-it-the-right-way-part-1-e6146b9b4e3f?source=rss-a50fbe23201d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6146b9b4e3f</guid>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[scrum]]></category>
            <category><![CDATA[scrum-master]]></category>
            <category><![CDATA[sprint-planning]]></category>
            <category><![CDATA[sprint-goal]]></category>
            <dc:creator><![CDATA[suhas murthy]]></dc:creator>
            <pubDate>Mon, 17 Aug 2020 13:52:36 GMT</pubDate>
            <atom:updated>2023-01-29T12:05:50.018Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unlearning Agile(Scrum) to relearn it the right way</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9woU7u6lss3k7AFWiZUd1A.jpeg" /></figure><p>Recently I took professional scrum master training and after two days I realized that the challenge is not learning Agile but unlearning my understanding of agile. In this article let me share my experience in unlearning Sprint planning and Velocity to learn it the right way</p><h3><strong>Storytime</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*touX6TFolZKgZkdALiLB_A.jpeg" /><figcaption>Image from Espncricinfo</figcaption></figure><p>How many of you remember the Historic test match between India vs Australia which happened in the year 2003 in Adelaide.</p><p>Australia had scored a mammoth 556 runs in the first innings and at one stage scorecard of India was 85 with four wickets down but India went on to win the test match and created a History.</p><p><strong><em>Reason:</em></strong><em> </em>The<em> </em>partnership of 303 runs between VVS Laxman and Rahul Dravid(Ofcourse Dravid and Laxman name has to come when you speak about historic victories against Australia 😀)</p><p>Recalling this test match in one of the interviews VVS Laxman stated</p><blockquote>Somehow after that Kolkata Test, whenever we were in a tough situation we would always remember that. And we would talk about what we did there.So we would always look to set small goals and play to the merit of the ball. You are 85 for 4 and they have scored 550-plus. It’s too big a target. So you have to have smaller goals, probably one over, ten overs, and then a session. That’s how it panned out.</blockquote><h3><strong>Learnings from this incident</strong></h3><p><strong>Empiricism:</strong> Both Dravid and Laxman took decision-based on the experience of the Kolkota test match</p><p><strong>Inspection and Adaptation: </strong>They inspected the situation they were in i.e 85 for 4 and had just lost their captain and adapted accordingly.</p><p><strong>Goal: </strong>The key to their successful winning partnership is the goals they had set. They kept goals for each session and both played towards achieving the goal.</p><h3><strong>Sprint Planning</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t5mD8SNrFPAnclF3xBOImw.png" /></figure><p>Key points of Sprint planning</p><p>Scrum guide states Sprint planning is</p><blockquote>The work to be performed in the Sprint is planned at the Sprint Planning. This plan is created by the collaborative work of the entire Scrum Team.</blockquote><blockquote>Sprint Planning answers the following:</blockquote><blockquote>What can be delivered in the Increment resulting from the upcoming Sprint?</blockquote><blockquote>How will the work needed to deliver the Increment be achieved</blockquote><p>In Sprint planning The Scrum Master, Product Owner, and the Development Together carve out the <strong>Sprint Goal</strong>.</p><h3>Relating Sprint Planning to the above Story</h3><p>During their partnership, Laxman Dravid carved goals (<strong>Sprint goal) </strong>for each session (<strong>Sprint</strong>). They came up with a plan of what can be delivered and how it can be achieved based on prior experience. Having a goal gave them a clear vision of what they were trying to achieve by the end of each session. Throughout their partnership, they worked towards achieving the goal set and adapted according to the situation.</p><h3><strong>My unlearning and relearning experience</strong></h3><p><strong>Old Learning</strong></p><p>My old learning about Sprint planning was that its an event where Product Owner, Scrum Master, and Development team discuss committing and achieving velocity by adding story points for each story</p><p><strong>Unlearning</strong></p><p>Velocity should not be used to measure development team performance.</p><p>Velocity should not be used to compare the teams.</p><p>Sprint planning is not just about estimations.</p><p><strong>Relearning</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbX5stkF2sjeejMgLSPj7A.jpeg" /></figure><p>Sprint planning is an event where The Scrum Master, Product Owner, and Development Together carve out the <strong>Sprint Goal</strong>.</p><p><strong>The Sprint Goal </strong>is an objective set for the Sprint that can be met through the implementation of the Product Backlog. It provides guidance to the Development Team on why it is building the Increment</p><p>In Scrum<strong> Velocity is a Complimentary practice</strong>.</p><p>As my Professional Scrum master trainer pointed out the word Sprint goal appears more than 30 times in the Scrum guide but I never knew it exists.</p><p>The Product Owner, Stakeholders, Customers, or in fact developers will be happier in achieving the sprint goal and delivering something valuable than achieving velocity.</p><p>Velocity does help you in planning and forecasting the release plans but that shouldn&#39;t be the agenda in planning the sprint. It&#39;s a result, not a desire and doesn&#39;t speak about development team performance.</p><p><strong>Final Thoughts</strong> <strong>Sprint planning and Velocity</strong></p><p><strong>Velocity</strong> is good when the Scrum team uses it to measure its progress, Strength, and how to improve. It helps The Product owner in forecasting the release plan.</p><p><strong>Sprint planning</strong> should be an event where the development team <strong>forecasts</strong> the functionality that will be developed during the Sprint.</p><p>Everyone should understand that in complex and chaotic problems team doesn&#39;t commit but forecasts work likely to be done</p><p>The team should work towards achieving the Sprint goal</p><p>My journey in understanding Agile just started. Let me know your thoughts in the comment sections. Let&#39;s unlearn and learn agile together</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6146b9b4e3f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/unlearning-agile-scrum-to-relearn-it-the-right-way-part-1-e6146b9b4e3f">Unlearning Agile(Scrum) to relearn it the right way [Part 1]</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test-Driven Development + Continuous Integration using NodeJS and GitHub Hooks]]></title>
            <link>https://levelup.gitconnected.com/test-driven-development-continuous-integration-using-nodejs-and-github-hooks-f9f0e2924f7?source=rss-a50fbe23201d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9f0e2924f7</guid>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[ci]]></category>
            <category><![CDATA[ttd]]></category>
            <dc:creator><![CDATA[suhas murthy]]></dc:creator>
            <pubDate>Sun, 05 Jul 2020 08:42:36 GMT</pubDate>
            <atom:updated>2020-07-05T13:17:51.018Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*kStI68X-Mxz7CRCv1mzRQw.jpeg" /></figure><h4><strong>Why test-driven development or unit testing?</strong></h4><ol><li>Test-driven development helps you reduce bugs as we predefine the test cases</li><li>It helps you in code maintainability. Say a new developer comes and changes the code without having the product knowledge. Our test cases will fail which would help the new developer know where he went wrong</li><li>Additional to above point these test cases can act as documentation and help the new developer understand the code better</li><li>Test-driven development is adopted by agile software developers as it helps you with quick releases by using Continuers integration &amp; Continues deployment (CI/CD)</li></ol><p>In this article, let’s build a simple sign up service with Node using TTD. I will be using the same initial set up which I had earlier used in one of my articles to set up <a href="https://medium.com/@murthy.suhas/build-a-node-service-using-kubernetes-b360bde91ced">NodeJS using Kubernetes</a>. If you are interested, please check out the article here. GitHub link for initial set up with express and typescript can be found <a href="https://github.com/suhas86/node-typescript-kube-sample/tree/initial-setup">here</a>. <em>(Please ignore Docker and Kubernetes set up if you are not familiar with it as we won&#39;t be using it here).</em></p><p>Let&#39;s say we have a new user story where our product/customer wants to have a simple sign up page.</p><p>Typically as developers, we get requirements from our product owners and we start writing code but here we need to convert this user story to test cases. For this story, let&#39;s say these will be my test cases and all platforms should follow the same. By doing this we also ensure that its uniform across all platforms</p><ol><li>The first name should be mandatory</li><li>An email has to be valid</li><li>Password length has to a minimum of 6 characters</li><li>Email Id and Password fields should be mandatory</li><li>Password and Confirm password has to be same</li><li>Duplicate emails should not be allowed</li><li>Should allow to create a user with proper first name, last name email, password and confirm password</li><li>Should allow creating a user without last name.</li></ol><p>Now that we have our requirements ready let&#39;s build our application.</p><h4><strong>Install all the dependencies required and set up a test environment</strong></h4><p>In this application, we will use <a href="https://www.npmjs.com/package/supertest">supertest</a> for testing HTTP</p><pre>npm install supertest @types/supertest --save-dev</pre><p><a href="https://www.npmjs.com/package/jest">Jest</a> for JavaScript testing</p><pre>npm install jest @types/jest --save-dev</pre><p><a href="https://github.com/nodkz/mongodb-memory-server">mongodb-memory-server</a> for mocking MongoDB for testing</p><pre>npm i mongodb-memory-server --save-dev</pre><p>And lastly, <a href="https://www.npmjs.com/package/ts-jest">ts-jest</a> to allow jest test project built on TypeScript</p><p>After installing these dependencies we need to change the test script as follows in package.json</p><pre>&quot;scripts&quot;: {</pre><pre>&quot;start&quot;: &quot;ts-node-dev src/index.ts&quot;,</pre><pre>&quot;test&quot;: &quot;jest --watchAll --no-cache&quot;</pre><pre>},</pre><pre>&quot;jest&quot;: {</pre><pre>&quot;preset&quot;: &quot;ts-jest&quot;,</pre><pre>&quot;testEnvironment&quot;: &quot;node&quot;,</pre><pre>&quot;setupFilesAfterEnv&quot;: [</pre><pre>&quot;./src/test/setup.ts&quot;</pre><pre>]</pre><pre>},</pre><p>Above we are basically telling jest to use ts-jest as we are building this app using TypeScript and providing a path to run the code to configure or set up the testing framework before each test file in the suite is executed.</p><p>Let&#39;s create setup file by creating a folder with name test under src directory and create a file setup.ts</p><p>In Setup, we will set 3 helper functions</p><ol><li><strong>beforeAll </strong>=&gt; Connecting to Mongo memory server</li><li><strong>beforeEach</strong> =&gt; Get and delete all collections</li><li><strong>afterAll </strong>=&gt; After all the testing stop Mongo server and close the connection</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/265c17e78b5c7ea1b5e6497faf369252/href">https://medium.com/media/265c17e78b5c7ea1b5e6497faf369252/href</a></iframe><p>This concludes the set up required to write our test cases for a simple signup route</p><p>Like I mentioned earlier we would require our code to pass 8 test cases to meet our product owner/Customer requirement</p><p>Create a __test__ folder under routes. This naming convention will inform jest to pick all the files inside this folder when we run the test script.</p><p>Inside this folder create a file by name signup.test.ts and define the 8 test cases required.</p><pre>it(&quot;Should not allow to create user without first name&quot;, () =&gt; {});</pre><pre>it(&quot;Should not allow to create user with invalid email&quot;, () =&gt; {});</pre><pre>it(&quot;Should not allow to create user with invalid password. Has to be minimum of 6&quot;, () =&gt; {});</pre><pre>it(&quot;Should not allow to create user without email id and password&quot;, () =&gt; {});</pre><pre>it(&quot;Should not allow to create user without same password and confirm password&quot;, () =&gt; {});</pre><pre>it(&quot;Should not allow to create user with same email&quot;, () =&gt; {});</pre><pre>it(&quot;Should allow to create user with proper first name, last name  email, password and confirm password&quot;, () =&gt; {});</pre><pre>it(&quot;Should allow to create user without last name&quot;, () =&gt; {});</pre><p>Let&#39;s fill these test cases by importing super test and app.ts.</p><p>So for the first test case if the body doesn&#39;t have a valid first name we should not allow the user to sign up but instead throw error 400. So our test cases would be like this.</p><pre>it(&quot;Should not allow to create user without first name&quot;, async () =&gt; {</pre><pre>return request(app)</pre><pre>.post(&quot;/api/users/signup&quot;)</pre><pre>.send({</pre><pre>lastName: &quot;Abc&quot;,</pre><pre>email: &quot;abc@example.com&quot;,</pre><pre>password: &quot;12345678&quot;,</pre><pre>confirmPassword: &quot;12345678&quot;,</pre><pre>})</pre><pre>.expect(400);</pre><pre>});</pre><p>Similarly, let&#39;s fill all our test cases which is pretty straight forward.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a43af4d15d62a810482b72364caced4/href">https://medium.com/media/2a43af4d15d62a810482b72364caced4/href</a></iframe><p>Now when we run the test script all test cases would fail and we see something similar to this on our console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKCDucF0XbtDtoe8hJgkSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqFGpWE6ZXLaL5xmlUEXAw.png" /></figure><p>Now let&#39;s change our code to pass each of these test cases</p><p><strong>Pass the test cases</strong></p><p>Let&#39;s change our code to pass these test cases</p><p>Test case number one says first name cant be invalid. To check this condition we will be using <a href="https://www.npmjs.com/package/express-validator">express-validator</a></p><pre>npm install express-validator</pre><p>Now let&#39;s include the express-validator body as middleware to our route and check if the first name exists and check for errors. If errors are not empty throw a 400 status error code</p><pre>import express, { Request, Response } from &quot;express&quot;;</pre><pre>import { User } from &quot;../models/user&quot;;</pre><pre>import express, { Request, Response } from &quot;express&quot;;</pre><pre>import { User } from &quot;../models/user&quot;;</pre><pre>import { body, validationResult } from &quot;express-validator&quot;;</pre><pre>const router = express.Router();</pre><pre>router.post(</pre><pre>&quot;/api/users/signup&quot;,</pre><pre>[</pre><pre>body(&quot;firstName&quot;)</pre><pre>.trim()</pre><pre>.not()</pre><pre>.isEmpty()</pre><pre>.withMessage(&quot;First Name is required&quot;)</pre><pre>],</pre><pre>async (req: Request, res: Response) =&gt; {</pre><pre>const errors = validationResult(req);</pre><pre>if (!errors.isEmpty()) {</pre><pre>return res.status(400).send(errors.array());</pre><pre>}</pre><pre>res.send({})</pre><pre>}</pre><pre>);</pre><pre>export { router as SignupRoute };</pre><p>Now if we run the test script our first test case will pass</p><p>If you observe four test cases are pretty similar and have to do with validations. To keep the article short I summarize all the validation into one code. By doing this our code would end up like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c68c97ba795f2972f0758c8935fc1069/href">https://medium.com/media/c68c97ba795f2972f0758c8935fc1069/href</a></iframe><p>The next three test cases have to do with MongoDB. To pass these test cases lets create a user model under a model folder</p><pre>import mongoose from &quot;mongoose&quot;;</pre><pre>const userSchema = new mongoose.Schema({</pre><pre>firstName: { type: String, required: true },</pre><pre>lastName: { type: String, required: false },</pre><pre>email: { type: String, required: true },</pre><pre>password: { type: String, required: true },</pre><pre>});</pre><pre>const User = mongoose.model(&quot;User&quot;, userSchema);</pre><pre>export { User };</pre><p>So the next test case is to make sure there is no duplicate email id entered. To pass this let&#39;s add validation to our route</p><pre>const { firstName, lastName, email, password } = req.body;</pre><pre>const existingUser = await User.findOne({ email });</pre><pre>if (existingUser) {</pre><pre>return res.status(400).send({ error: &quot;Email already exists&quot; });</pre><pre>}</pre><p>If we run our test cases 6 of our test cases will pass. The next two test cases are happy test cases where we allow the creation of users. By adding this all our test cases will pass and our code would end up like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/206f81cecf7de2b5f7fd3da0acdcc942/href">https://medium.com/media/206f81cecf7de2b5f7fd3da0acdcc942/href</a></iframe><p>The entire code section for this can be found <a href="https://github.com/suhas86/node-typescript-kube-sample/tree/add-test-signup-route">here</a>. This concludes test-driven development</p><p><a href="https://docs.github.com/en/actions"><strong>GitHub Action</strong></a><strong> hooks and CI test scripts</strong></p><p>What&#39;s the importance of the CI test script?</p><p>Usually, we maintain our production code in the master branch and create a separate branch for development. So when we want to merge the changes to the master branch for a production release we need to have a validation layer that should run test scripts in our project and tell us if all our test cases pass and we do not end up adding bugs to our application. To do this we can use CI test scripts in Github action hook</p><p><strong>Prerequisite:</strong> To create GitHub action push your code to GitHub and create another branch say dev.</p><p>Let&#39;s go to GitHub and create action</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q3r4NIaloq1nt8i1TRyHjQ.png" /><figcaption>Click on set up this workforce</figcaption></figure><p>Rename the file to tests.yaml and delete everything inside the editor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IEbGP7O3Gg_454ZRKgJbUw.png" /><figcaption>Clear everything inside Edit new file</figcaption></figure><p>Add this code inside the editor</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff2e72545a6ac7a1dcede5e5b5624414/href">https://medium.com/media/ff2e72545a6ac7a1dcede5e5b5624414/href</a></iframe><p>In this Yaml file, we define when we want to run the test script ie during a pull request and also passing build instructions and click on start commit to commit a file</p><p>Before making a pull request we need to make a small change in package.json and add because the existing test script will not come out of the job we are adding a new script explicitly for GitHub</p><pre>&quot;test:ci&quot;: &quot;jest&quot;</pre><p>Now let&#39;s create a pull request from dev (In my case its add-test-signup-route)to master branch and test if this works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QSTs2hw4ORzbazuulrLlew.png" /><figcaption>Click on Pull request and click on New pull request</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8u8Qq7JrGfR5Fs0eLcB4g.png" /><figcaption>Select from the branch you would like to merge to master and hit create pull request</figcaption></figure><p>As soon as we click on Pull request we can see our script running in Github</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eMI_YlhPIzbvNfJSA6OQ4w.png" /></figure><p>And if you click on show all check and click on details we can find the details</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vamoUOwVkZyViGfkCvi6qg.png" /></figure><p>Now we can confidently click on a Merge pull request to merge the code to our master branch.</p><p>This concludes CI using GitHub hooks.</p><p>Hope you enjoyed this article on test-driven development and CI using GitHub.</p><p>Happy Coding!!! Cheers !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9f0e2924f7" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/test-driven-development-continuous-integration-using-nodejs-and-github-hooks-f9f0e2924f7">Test-Driven Development + Continuous Integration using NodeJS and GitHub Hooks</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Node Service using Kubernetes]]></title>
            <link>https://levelup.gitconnected.com/build-a-node-service-using-kubernetes-b360bde91ced?source=rss-a50fbe23201d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b360bde91ced</guid>
            <category><![CDATA[typesetting]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[skaffold]]></category>
            <dc:creator><![CDATA[suhas murthy]]></dc:creator>
            <pubDate>Sun, 05 Jul 2020 08:40:53 GMT</pubDate>
            <atom:updated>2020-07-05T12:31:49.743Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*uI2Y-R8gE_fcHTW0tDi95w.jpeg" /></figure><p>In this article, I will try to walk you through on how to set up Kubernetes for a Node application using MongoDB for development.</p><p>Prerequisite to read this article — Basics of Node, TypeScript, Docker, and Kubernetes</p><p><strong>Let&#39;s start by setting up the application</strong></p><p>First, let&#39;s create a package.json and install all our dependencies required for this application</p><pre>npm init</pre><p>Now in this application, we will be using express framework and TypeScript. So let&#39;s go ahead and install it.</p><pre>npm i express @types/express typescript @types/typescript</pre><p>Now to run this app locally we would require ts-node-dev to run and restart our Node app built on TypeScript. More info can be found <a href="https://www.npmjs.com/package/ts-node-dev">here</a>.</p><pre>npm i ts-node-dev</pre><p>And finally to start the application, edit the script tag in package.json to below code where index.ts is our source file for our application.</p><pre>&quot;scripts&quot;: {</pre><pre>  &quot;start&quot;: &quot;ts-node-dev src/index.ts&quot;,</pre><pre>  &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;</pre><pre>}</pre><p><strong>Creating an express server and setting up a route for our application</strong></p><p>Let&#39;s create a simple route for now inside routes folder which later will be converted into a simple signup route</p><pre>import express, { Request, Response } from &quot;express&quot;;</pre><pre>const router = express.Router();</pre><pre>router.get(&quot;/api/users/signup&quot;, (req: Request, res: Response) =&gt; {</pre><pre>  console.log(&quot;API Hit&quot;);</pre><pre>  res.send({ success: true });</pre><pre>});</pre><pre>export { router as SignupRoute };</pre><p>I will split the app and express server into two files as I would require app configurations later to write unit tests for this app.</p><p>I will define my app under app.ts</p><pre>import express from &quot;express&quot;;</pre><pre>import { json } from &quot;body-parser&quot;;</pre><pre>import { SignupRoute } from &quot;./routes/signup&quot;;</pre><pre>const app = express();</pre><pre>app.use(json());</pre><pre>app.set(&quot;trust proxy&quot;, true);</pre><pre>app.use(SignupRoute)</pre><pre>export { app };</pre><p>Start the express server in index.ts</p><pre>import { app } from &quot;./app&quot;;</pre><pre>const start = async () =&gt; {</pre><pre>  app.listen(3000, () =&gt; {</pre><pre>    console.log(&quot; listening on port 3000&quot;);</pre><pre>  });</pre><pre>};</pre><pre>start();</pre><p>Now that our basic app is ready with a simple route let us create Docker file for this application</p><p><strong>Docker for our node application</strong></p><p>Our docker file will have the following steps defined</p><ol><li>From =&gt; On which server we will run the application</li><li>WORKDIR =&gt; Directory for our application</li><li>COPY =&gt; Copy package.json</li><li>RUN =&gt; To install all npm packages defined in pacakge.json</li><li>COPY =&gt; rest of the source files</li><li>CMD =&gt; Command to run our application</li></ol><pre>FROM node:13.3.0-alpine</pre><pre>WORKDIR /app</pre><pre>COPY package.json .</pre><pre>RUN npm install --only=prod</pre><pre>COPY . .</pre><pre>CMD [&quot;npm&quot;,&quot;start&quot;]</pre><p>Build and push the docker image</p><pre>docker build -t dockerid/imagename .</pre><pre>In my case its<br>docker build -t suhas86/auth</pre><pre>Followed by</pre><pre>docker push dockerid/imagename<br>docker push suhas86/auth</pre><p><strong>Setting up Kubernetes for our application</strong></p><p>Before setting up let&#39;s have a small Kubernetes tour</p><p><strong>What is Kubernetes?</strong></p><p><strong><em>Note: If you know the basics of Kubernetes you can skip this section</em></strong></p><p>Kubernetes is a tool for running a bunch of different containers.</p><p>Whenever we want to use Kubernetes we need to have a docker image. Docker image is basically a guide for how to create a container</p><p>We use this image to create a container and deploy it to the Kubernetes cluster.</p><p>To create a container out of the docker image we need to create a configuration file. In this configuration file, we mention how many copies of the docker image we need to run and make it accessible from the network.</p><p>When we feed this configuration information to Kubernetes it will fetch the docker image. If the image is not available it will download from the docker hub.</p><p>It will download the docker image and create the container inside the pod. A Pod is the basic execution unit of a Kubernetes application.</p><p>So these pods will run our service. But what if something goes wrong and we need to restart the pod?</p><p>Well, to maintain pods we create deployments for the pods. If anything goes wrong with pod or say it crashes or gets deleted accidentally. These deployments will make sure its recreated automatically.</p><p>So the second part of the configuration is to make it accessible from the network. For this Kubernetes creates service. Service gives access to running pods inside our server. It handles networking among different pods inside our Kubernetes cluster.</p><p>In our project, let&#39;s call it auth we need deployment and service for the auth module and auth mongo DB. So let&#39;s create YAML files for the same. We will create these YAML files under infra/k8s directory which is standard practice.</p><p><strong>YAML file for auth</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/062a494b2db23aa79526c1806b80fb88/href">https://medium.com/media/062a494b2db23aa79526c1806b80fb88/href</a></iframe><p>The above file has a deployment of pod along with service to connect to the network.</p><p>To summarise the YAML file, we have the name of the deployment as auth-depl, name of the pod as auth and under spec, we have provided the image from which it has to create the container, Mongodb URL for which we will create a config file next and service to access our pod by the name auth-srv.</p><p>Now similarly let&#39;s create YAML for the mongo DB required for this project</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67945ab4ae63df856739fb830a3b6560/href">https://medium.com/media/67945ab4ae63df856739fb830a3b6560/href</a></iframe><p>In this YAML file, we will be using the mongo image created by the MongoDB team to create a container inside our pod.</p><p><strong>Load Balancer and Ingress Controller</strong></p><p>We need a Load Balancer service to make service calls from outside the cluster. A load balancer service gets traffic into a single pod. But the Load balancer alone won&#39;t serve if we have multiple clusters. If we have multiple pods and we need to distribute traffic to different pods and we need to have routing rules to decide where to send the request. To do this we use the Ingress controller. A pod with a set of routing rules</p><p>In this application, we will be using ingress-nginx that will create a Load Balancer service and ingress. Please follow this <a href="https://kubernetes.github.io/ingress-nginx/deploy/">link</a> for the installation guide for NGINX Ingress Controller.</p><p>YAML file ingress service</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca919853a4bd62b8b0323420e71c39af/href">https://medium.com/media/ca919853a4bd62b8b0323420e71c39af/href</a></iframe><p>In the above YAML file, I have mentioned route rule for <strong>auth-srv </strong>which we have created earlier. Also, I have mentioned the host as a quiz.com.</p><p>To change the hostname of localhost</p><pre>code /etc/hosts .</pre><pre>This will open host file in your code editor</pre><pre>Add this at the end of the file<br>127.0.0.1 quiz.com</pre><pre>Note: If your editor is not configured in command path. Please do this manuallay. Also to make this change you need to grant Admin access</pre><p><a href="https://skaffold.dev/"><strong>Skaffold</strong></a><strong> for development</strong></p><p>Every time we make the change we need to build the docker image, push the image, and apply the Kubernetes deployments again ex <strong>kubectl apply -f auth-dep.yaml</strong> which is quite a time consuming and quite frustrating. To automate this process during development we use skaffold. Also when we exit skaffold will delete all the pods and objects belonging to the project. Installation guide of Skaffold can be found <a href="https://skaffold.dev/docs/install/">here</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee87a58fd8def319ad7861824f3baf37/href">https://medium.com/media/ee87a58fd8def319ad7861824f3baf37/href</a></iframe><p>In this configuration file, we have given our infra k8s path under manifests and under artifacts the image name.</p><p>To run our application on the development machine</p><pre>skaffold dev</pre><p>You will something similar to this on your console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sm3ZZOXT_JcOF-Z50rZ9Vw.png" /></figure><p>Now if you open another console and type <strong>kubectl get pods. </strong>You can see all the pods of our application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gdR86DFd8lCRh5nK-QGpBQ.png" /></figure><p>To test our load balancer service and NGINX ingress controller, go to postman or any other API testing tool and test the GET method which we have written in our routes directory and you should get 200 response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F6XVKxBjHPmpCthf2KJv1Q.png" /></figure><p>This concludes the setting up of Kubernetes for a node application. The code for this can be found in <a href="https://github.com/suhas86/node-typescript-kube-sample/tree/initial-setup">GitHub</a>.</p><p>I recently learned Kubernetes to build a microservice application. I got so fascinated by Kubernetes world I wanted to share my learnings in an article. Hope this gives you an idea of how to set up Kubernetes for your application. If you have any suggestions on how we could improve this setup please leave a comment as it would help me and fellow developers to improve more on this.</p><p>There is a follow-up article where using the same setup I have used MongoDB and I have explained <a href="https://medium.com/@murthy.suhas/test-driven-development-continuous-integration-using-nodejs-and-github-hooks-f9f0e2924f7">test-driven development and continuous integration using GitHub hooks.</a></p><p>Happy Coding, Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b360bde91ced" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/build-a-node-service-using-kubernetes-b360bde91ced">Build a Node Service using Kubernetes</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication using Firebase and React.js]]></title>
            <link>https://levelup.gitconnected.com/authentication-using-firebase-and-react-js-99392c6fa58b?source=rss-a50fbe23201d------2</link>
            <guid isPermaLink="false">https://medium.com/p/99392c6fa58b</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[firebaseauthentication]]></category>
            <category><![CDATA[javscript]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[suhas murthy]]></dc:creator>
            <pubDate>Thu, 21 May 2020 18:52:23 GMT</pubDate>
            <atom:updated>2020-05-24T02:53:42.694Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will help you understand how we can build an Authentication module i.e sign in and sign up pages, using Firebase Authentication</p><p><em>Setting up the Firebase database and setting firebase in our react app can be found in my previous </em><a href="https://medium.com/@murthy.suhas/todo-app-using-firebase-react-typescript-ea0a34bd417d"><em>article</em></a></p><p>In this article, we will build a Sign in, Sign up, and Sign up using a google account using firebase</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ivsZHG_KqBj149jPQASJ4A.png" /><figcaption>A basic login app</figcaption></figure><p>Firebase has a huge collection of APIs and features so it is difficult to remember everything. It&#39;s important as a developer to understand and know how to read the documentation and Firebase has good user-friendly <a href="https://firebase.google.com/docs/web/setup">documentation</a>. Using this let us build our app.</p><p><strong>Lets set up a sign up with Google account</strong></p><p><a href="https://firebase.google.com/docs/auth/web/google-signin">Documentation</a> guide on how to set up</p><p>Authentication using Google Sign-In can be set up by creating an instance of the Google provider object and also by importing the auth module from firebase.</p><pre>import &#39;firebase/auth&#39;;</pre><pre>const provider = new firebase.auth.GoogleAuthProvider();</pre><p>Next, we could set custom parameters if required which we want to send with the OAuth request.</p><pre>provider.setCustomParameters({</pre><pre>  promt: &quot;select_account&quot;,</pre><pre>});</pre><p>Now finally we will authenticate our google provider object with firebase. You can ask users to sign in by prompting google sign in or by redirecting to google sign-in page. For pop up we use signInWithPopup() method for redirect we use signInWithRedirect() method. In our example, we will use signInWithPopup() method. That&#39;s it with only these two mandatory steps you can set up your app to sign up with Google account. At this point, your firebase.ts file should look like this:</p><pre>import firebase from &#39;firebase/app&#39;;</pre><pre>import  &quot;firebase/firestore&quot;;</pre><pre>import &#39;firebase/auth&#39;;</pre><pre>const config = {</pre><pre>  apiKey: process.env.REACT_APP_APIKEY,</pre><pre>  authDomain: process.env.REACT_APP_AUTHDOMAIN, </pre><pre>  databaseURL: process.env.REACT_APP_DB,</pre><pre>  projectId: process.env.REACT_APP_PID,</pre><pre>  storageBucket: process.env.REACT_APP_SB,</pre><pre>  messagingSenderId: process.env.REACT_APP_SID,</pre><pre>  appId: process.env.REACT_APP_APPID,</pre><pre>  measurementId:process.env.REACT_APP_MID</pre><pre>};</pre><pre>firebase.initializeApp(config);</pre><pre>export const auth = firebase.auth();</pre><pre>export const firestore = firebase.firestore();</pre><pre>/** To sign up using google</pre><pre>* Link for developer documentation (https://firebase.google.com/docs/auth/web/google-signin)</pre><pre>*/</pre><pre>const provider = new firebase.auth.GoogleAuthProvider();</pre><pre>provider.setCustomParameters({</pre><pre>  promt: &quot;select_account&quot;,</pre><pre>});</pre><pre>export const signInWithGoogle = () =&gt;    auth.signInWithPopup(provider);</pre><p>Now all we have to do is call signInWithGoogle method on click of a button</p><pre>&lt;Button type=&quot;button&quot; fullWidth variant=&quot;contained&quot; onClick = {signInWithGoogle} color=&quot;secondary&quot;&gt;</pre><pre>  Sign In with google</pre><pre>&lt;/Button&gt;</pre><p>When we will click on Sign in with Google button we will not see the popup but if you open the console you will see an error that says <em>the identity provider configuration is disabled. </em>That is because all the authentication APIs will be disabled by default. So we need to go to Firebase console and enable Google sign-in method under authentication</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*utnGA30EKZZIbRyY-H2ViQ.png" /></figure><p>If you try again in your application after enabling the option you will get a pop-up and you can sign up into the application. In Firebase console if you go to Users tab under authentication you can see the user and you can see the provider as Google:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lI6M9gfmtwbYwoTnhYd3ZA.png" /></figure><p>But how do we get to know in our react app if the user has signed in or not? According to the <a href="https://firebase.google.com/docs/auth/web/manage-users">documentation</a> onAuthStateChanged(), the observer will tell every time there is a change in the authorization. So let&#39;s add this observer in App.ts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb8f8e3eab776c3dca707f4e32abf323/href">https://medium.com/media/eb8f8e3eab776c3dca707f4e32abf323/href</a></iframe><p>If you console the current user you will find all the information including: UUID, email, and creation details.</p><p>But as you can observe the user who got signed up is there under Users but not in our database. Normally we do want the user reference in our application. So let&#39;s see how to do that.</p><p>Before going forward let&#39;s understand a few basic concepts Query references and Snapshots in Firebase.</p><p>A <strong>Query </strong>is a request we make to our Firestore to get data from the database</p><p>Firestore returns two objects</p><ol><li>References</li><li>Snapshots</li></ol><p>The returned object can be either collection or a document.</p><p>But the key thing to remember is <strong>Firestore always returns these object, even if nothing exists</strong></p><p>We can get the data reference i.e Query reference by calling <strong><em>firestore.doc(‘/users’)</em></strong></p><p>We should keep in mind that the Query reference will not return actual data instead it will give us properties that will tell us the details about it.</p><p>From this document reference, we can get a snapshot object which will allow us to know if the object exists or not.</p><p>Using these two key features document reference and document snapshot lets create a method in firebase.ts which check if user exits if doesn&#39;t we will add the user to our database and call every time there is a change in auth state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b943aa788bcc9cac858a945a22246df/href">https://medium.com/media/5b943aa788bcc9cac858a945a22246df/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ce46bbd32b91b621b3741f129b5367f/href">https://medium.com/media/6ce46bbd32b91b621b3741f129b5367f/href</a></iframe><p>Now if we sign up a user you can find the user in our collection</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8qrVH14Db5x0Bkbd7ZTUbg.png" /></figure><p>Next step is creating user using our custom form for that we need to enable email/password sign-in method in our Authentication</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kW_XS5MkgHYFGUSHF4qi-w.png" /><figcaption>Enable Email/Password option</figcaption></figure><p>The API we use to create a user in using email/password sign-in method is <strong>createUserWithEmailAndPassword </strong>and pass<strong> </strong>email and password. Documentation of this can be found <a href="https://firebase.google.com/docs/auth/web/password-auth">here</a></p><p>But this will create a user in an authentication database. To create a user in our database we need to pass the created user to our <strong>createUserProfileDocument </strong>method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dc0c205b3183f7b9369efc0d528c37e/href">https://medium.com/media/1dc0c205b3183f7b9369efc0d528c37e/href</a></iframe><p>The final step to this sample app is to log in with email and password used during sign up. So lets complete by setting up our login component.</p><p>We can sign in using signInWithEmailAndPassword method. Documentation details can be found <a href="https://firebase.google.com/docs/auth/web/password-auth#sign_in_a_user_with_an_email_address_and_password">here</a></p><pre>const onSubmit = async (e: React.FormEvent&lt;EventTarget&gt;) =&gt; {</pre><pre>  e.preventDefault();</pre><pre>  const { email, password } = user;</pre><pre>  await auth.signInWithEmailAndPassword(email, password);</pre><pre>  setUser({</pre><pre>    email: &quot;&quot;,</pre><pre>    password: &quot;&quot;,</pre><pre>  });</pre><pre>};</pre><p>Finally to logout we can use the auth method signOut <a href="https://firebase.google.com/docs/auth/web/password-auth">method</a>.</p><p>This concludes the sample application to build authentication using Firebase. The initial set up for this project can be found <a href="https://github.com/suhas86/firebase-react-auth">here</a> and the complete project can be found <a href="https://github.com/suhas86/firebase-react-auth/tree/firebase-integration">here</a></p><p>I hope this helps you in understanding how authentication works in firebase.</p><p>Happy coding! Cheers</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99392c6fa58b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/authentication-using-firebase-and-react-js-99392c6fa58b">Authentication using Firebase and React.js</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>