<?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 Rahul Shrivastava on Medium]]></title>
        <description><![CDATA[Stories by Rahul Shrivastava on Medium]]></description>
        <link>https://medium.com/@rahul.panna87?source=rss-7729aab9f373------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*P5R9ivZ6WSqI9AJeT5HwkQ.jpeg</url>
            <title>Stories by Rahul Shrivastava on Medium</title>
            <link>https://medium.com/@rahul.panna87?source=rss-7729aab9f373------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 17:39:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahul.panna87/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[State management with NgRx]]></title>
            <link>https://medium.com/@rahul.panna87/state-management-with-ngrx-46b2b5785817?source=rss-7729aab9f373------2</link>
            <guid isPermaLink="false">https://medium.com/p/46b2b5785817</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ngrx-store]]></category>
            <dc:creator><![CDATA[Rahul Shrivastava]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 15:06:35 GMT</pubDate>
            <atom:updated>2025-02-04T15:06:35.370Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is NgRx?</h3><p>NgRx is a state management library for Angular applications. It provides a way to manage the state of your application in a predictable and centralized manner. NgRx is based on the <strong>Redux pattern</strong>, which revolves around a unidirectional data flow and immutable state.</p><p>NgRx is particularly useful for applications with complex state requirements, such as:</p><ol><li>Applications with shared state across multiple components.</li><li>Applications that require undo/redo functionality.</li><li>Applications with asynchronous data fetching and caching.</li></ol><h3>Why Use NgRx?</h3><p>Managing state in large applications can become challenging as the application grows. Without a proper state management solution, you may encounter issues like:</p><ol><li><strong>Tight coupling</strong> between components.</li><li><strong>Difficulty in debugging</strong> due to scattered state logic.</li><li><strong>Inconsistent state</strong> across the application.</li></ol><p>NgRx solves these problems by providing:</p><ol><li><strong>Centralised State</strong>: All application state is stored in a single, immutable store.</li><li><strong>Predictability</strong>: State changes are predictable because they are handled by pure functions called reducers.</li><li><strong>Debugging Tools</strong>: NgRx integrates with tools like the Redux DevTools, making it easier to debug and track state changes.</li><li><strong>Reactive Programming</strong>: NgRx leverages RxJS to handle asynchronous operations and state updates in a reactive way.</li></ol><h3>Core Concepts of NgRx</h3><p>Before diving into implementation, let’s understand the core building blocks of NgRx:</p><ol><li><strong>Store</strong>: The store is a centralized container that holds the application state. It is immutable, meaning the state cannot be modified directly.</li><li><strong>Actions</strong>: Actions are plain objects that describe an event or intention to change the state. They are dispatched to the store to trigger state changes.</li><li><strong>Reducers</strong>: Reducers are pure functions that take the current state and an action as input and return a new state. They define how the state should change in response to an action.</li><li><strong>Selectors</strong>: Selectors are functions used to query and retrieve specific pieces of state from the store.</li><li><strong>Effects</strong>: Effects handle side effects, such as API calls or other asynchronous operations, and dispatch new actions based on the results.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CU2KSBgVXCWc8XXFOtLtbA.png" /></figure><h3>Setting Up NgRx in an Angular Application</h3><p>Let’s walk through the steps to set up and use NgRx in an Angular application.</p><h3>Step 1: Install NgRx</h3><p>To get started, install the required NgRx packages:</p><pre>npm install @ngrx/store @ngrx/effects @ngrx/store-devtools @ngrx/entity @ngrx/router-store</pre><h3>Step 2: Define the State</h3><p>Create an interface to define the shape of your application state. For example, if you’re managing a list of products:</p><pre>export interface Product {<br>  id: number;<br>  name: string;<br>  price: number;<br>}</pre><pre>export interface AppState {<br>  products: Product[];<br>}</pre><h3>Step 3: Create Actions</h3><p>Actions represent events that can change the state. Define actions for adding, removing, or loading products:</p><pre>import { createAction, props } from &#39;@ngrx/store&#39;;<br>import { Product } from &#39;./product.model&#39;;</pre><pre>export const loadProducts = createAction(&#39;[Product] Load Products&#39;);<br>export const loadProductsSuccess = createAction(<br>  &#39;[Product] Load Products Success&#39;,<br>  props&lt;{ products: Product[] }&gt;()<br>);<br>export const addProduct = createAction(<br>  &#39;[Product] Add Product&#39;,<br>  props&lt;{ product: Product }&gt;()<br>);<br>export const removeProduct = createAction(<br>  &#39;[Product] Remove Product&#39;,<br>  props&lt;{ productId: number }&gt;()<br>);</pre><h3>Step 4: Create a Reducer</h3><p>Reducers handle state changes based on the dispatched actions. Use the createReducer function to define how the state should change:</p><pre>import { createReducer, on } from &#39;@ngrx/store&#39;;<br>import { Product } from &#39;./product.model&#39;;<br>import { addProduct, removeProduct, loadProductsSuccess } from &#39;./product.actions&#39;;</pre><pre>export const initialState: Product[] = [];</pre><pre>export const productReducer = createReducer(<br>  initialState,<br>  on(loadProductsSuccess, (state, { products }) =&gt; [...products]),<br>  on(addProduct, (state, { product }) =&gt; [...state, product]),<br>  on(removeProduct, (state, { productId }) =&gt;<br>    state.filter(product =&gt; product.id !== productId)<br>  )<br>);</pre><h3>Step 5: Register the Store</h3><p>Register the reducer in the AppModule using the StoreModule.forRoot method:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { StoreModule } from &#39;@ngrx/store&#39;;<br>import { productReducer } from &#39;./state/product.reducer&#39;;</pre><pre>@NgModule({<br>  declarations: [AppComponent],<br>  imports: [<br>    BrowserModule,<br>    StoreModule.forRoot({ products: productReducer })<br>  ],<br>  providers: [],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule {}</pre><h3>Step 6: Create Selectors</h3><p>Selectors are used to retrieve specific pieces of state from the store. Define selectors for the product state:</p><pre>import { createSelector, createFeatureSelector } from &#39;@ngrx/store&#39;;<br>import { Product } from &#39;./product.model&#39;;</pre><pre>export const selectProducts = createFeatureSelector&lt;Product[]&gt;(&#39;products&#39;);</pre><pre>export const selectProductById = (productId: number) =&gt;<br>  createSelector(selectProducts, products =&gt;<br>    products.find(product =&gt; product.id === productId)<br>  );</pre><h3>Step 7: Use the Store in Components</h3><p>Inject the Store service into your components to dispatch actions and select state:</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { Store } from &#39;@ngrx/store&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>import { Product } from &#39;./product.model&#39;;<br>import { addProduct, loadProducts } from &#39;./state/product.actions&#39;;<br>import { selectProducts } from &#39;./state/product.selectors&#39;;</pre><pre>@Component({<br>  selector: &#39;app-product-list&#39;,<br>  template: `<br>    &lt;div *ngFor=&quot;let product of products\$ | async&quot;&gt;<br>      {{ product.name }} - \${{ product.price }}<br>    &lt;/div&gt;<br>    &lt;button (click)=&quot;addNewProduct()&quot;&gt;Add Product&lt;/button&gt;<br>  `<br>})<br>export class ProductListComponent implements OnInit {<br>  products\$: Observable&lt;Product[]&gt;;</pre><pre>  constructor(private store: Store) {<br>    this.products\$ = this.store.select(selectProducts);<br>  }</pre><pre>  ngOnInit() {<br>    this.store.dispatch(loadProducts());<br>  }</pre><pre>  addNewProduct() {<br>    const newProduct: Product = { id: 3, name: &#39;New Product&#39;, price: 100 };<br>    this.store.dispatch(addProduct({ product: newProduct }));<br>  }<br>}</pre><h3>Step 8: Handle Side Effects with Effects</h3><p>Use NgRx Effects to handle side effects like API calls. For example, fetching products from an API:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { Actions, createEffect, ofType } from &#39;@ngrx/effects&#39;;<br>import { of } from &#39;rxjs&#39;;<br>import { catchError, map, mergeMap } from &#39;rxjs/operators&#39;;<br>import { ProductService } from &#39;./product.service&#39;;<br>import { loadProducts, loadProductsSuccess } from &#39;./state/product.actions&#39;;</pre><pre>@Injectable()<br>export class ProductEffects {<br>  loadProducts\$ = createEffect(() =&gt;<br>    this.actions\$.pipe(<br>      ofType(loadProducts),<br>      mergeMap(() =&gt;<br>        this.productService.getProducts().pipe(<br>          map(products =&gt; loadProductsSuccess({ products })),<br>          catchError(() =&gt; of({ type: &#39;[Product] Load Products Failure&#39; }))<br>        )<br>      )<br>    )<br>  );</pre><pre>  constructor(private actions\$: Actions, private productService: ProductService) {}<br>}</pre><p>Register the ProductEffects in the AppModule:</p><pre>import { EffectsModule } from &#39;@ngrx/effects&#39;;<br>import { ProductEffects } from &#39;./state/product.effects&#39;;</pre><pre>@NgModule({<br>  imports: [<br>    EffectsModule.forRoot([ProductEffects])<br>  ]<br>})<br>export class AppModule {}</pre><h3>Conclusion</h3><p>NgRx provides a powerful and scalable solution for managing state in Angular applications. By following the principles of unidirectional data flow and immutability, NgRx makes it easier to build predictable and maintainable applications. While the initial setup may seem complex, the benefits of centralized state management, debugging tools, and reactive programming make it worth the effort.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46b2b5785817" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State Management in Vue 3 with Pinia]]></title>
            <link>https://medium.com/@rahul.panna87/state-management-in-vue-3-with-pinia-0715bf649efd?source=rss-7729aab9f373------2</link>
            <guid isPermaLink="false">https://medium.com/p/0715bf649efd</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[state-management-in-vuejs]]></category>
            <category><![CDATA[composition-api]]></category>
            <category><![CDATA[pinia]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[Rahul Shrivastava]]></dc:creator>
            <pubDate>Mon, 09 Dec 2024 06:06:32 GMT</pubDate>
            <atom:updated>2024-12-09T06:36:18.180Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70hSH2G_LgOo1W2oKT0HDA.png" /></figure><p>Pinia is a state management library designed specifically for Vue 3. It aims to provide a simpler and more intuitive API compared to Vuex, while still offering powerful features for managing state in your applications. Pinia is inspired by the Composition API introduced in Vue 3, making it a natural fit for modern Vue applications.</p><h3>Key Features of Pinia</h3><ol><li><strong>TypeScript Support</strong>: Pinia has first-class TypeScript support, making it easier to work with type-safe state management.</li><li><strong>Modular Design</strong>: Pinia encourages a modular approach to state management, allowing you to split your state into multiple stores.</li><li><strong>DevTools Integration</strong>: Pinia integrates seamlessly with Vue DevTools, providing a great developer experience.</li><li><strong>Zero Boilerplate</strong>: Pinia reduces the amount of boilerplate code required to manage state, making your codebase cleaner and more maintainable.</li></ol><h3>Why Use Pinia?</h3><p>While Vuex is a powerful state management solution, it can sometimes feel verbose and complex, especially for smaller projects. Pinia offers a more lightweight and intuitive alternative, making it easier to manage state without sacrificing functionality. Here are a few reasons why you might choose Pinia over Vuex:</p><ol><li><strong>Simplicity</strong>: Pinia’s API is simpler and more intuitive, reducing the learning curve for new developers.</li><li><strong>Composition API</strong>: Pinia leverages the Composition API, making it a natural fit for Vue 3 applications.</li><li><strong>Modularity</strong>: Pinia encourages a modular approach, allowing you to organize your state in a more maintainable way.</li><li><strong>Performance</strong>: Pinia is designed to be performant, with minimal overhead.</li></ol><h3>Getting Started with Pinia</h3><p>Let’s walk through the process of setting up Pinia in a Vue 3 project and creating a simple store.</p><h3>Step 1: Install Pinia</h3><p>First, you’ll need to install Pinia. You can do this using npm or yarn:</p><pre>npm install pinia<br>or<br>yarn add pinia</pre><h3>Step 2: Create a Pinia Store</h3><p>Next, let’s create a simple Pinia store. In your src directory, create a new folder called stores and add a file named counter.js:</p><pre>// src/stores/counter.js<br>import { defineStore } from &#39;pinia&#39;;</pre><pre>export const useCounterStore = defineStore(&#39;counter&#39;, {<br>  state: () =&gt; ({<br>    count: 0,<br>  }),<br>  actions: {<br>    increment() {<br>      this.count++;<br>    },<br>    decrement() {<br>      this.count--;<br>    },<br>  },<br>});</pre><p>In this example, we’ve defined a store named counter with a state property count and two actions: increment and decrement.</p><h3>Step 3: Register Pinia in Your Vue App</h3><p>Now, let’s register Pinia in your Vue application. Open your main.js file and add the following code:</p><pre>// src/main.js<br>import { createApp } from &#39;vue&#39;;<br>import { createPinia } from &#39;pinia&#39;;<br>import App from &#39;./App.vue&#39;;</pre><pre>const app = createApp(App);<br>const pinia = createPinia();</pre><pre>app.use(pinia);<br>app.mount(&#39;#app&#39;);</pre><h3>Step 4: Use the Store in Your Components</h3><p>Finally, let’s use the store in a Vue component. Open your App.vue file and add the following code:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h1&gt;Counter: {{ count }}&lt;/h1&gt;<br>    &lt;button @click=&quot;increment&quot;&gt;Increment&lt;/button&gt;<br>    &lt;button @click=&quot;decrement&quot;&gt;Decrement&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>import { useCounterStore } from &#39;./stores/counter&#39;;</pre><pre>export default {<br>  setup() {<br>    const counterStore = useCounterStore();</pre><pre>    return {<br>      count: counterStore.count,<br>      increment: counterStore.increment,<br>      decrement: counterStore.decrement,<br>    };<br>  },<br>};<br>&lt;/script&gt;</pre><p>In this example, we’re using the useCounterStore function to access the store and bind its state and actions to our component.</p><h3>Pinia vs. Vuex</h3><p>While Pinia can be seen as an evolution towards what could be Vuex 5, there are several key differences between the two that you should consider:</p><ol><li><strong>No Mutations</strong>: Pinia eliminates the need for mutations, reducing verbosity and simplifying state management.</li><li><strong>TypeScript Support</strong>: Pinia offers full TypeScript support, including autocompletion for JavaScript code, enhancing the developer experience.</li><li><strong>No Nested Modules</strong>: Pinia does not require nested modules. Instead, if one store uses another, it is treated as implicit nesting, simplifying the structure.</li><li><strong>No Namespacing</strong>: Unlike Vuex modules, Pinia does not require namespacing for app stores, making the API cleaner and easier to use.</li><li><strong>Composition API</strong>: Pinia is designed to work seamlessly with the Composition API but can also be used with the Options API, providing flexibility in how you structure your code.</li><li><strong>Server-Side Rendering (SSR)</strong>: Pinia offers built-in support for server-side rendering, making it suitable for a wide range of applications.</li><li><strong>Compatibility</strong>: Pinia is compatible with both Vue 2 and Vue 3, and it supports DevTools for both versions, ensuring a smooth development experience.</li></ol><p>These differences make Pinia a compelling choice for modern Vue applications, offering a more streamlined and developer-friendly approach to state management.</p><p>To know about more features: <a href="https://pinia.vuejs.org/getting-started.html">https://pinia.vuejs.org/getting-started.html</a></p><h3>Conclusion</h3><p>Pinia is a powerful and intuitive state management library for Vue 3, offering a modern alternative to Vuex. With its simple API, modular design, and seamless integration with the Composition API, Pinia makes state management in Vue 3 applications more straightforward and maintainable. If you’re starting a new Vue 3 project or looking to simplify state management in an existing project, give Pinia a try!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0715bf649efd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>