<?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 Karan Patel (Software Engineer) on Medium]]></title>
        <description><![CDATA[Stories by Karan Patel (Software Engineer) on Medium]]></description>
        <link>https://medium.com/@karan0740?source=rss-7ed3bc7cd5be------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AeQ08aPu1bR--ppQh_94Gw.gif</url>
            <title>Stories by Karan Patel (Software Engineer) on Medium</title>
            <link>https://medium.com/@karan0740?source=rss-7ed3bc7cd5be------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 16:46:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@karan0740/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[How to Implement End-to-End Encryption in Angular and .NET]]></title>
            <link>https://medium.com/@karan0740/how-to-implement-end-to-end-encryption-in-angular-and-net-4592cefbe225?source=rss-7ed3bc7cd5be------2</link>
            <guid isPermaLink="false">https://medium.com/p/4592cefbe225</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[passwords]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[encryption]]></category>
            <dc:creator><![CDATA[Karan Patel (Software Engineer)]]></dc:creator>
            <pubDate>Tue, 22 Jul 2025 06:22:13 GMT</pubDate>
            <atom:updated>2025-12-04T09:00:44.801Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Implement End-to-End Encryption in Angular and .NET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zOjbYl_mcN6vve44Hs1r5Q.png" /><figcaption>End-to-End Encryption</figcaption></figure><h3>Architecture Overview</h3><p>The recommended architecture uses hybrid encryption where AES handles the bulk data encryption (fast and efficient) while RSA manages the secure key exchange. Angular 19 serves as the client using either the native Web Crypto API or crypto-js library, communicating with a .NET API server that leverages System.Security.Cryptography for server-side operations.</p><p><strong>Core Components:</strong></p><ul><li><strong>Client Side:</strong> Angular 19 with Web Crypto API or crypto-js</li><li><strong>Server Side:</strong> .NET API with built-in cryptography libraries</li><li><strong>Transport:</strong> HTTPS + Application-level encryption</li><li><strong>Key Exchange:</strong> RSA public/private key mechanism</li></ul><h3>Github Repository</h3><p><a href="https://github.com/karanpatel7193/EndtoEndEncryption">https://github.com/karanpatel7193/EndtoEndEncryption</a></p><h3>Angular 19 Implementation</h3><h4>1. Crypto Service Implementation</h4><p>Angular 19 presents some compatibility challenges with crypto-js, making the native Web Crypto API the preferred choice. However, both approaches are viable:</p><p><strong>Option A:</strong> Native Web Crypto API (Recommended)</p><pre>// crypto.service.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class CryptoService {<br>  private publicKey: CryptoKey | null = null;<br><br>  async setServerPublicKey(publicKeyPem: string): Promise&lt;void&gt; {<br>    const keyData = this.pemToArrayBuffer(publicKeyPem);<br>    this.publicKey = await window.crypto.subtle.importKey(<br>      &#39;spki&#39;,<br>      keyData,<br>      { name: &#39;RSA-OAEP&#39;, hash: &#39;SHA-256&#39; },<br>      false,<br>      [&#39;encrypt&#39;]<br>    );<br>  }<br><br>  async generateAESKey(): Promise&lt;CryptoKey&gt; {<br>    return await window.crypto.subtle.generateKey(<br>      { name: &#39;AES-GCM&#39;, length: 256 },<br>      true,<br>      [&#39;encrypt&#39;, &#39;decrypt&#39;]<br>    );<br>  }<br><br>  async encryptData(data: any): Promise&lt;{<br>    encryptedData: string;<br>    encryptedAESKey: string;<br>    iv: string;<br>  }&gt; {<br>    // Generate AES key for this session<br>    const aesKey = await this.generateAESKey();<br>    <br>    // Generate random IV<br>    const iv = window.crypto.getRandomValues(new Uint8Array(12));<br>    <br>    // Encrypt data with AES<br>    const encodedData = new TextEncoder().encode(JSON.stringify(data));<br>    const encryptedData = await window.crypto.subtle.encrypt(<br>      { name: &#39;AES-GCM&#39;, iv },<br>      aesKey,<br>      encodedData<br>    );<br>    <br>    // Export AES key and encrypt with RSA public key<br>    const exportedAESKey = await window.crypto.subtle.exportKey(&#39;raw&#39;, aesKey);<br>    const encryptedAESKey = await window.crypto.subtle.encrypt(<br>      { name: &#39;RSA-OAEP&#39; },<br>      this.publicKey!,<br>      exportedAESKey<br>    );<br>    <br>    return {<br>      encryptedData: this.arrayBufferToBase64(encryptedData),<br>      encryptedAESKey: this.arrayBufferToBase64(encryptedAESKey),<br>      iv: this.arrayBufferToBase64(iv)<br>    };<br>  }<br><br>  private pemToArrayBuffer(pem: string): ArrayBuffer {<br>    const b64 = pem.replace(/(-----(BEGIN|END) PUBLIC KEY-----|\s)/g, &#39;&#39;);<br>    return Uint8Array.from(atob(b64), c =&gt; c.charCodeAt(0)).buffer;<br>  }<br><br>  private arrayBufferToBase64(buffer: ArrayBuffer): string {<br>    return btoa(String.fromCharCode(...new Uint8Array(buffer)));<br>  }<br>}</pre><p><strong>Option B:</strong> Crypto-js (With Angular 19 Compatibility Fixes)</p><pre>// For Angular 19, install with compatibility patches<br>// npm install crypto-js<br>// npm install @types/crypto-js<br><br>import { Injectable } from &#39;@angular/core&#39;;<br>import * as CryptoJS from &#39;crypto-js&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class CryptoServiceLegacy {<br>  private serverPublicKey: string = &#39;&#39;;<br><br>  setServerPublicKey(publicKey: string): void {<br>    this.serverPublicKey = publicKey;<br>  }<br><br>  encryptData(data: any): { encryptedData: string; encryptedAESKey: string } {<br>    // Generate random AES key<br>    const aesKey = CryptoJS.lib.WordArray.random(32);<br>    <br>    // Encrypt data with AES<br>    const encryptedData = CryptoJS.AES.encrypt(<br>      JSON.stringify(data), <br>      aesKey.toString()<br>    ).toString();<br>    <br>    // Note: RSA encryption with crypto-js requires additional libraries<br>    // This is a simplified example - use jsencrypt for actual RSA operations<br>    const encryptedAESKey = this.encryptWithRSA(aesKey.toString());<br>    <br>    return { encryptedData, encryptedAESKey };<br>  }<br><br>  private encryptWithRSA(data: string): string {<br>    // Implementation using jsencrypt or similar RSA library<br>    // This is where you&#39;d use the server&#39;s public key<br>    return data; // Placeholder<br>  }<br>}</pre><h4>2. Functional HTTP Interceptor (Angular 19 Standard)</h4><p>Angular 19 emphasizes functional interceptors over class-based ones. Here’s the implementation:</p><pre>// encryption.interceptor.ts<br>import { HttpInterceptorFn } from &#39;@angular/common/http&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br>import { CryptoService } from &#39;./crypto.service&#39;;<br><br>export const encryptionInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  const cryptoService = inject(CryptoService);<br>  <br>  // Only encrypt specific endpoints<br>  if (req.url.includes(&#39;/api/secure&#39;)) {<br>    return from(cryptoService.encryptData(req.body)).pipe(<br>      mergeMap(encrypted =&gt; {<br>        const encryptedRequest = req.clone({<br>          body: {<br>            encryptedData: encrypted.encryptedData,<br>            encryptedAESKey: encrypted.encryptedAESKey,<br>            iv: encrypted.iv<br>          },<br>          setHeaders: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            &#39;X-Encrypted&#39;: &#39;true&#39;<br>          }<br>        });<br>        return next(encryptedRequest);<br>      })<br>    );<br>  }<br>  <br>  return next(req);<br>};</pre><h4>3. Application Configuration</h4><pre>// app.config.ts<br>import { ApplicationConfig } from &#39;@angular/core&#39;;<br>import { provideHttpClient, withInterceptors } from &#39;@angular/common/http&#39;;<br>import { encryptionInterceptor } from &#39;./interceptors/encryption.interceptor&#39;;<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideHttpClient(<br>      withInterceptors([encryptionInterceptor])<br>    ),<br>    // Other providers...<br>  ]<br>};</pre><h3>.NET API Implementation</h3><h4>1. Crypto Service</h4><pre>// Services/ICryptoService.cs<br>public interface ICryptoService<br>{<br>    string GetPublicKey();<br>    T DecryptRequest&lt;T&gt;(EncryptedRequest request);<br>    EncryptedResponse EncryptResponse&lt;T&gt;(T data);<br>}<br><br>// Services/CryptoService.cs<br>public class CryptoService : ICryptoService<br>{<br>    private readonly RSA _rsa;<br>    <br>    public CryptoService()<br>    {<br>        _rsa = RSA.Create(2048);<br>    }<br>    <br>    public string GetPublicKey()<br>    {<br>        return Convert.ToBase64String(_rsa.ExportRSAPublicKey());<br>    }<br>    <br>    public T DecryptRequest&lt;T&gt;(EncryptedRequest request)<br>    {<br>        // Decrypt AES key using RSA private key<br>        var encryptedAESKeyBytes = Convert.FromBase64String(request.EncryptedAESKey);<br>        var aesKeyBytes = _rsa.Decrypt(encryptedAESKeyBytes, RSAEncryptionPadding.OaepSHA256);<br>        <br>        // Decrypt data using AES key<br>        using var aes = Aes.Create();<br>        aes.Key = aesKeyBytes;<br>        aes.IV = Convert.FromBase64String(request.IV);<br>        aes.Mode = CipherMode.GCM;<br>        <br>        var encryptedDataBytes = Convert.FromBase64String(request.EncryptedData);<br>        using var decryptor = aes.CreateDecryptor();<br>        using var msDecrypt = new MemoryStream(encryptedDataBytes);<br>        using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);<br>        using var srDecrypt = new StreamReader(csDecrypt);<br>        <br>        var decryptedJson = srDecrypt.ReadToEnd();<br>        return JsonSerializer.Deserialize&lt;T&gt;(decryptedJson);<br>    }<br>    <br>    public EncryptedResponse EncryptResponse&lt;T&gt;(T data)<br>    {<br>        // Similar implementation for response encryption<br>        // Generate new AES key, encrypt data, encrypt AES key with RSA<br>        throw new NotImplementedException();<br>    }<br>}</pre><h4>2. Models</h4><pre>// Models/EncryptedRequest.cs<br>public class EncryptedRequest<br>{<br>    public string EncryptedData { get; set; }<br>    public string EncryptedAESKey { get; set; }<br>    public string IV { get; set; }<br>}<br><br>public class EncryptedResponse<br>{<br>    public string EncryptedData { get; set; }<br>    public string EncryptedAESKey { get; set; }<br>    public string IV { get; set; }<br>}</pre><h4>3. Controller Implementation</h4><pre>// Controllers/SecureController.cs<br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class SecureController : ControllerBase<br>{<br>    private readonly ICryptoService _cryptoService;<br>    <br>    public SecureController(ICryptoService cryptoService)<br>    {<br>        _cryptoService = cryptoService;<br>    }<br>    <br>    [HttpGet(&quot;public-key&quot;)]<br>    public IActionResult GetPublicKey()<br>    {<br>        return Ok(new { PublicKey = _cryptoService.GetPublicKey() });<br>    }<br>    <br>    [HttpPost(&quot;data&quot;)]<br>    public IActionResult ProcessSecureData([FromBody] EncryptedRequest request)<br>    {<br>        try<br>        {<br>            var decryptedData = _cryptoService.DecryptRequest&lt;UserData&gt;(request);<br>            <br>            // Process the decrypted data<br>            var result = ProcessUserData(decryptedData);<br>            <br>            // Optionally encrypt the response<br>            return Ok(result);<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest(&quot;Decryption failed&quot;);<br>        }<br>    }<br>    <br>    private object ProcessUserData(UserData userData)<br>    {<br>        // Your business logic here<br>        return new { Success = true, Message = &quot;Data processed successfully&quot; };<br>    }<br>}</pre><h3>Security Considerations and Best Practices</h3><h4>1. HTTPS Requirement</h4><p>The Web Crypto API requires a secure context (HTTPS) to function. This is mandatory for production environments and should be configured during development</p><h4>2. Key Management</h4><ul><li><strong>Rotation:</strong> Implement regular RSA key pair rotation</li><li><strong>Storage: </strong>Store private keys securely using ASP.NET Core Data Protection API</li><li><strong>Distribution:</strong> Use secure channels for public key distribution</li></ul><h4>4. Performance Considerations</h4><ul><li><strong>AES for bulk data:</strong> Use AES for encrypting large payloads due to speed</li><li><strong>RSA for key exchange:</strong> Limit RSA to small data (key exchange only)</li><li><strong>Caching: </strong>Cache public keys appropriately to reduce server requests</li></ul><p>This implementation provides robust end-to-end encryption between Angular 19 clients and .NET APIs while maintaining performance and security best practices. The hybrid approach ensures that sensitive data remains protected throughout the entire communication pipeline, even if intermediate servers or networks are compromised.</p><p>Happy coding 😃</p><h3>Github Repository</h3><p><a href="https://github.com/karanpatel7193/EndtoEndEncryption">https://github.com/karanpatel7193/EndtoEndEncryption</a></p><p>By: <a href="https://www.infoelegant.com/">InfoElegant Solutions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4592cefbe225" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimize your business with inventory automation software]]></title>
            <link>https://medium.com/@karan0740/optimize-your-business-with-inventory-automation-software-8812f6c22c44?source=rss-7ed3bc7cd5be------2</link>
            <guid isPermaLink="false">https://medium.com/p/8812f6c22c44</guid>
            <category><![CDATA[inventory-management]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[business-strategy]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <dc:creator><![CDATA[Karan Patel (Software Engineer)]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 13:09:49 GMT</pubDate>
            <atom:updated>2024-12-18T13:09:49.603Z</atom:updated>
            <content:encoded><![CDATA[<p>Inventory management is one of the most critical aspects of running a successful business. Yet, it’s also one of the most challenging, with risks ranging from overstocking to stockouts, human errors, and inefficient tracking. In today’s fast-paced and competitive market, businesses need a robust solution to streamline inventory processes and ensure optimal stock levels. Software automation emerges as a game-changer, addressing these challenges with efficiency and precision. Here’s how automation can revolutionize inventory management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ejgNufoS3ojc-pHdqSD0-g.jpeg" /><figcaption>eCommerce — Inventory management</figcaption></figure><h3>1. Real-Time Inventory Tracking</h3><p>With software automation, businesses can achieve real-time visibility into their inventory levels. Automated tools track stock movements as they happen, reducing the risk of overstocking or running out of products. Here’s how:</p><ul><li><strong>Automated Updates</strong>: Inventory software instantly updates stock levels as items are sold, returned, or replenished.</li><li><strong>POS Integration</strong>: Point-of-Sale (POS) systems sync with inventory management software to ensure accurate data across all sales channels.</li><li><strong>Barcode and QR Scanning</strong>: Advanced scanning systems automate the process of logging inventory changes, reducing manual errors.</li></ul><h3>2. Demand Forecasting</h3><p>Understanding future demand is critical for maintaining the right inventory levels. Software automation leverages advanced analytics to forecast demand accurately:</p><ul><li><strong>AI-Powered Insights</strong>: Machine learning algorithms analyze historical sales data and market trends to predict future needs.</li><li><strong>Seasonal Adjustments</strong>: Automation identifies patterns in customer behavior during peak seasons or promotional periods, enabling proactive stock adjustments.</li></ul><h3>3. Automated Reordering</h3><p>Never run out of stock again. Automated systems can trigger reorders before inventory runs low:</p><ul><li><strong>Reorder Points</strong>: Set minimum stock thresholds that automatically generate purchase orders when inventory dips below the set level.</li><li><strong>Supplier Integration</strong>: Seamlessly connect with suppliers to streamline reordering and track order statuses.</li></ul><h3>4. Centralized Inventory Management</h3><p>For businesses operating across multiple sales channels, centralized inventory management is essential. Automation makes it seamless:</p><ul><li><strong>Multi-Channel Synchronization</strong>: Track and manage inventory across e-commerce platforms, retail stores, and warehouses in one unified system.</li><li><strong>Cloud-Based Access</strong>: Cloud solutions allow teams to access inventory data anytime, anywhere, ensuring real-time collaboration.</li></ul><h3>5. Warehouse Optimization</h3><p>Efficient warehouse management is a cornerstone of effective inventory control. Automation optimizes warehouse operations:</p><ul><li><strong>Automated Picking and Packing</strong>: Software algorithms determine the most efficient picking routes, reducing fulfillment time.</li><li><strong>Inventory Categorization</strong>: Automate categorization of products based on demand frequency, enabling smarter storage strategies.</li></ul><h3>6. Regular Stock Audits and Reporting</h3><p>Inventory accuracy is vital, and automation ensures consistency through regular audits:</p><ul><li><strong>Cycle Counting</strong>: Inventory software automates cycle counts, replacing the need for disruptive physical inventory checks.</li><li><strong>Detailed Reporting</strong>: Generate comprehensive reports on inventory performance, highlighting slow-moving items and potential issues.</li></ul><h3>7. Minimized Human Errors</h3><p>Manual processes often lead to costly errors. Automation significantly reduces these risks:</p><ul><li><strong>Automated Data Entry</strong>: Eliminate manual entry errors with systems that automatically update inventory records.</li><li><strong>Alerts and Notifications</strong>: Set automated alerts for discrepancies or low stock levels, ensuring prompt action.</li></ul><h3>Key Benefits of Inventory Automation</h3><p>Implementing software automation in inventory management brings numerous advantages:</p><ul><li><strong>Efficiency</strong>: Saves time and labor costs by automating repetitive tasks.</li><li><strong>Accuracy</strong>: Reduces errors and ensures reliable data.</li><li><strong>Scalability</strong>: Supports business growth by handling increased inventory demands.</li><li><strong>Customer Satisfaction</strong>: Ensures product availability and timely delivery.</li></ul><h3>Final Thoughts</h3><p>Inventory management doesn’t have to be a daunting task. By embracing software automation, businesses can streamline operations, reduce costs, and enhance customer satisfaction. Whether you’re a small retailer or a large enterprise, the right inventory automation tools can make a world of difference in achieving operational excellence and staying ahead in a competitive market.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8812f6c22c44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering ES6: Best Coding Practices for Modern JavaScript Development]]></title>
            <link>https://medium.com/@karan0740/mastering-es6-best-coding-practices-for-modern-javascript-development-89de17156d4f?source=rss-7ed3bc7cd5be------2</link>
            <guid isPermaLink="false">https://medium.com/p/89de17156d4f</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[top-10]]></category>
            <dc:creator><![CDATA[Karan Patel (Software Engineer)]]></dc:creator>
            <pubDate>Thu, 12 Dec 2024 13:01:41 GMT</pubDate>
            <atom:updated>2024-12-12T13:01:41.453Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*fTUr6NpgCnfP8ygv5z5TGQ.jpeg" /><figcaption>ES6 — Javascript Best Practices</figcaption></figure><p>ECMAScript 6 (ES6), also known as ECMAScript 2015, introduced a wealth of new features and improvements to JavaScript. These enhancements not only make code more readable and maintainable but also help developers write more efficient and robust applications. In this blog, we’ll explore some of the best coding practices for ES6, complete with examples.</p><h3>1. Use let and const Instead of var</h3><p>ES6 introduced let and const for variable declarations, offering better scoping rules and preventing issues related to hoisting.</p><ul><li>let: Allows block-level scoping and can be reassigned.</li><li>const: Also block-level but cannot be reassigned after its initial assignment.</li></ul><p><strong>Example:</strong></p><pre>// Avoid using &#39;var&#39;<br>var count = 10;<br><br>// Use &#39;let&#39; for variables that will change<br>let count = 10;<br>count = 20; // Valid<br><br>// Use &#39;const&#39; for constants<br>const PI = 3.14;<br>PI = 3.14159; // Error: Assignment to constant variable</pre><h3>2. Arrow Functions</h3><p>Arrow functions provide a concise syntax for writing functions and lexically bind the this value, which can help avoid common pitfalls with traditional functions.</p><p><strong>Example:</strong></p><pre>// Traditional function<br>function add(a, b) {<br>    return a + b;<br>}<br>// Arrow function<br>const add = (a, b) =&gt; a + b;<br>// Arrow function with multiple lines<br>const multiply = (a, b) =&gt; {<br>    const result = a * b;<br>    return result;<br>};</pre><h3>3. Template Literals</h3><p>Template literals (`) allow for easier string interpolation and multiline strings.</p><p><strong>Example:</strong></p><pre>const name = &#39;Alice&#39;;<br>const greeting = `Hello, ${name}!`;<br>console.log(greeting); // Hello, Alice!<br><br>const multiline = `<br>  This is a multiline string.<br>  Each new line is preserved.<br>`;<br>console.log(multiline);</pre><h3>4. Destructuring Assignment</h3><p>Destructuring assignment makes it easy to extract values from arrays or properties from objects into distinct variables.</p><p><strong>Example:</strong></p><pre>// Array destructuring<br>const numbers = [1, 2, 3];<br>const [one, two, three] = numbers;<br>console.log(one, two, three); // 1 2 3<br><br>// Object destructuring<br>const person = { name: &#39;Bob&#39;, age: 30 };<br>const { name, age } = person;<br>console.log(name, age); // Bob 30</pre><h3>5. Default Parameters</h3><p>Default parameters allow you to set default values for function parameters.</p><p><strong>Example:</strong></p><pre>function greet(name = &#39;Guest&#39;) {<br>    return `Hello, ${name}!`;<br>}<br><br>console.log(greet()); // Hello, Guest!<br>console.log(greet(&#39;Alice&#39;)); // Hello, Alice!</pre><h3>6. Spread and Rest Operators</h3><p>The spread operator (...) allows an iterable such as an array to be expanded. The rest operator allows for collecting all remaining elements into an array.</p><p><strong>Example:</strong></p><pre>// Spread operator<br>const arr1 = [1, 2, 3];<br>const arr2 = [4, 5, 6];<br>const combined = [...arr1, ...arr2];<br>console.log(combined); // [1, 2, 3, 4, 5, 6]<br><br>// Rest operator<br>function sum(...numbers) {<br>    return numbers.reduce((acc, num) =&gt; acc + num, 0);<br>}<br>console.log(sum(1, 2, 3)); // 6</pre><h3>7. Promises and Async/Await</h3><p>Promises and async/await simplify working with asynchronous code, making it more readable and easier to manage.</p><p><strong>Example:</strong></p><pre>// Promise example<br>const fetchData = () =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        setTimeout(() =&gt; {<br>            resolve(&#39;Data received&#39;);<br>        }, 2000);<br>    });<br>};<br>fetchData().then(data =&gt; console.log(data)); // Data received<br><br>// Async/Await example<br>const fetchDataAsync = async () =&gt; {<br>    const data = await fetchData();<br>    console.log(data); // Data received<br>};<br>fetchDataAsync();</pre><h3>8. Modules</h3><p>ES6 modules allow you to organize your code into separate files and reuse them across different parts of your application.</p><p><strong>Example:</strong></p><pre>// file: math.js<br>export const add = (a, b) =&gt; a + b;<br>export const multiply = (a, b) =&gt; a * b;<br><br>// file: main.js<br>import { add, multiply } from &#39;./math.js&#39;;<br><br>console.log(add(2, 3)); // 5<br>console.log(multiply(2, 3)); // 6</pre><h3>9. Classes</h3><p>Classes in ES6 provide a clearer and more concise syntax for creating objects and dealing with inheritance.</p><p><strong>Example:</strong></p><pre>class Animal {<br>    constructor(name) {<br>        this.name = name;<br>    }<br>    speak() {<br>        console.log(`${this.name} makes a noise`);<br>    }<br>}<br>class Dog extends Animal {<br>    speak() {<br>        console.log(`${this.name} barks`);<br>    }<br>}<br>const dog = new Dog(&#39;Rex&#39;);<br>dog.speak(); // Rex barks</pre><h3>10. Enhanced Object Literal</h3><p>ES6 provides enhanced object literals that make it easier to define object properties and methods.</p><p><strong>Example:</strong></p><pre>const name = &#39;Alice&#39;;<br>const age = 25;<br><br>// Before ES6<br>const person = {<br>    name: name,<br>    age: age,<br>    greet: function() {<br>        console.log(&#39;Hello&#39;);<br>    }<br>};<br>// With ES6<br>const person = {<br>    name,<br>    age,<br>    greet() {<br>        console.log(&#39;Hello&#39;);<br>    }<br>};</pre><h3>Conclusion</h3><p>Adopting ES6 best practices can greatly enhance the readability, maintainability, and efficiency of your JavaScript code. By using features such as let and const, arrow functions, template literals, destructuring, and more, you can write cleaner and more modern JavaScript. Keep these practices in mind as you develop your next project, and enjoy the benefits of ES6!</p><p>Happy coding! 🌟✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89de17156d4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Optimization Techniques for Angular Applications: Maximizing Efficiency]]></title>
            <link>https://medium.com/@karan0740/performance-optimization-techniques-for-angular-applications-maximizing-efficiency-9e73babae22c?source=rss-7ed3bc7cd5be------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e73babae22c</guid>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[website-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Karan Patel (Software Engineer)]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 09:19:25 GMT</pubDate>
            <atom:updated>2024-12-06T09:19:25.400Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-516cq5q2Z30_tfzzngQ-w.jpeg" /></figure><p>Performance is a critical factor in the success of any web application. In the competitive digital landscape, users expect fast and responsive applications. Angular, as one of the leading frameworks for building single-page applications, provides various tools and best practices to enhance performance. This blog will explore several techniques to optimize the performance of your Angular application, ensuring it runs smoothly and efficiently.</p><h3>1. Ahead-of-Time (AOT) Compilation</h3><p>By default, Angular uses Just-in-Time (JIT) compilation, which compiles the application in the browser at runtime. Switching to Ahead-of-Time (AOT) compilation compiles the application during the build process, resulting in faster rendering and smaller bundle sizes.</p><p>To enable AOT, simply add the --aot flag to your build command:</p><pre>ng build --aot</pre><h3>2. Lazy Loading Modules</h3><p>Lazy loading is a technique that delays the loading of modules until they are needed. This reduces the initial load time of the application by splitting it into smaller chunks.</p><p>Define routes for lazy loading in your app-routing.module.ts:</p><pre>const routes: Routes = [<br>  {<br>    path: &#39;feature&#39;,<br>    loadChildren: () =&gt; import(&#39;./feature/feature.module&#39;).then(m =&gt; m.FeatureModule)<br>  }<br>];</pre><h3>3. OnPush Change Detection Strategy</h3><p>Angular’s default change detection strategy checks the entire component tree for changes, which can be inefficient for large applications. Switching to the OnPush change detection strategy makes Angular check only when an input property changes.</p><p>Use the OnPush strategy in your component:</p><pre>@Component({<br>  selector: &#39;app-example&#39;,<br>  changeDetection: ChangeDetectionStrategy.OnPush,<br>  template: `...`<br>})<br>export class ExampleComponent { }</pre><h3>4. Use TrackBy with ngFor</h3><p>When rendering lists with ngFor, Angular checks the entire list for changes. Using the trackBy function helps Angular track changes more efficiently by identifying items using unique identifiers.</p><pre>&lt;tr *ngFor=&quot;let item of items; trackBy: trackByFn&quot;&gt;<br>  ...<br>&lt;/tr&gt;<br><br>trackByFn(index, item) {<br>  return item.id; // or any unique identifier<br>}</pre><h3>5. Optimize Images and Assets</h3><p>Large images and assets can significantly impact load times. Optimize your images using tools like ImageOptim, TinyPNG, or WebP format to reduce their sizes without compromising quality.</p><pre>npm install ngx-lazy-load-images</pre><p>Use lazy loading for images:</p><pre>&lt;img [defaultImage]=&quot;defaultImageUrl&quot; [lazyLoad]=&quot;imageUrl&quot; [errorImage]=&quot;errorImageUrl&quot;&gt;</pre><h3>6. Enable Gzip Compression</h3><p>Gzip compression reduces the size of files sent from the server to the client, speeding up load times. Enable Gzip in your server configuration (e.g., Nginx or Apache).</p><p>For Nginx:</p><pre>gzip on;<br>gzip_types text/plain application/javascript text/css;</pre><h3>7. Use Angular Universal for Server-Side Rendering (SSR)</h3><p>Angular Universal enables server-side rendering, which pre-renders the application on the server and sends the HTML to the client. This improves initial load times and SEO performance.</p><p>Set up Angular Universal:</p><pre>ng add @nguniversal/express-engine</pre><h3>8. Avoid Memory Leaks</h3><p>Memory leaks can degrade performance over time. Ensure you unsubscribe from Observables and detach event listeners when they are no longer needed.</p><pre>export class ExampleComponent implements OnDestroy {<br>  private subscription: Subscription;<br>  ngOnInit() {<br>    this.subscription = this.someService.someObservable.subscribe(data =&gt; {<br>      // ...<br>    });<br>  }<br>  ngOnDestroy() {<br>    this.subscription.unsubscribe();<br>  }<br>}</pre><h3>9. Minimize Use of Third-Party Libraries</h3><p>While third-party libraries can add functionality, they also increase the bundle size. Use them sparingly and remove any unused libraries.</p><h3>10. Use Browser’s Performance Tools</h3><p>Utilize the browser’s developer tools to profile and analyze the performance of your application. Tools like Chrome’s Lighthouse and Performance tab can provide insights into bottlenecks and areas for improvement.</p><h3>Conclusion</h3><p>Optimizing the performance of your Angular application involves a combination of techniques and best practices. By implementing the strategies outlined in this blog, you can significantly enhance the speed and responsiveness of your application, providing a better user experience. Remember, performance optimization is an ongoing process, and regularly monitoring and fine-tuning your application is key to maintaining its efficiency.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e73babae22c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Micro-Frontend Revolution: Breaking Down Applications for Better Development and Maintenance]]></title>
            <link>https://medium.com/@karan0740/the-micro-frontend-revolution-breaking-down-applications-for-better-development-and-maintenance-df3e44092fbd?source=rss-7ed3bc7cd5be------2</link>
            <guid isPermaLink="false">https://medium.com/p/df3e44092fbd</guid>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <dc:creator><![CDATA[Karan Patel (Software Engineer)]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 08:58:43 GMT</pubDate>
            <atom:updated>2024-12-06T08:58:43.068Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FHbCgoNwZKrtKep8M8KnhQ.jpeg" /><figcaption>Micro front-end</figcaption></figure><p>As web applications grow in complexity, maintaining a monolithic front-end can become increasingly challenging. Enter the concept of micro-frontends — a technique that breaks down a frontend application into smaller, more manageable pieces. This approach not only simplifies development and maintenance but also allows teams to work more independently and efficiently. In this blog, we will explore the principles of micro-frontends, their benefits, and how to implement them with some simple examples.</p><h3>What Are Micro-Frontends?</h3><p>Micro-frontends extend the concept of microservices to the frontend. Instead of building a single, large application, the application is divided into smaller, self-contained units called micro-frontends. Each unit can be developed, tested, and deployed independently, often by different teams. This modular approach brings numerous advantages, including improved scalability, flexibility, and maintainability.</p><h3>Key Benefits of Micro-Frontends</h3><ol><li><strong>Independent Development and Deployment</strong>: Each micro-frontend can be developed and deployed separately, enabling faster release cycles and reducing dependencies between teams.</li><li><strong>Scalability</strong>: Different parts of the application can be scaled independently based on demand, optimizing resource usage.</li><li><strong>Technological Diversity</strong>: Teams can choose different technologies for different micro-frontends, allowing for greater flexibility and experimentation.</li><li><strong>Improved Maintainability</strong>: Smaller, self-contained codebases are easier to understand, maintain, and refactor.</li><li><strong>Enhanced Collaboration</strong>: Teams can work more autonomously, reducing coordination overhead and increasing productivity.</li></ol><h3>Advanced Techniques</h3><p>While iframes provide a simple way to implement micro-frontends, they are not the only method. More advanced techniques include:</p><ul><li><strong>Module Federation</strong>: A feature of Webpack 5 that allows code to be shared dynamically between different applications.</li><li><strong>Single-SPA</strong>: A JavaScript framework for front-end microservices that helps manage multiple micro-frontends in a single application.</li><li><strong>Custom Elements</strong>: Using Web Components to encapsulate micro-frontends as custom HTML elements.</li></ul><h3>Conclusion</h3><p>Micro-frontends offer a powerful way to break down complex applications into manageable, independent units. By enabling independent development, deployment, and scaling, they bring significant benefits in terms of flexibility, maintainability, and team collaboration. While the example provided uses iframes for simplicity, exploring more advanced techniques can unlock even greater potential for your projects. Embrace the micro-frontend revolution and take your web development to the next level!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df3e44092fbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript vs TypeScript: Understanding the Benefits of Using TypeScript in Your Projects]]></title>
            <link>https://medium.com/@karan0740/typescript-vs-javascript-understanding-the-benefits-of-using-typescript-in-your-projects-e1a3f52d75d6?source=rss-7ed3bc7cd5be------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1a3f52d75d6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Karan Patel (Software Engineer)]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 08:42:00 GMT</pubDate>
            <atom:updated>2024-12-06T08:45:57.495Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*OwpNWhytm_FbBXEqZvFq-g.png" /><figcaption>JavsScript vs TypeScript(JS vs TS)</figcaption></figure><p>JavaScript has long been the backbone of web development, allowing developers to create dynamic and interactive web applications. However, as projects grow larger and more complex, managing JavaScript code can become increasingly challenging. This is where TypeScript comes in. Developed by Microsoft, TypeScript is a superset of JavaScript that introduces static typing and other powerful features. In this blog, we’ll explore the key differences between TypeScript and JavaScript, and how TypeScript can enhance your development process.</p><h3>What is TypeScript?</h3><p>TypeScript is an open-source programming language that builds on JavaScript by adding static type definitions. These type definitions help catch errors early in the development process, making the code more robust and easier to maintain. TypeScript code is then converted into plain JavaScript, ensuring compatibility with all JavaScript environments.</p><h3>Key Differences Between TypeScript and JavaScript</h3><h4>Static Typing</h4><p>One of the most significant differences between TypeScript and JavaScript is static typing. In JavaScript, you can declare variables without specifying their data type:</p><pre>// JavaScript<br>let message = &quot;Hello, world!&quot;;<br>message = 42; // This will not cause an error at compile time</pre><p>In TypeScript, you can specify the type of variable, which helps catch type-related errors during compile time:</p><pre>// TypeScript<br>let message: string = &quot;Hello, world!&quot;;<br>// message = 42; // This will cause a compile-time error</pre><h4>Interfaces and Type Aliases</h4><p>TypeScript allows you to define interfaces and type aliases, which makes the code more expressive and easier to understand:</p><pre>// TypeScript<br>interface User {<br>  id: number;<br>  name: string;<br>  email: string;<br>}<br>const user: User = {<br>  id: 1,<br>  name: &quot;Jane Doe&quot;,<br>  email: &quot;jane.doe@example.com&quot;<br>};</pre><p>JavaScript does not have built-in support for interfaces:</p><pre>// JavaScript<br>const user = {<br>  id: 1,<br>  name: &quot;Jane Doe&quot;,<br>  email: &quot;jane.doe@example.com&quot;<br>};</pre><h4>Enums</h4><p>Enums are a feature in TypeScript that allow you to define a set of named constants. This can make your code more readable and maintainable:</p><pre>// TypeScript<br>enum Status {<br>  New,<br>  InProgress,<br>  Completed<br>}<br>let currentStatus: Status = Status.InProgress;</pre><p>JavaScript does not have native support for enums:</p><pre>// JavaScript<br>const Status = {<br>  New: 0,<br>  InProgress: 1,<br>  Completed: 2<br>};<br>let currentStatus = Status.InProgress;</pre><h4>Advanced Type Features</h4><p>TypeScript provides advanced type features like union types, intersection types, and generics, which offer greater flexibility and control over your code:</p><pre>// TypeScript<br>function combine(input1: number | string, input2: number | string) {<br>  if (typeof input1 === &quot;number&quot; &amp;&amp; typeof input2 === &quot;number&quot;) {<br>    return input1 + input2;<br>  } else {<br>    return input1.toString() + input2.toString();<br>  }<br>}<br>console.log(combine(10, 20)); // 30<br>console.log(combine(&quot;Hello, &quot;, &quot;world!&quot;)); // &quot;Hello, world!&quot;</pre><h3>Benefits of Using TypeScript</h3><h4>Early Error Detection</h4><p>With static typing, TypeScript catches errors at compile time, which reduces the likelihood of runtime errors and makes debugging easier.</p><h4>Improved Code Readability and Maintainability</h4><p>Type annotations and interfaces make the code more readable and self-documenting, which is particularly beneficial for large projects and team collaborations.</p><h4>Enhanced Tooling Support</h4><p>TypeScript offers enhanced support for modern code editors like Visual Studio Code, providing features like autocompletion, type checking, and inline documentation.</p><h4>Seamless Integration with JavaScript</h4><p>TypeScript is a superset of JavaScript, meaning any valid JavaScript code is also valid TypeScript code. This makes it easy to gradually adopt TypeScript in existing projects.</p><h3>Conclusion</h3><p>While JavaScript remains a powerful and flexible language, TypeScript offers several advantages that can make your development process more efficient and your code more robust. By adding static typing, interfaces, and other powerful features, TypeScript enhances JavaScript’s capabilities and helps you build scalable, maintainable applications. If you’re working on a large-scale project or simply want to improve your coding experience, give TypeScript a try. You might find it becomes an indispensable tool in your development toolkit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1a3f52d75d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering CRUD Operations in Next.js: A Comprehensive Guide]]></title>
            <link>https://medium.com/@karan0740/mastering-crud-operations-in-next-js-a-comprehensive-guide-bda8322a1814?source=rss-7ed3bc7cd5be------2</link>
            <guid isPermaLink="false">https://medium.com/p/bda8322a1814</guid>
            <category><![CDATA[crud]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Karan Patel (Software Engineer)]]></dc:creator>
            <pubDate>Thu, 05 Dec 2024 06:53:41 GMT</pubDate>
            <atom:updated>2024-12-05T06:53:41.774Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating robust web applications often involves handling data through basic operations known as CRUD: Create, Read, Update, and Delete. Next.js, with its powerful features and flexibility, makes it an excellent choice for building such applications. In this guide, we’ll dive into how you can implement CRUD operations in a Next.js application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7HL2wgmwamQBevnAj8PZg.jpeg" /><figcaption>Next.JS CRUD operation</figcaption></figure><h4>Setting Up Your Project</h4><p>First, ensure you have Node.js installed. Then, create a new Next.js project:</p><pre>npx create-next-app crud-nextjs<br>cd crud-nextjs</pre><h4>Creating the Backend API</h4><p>For simplicity, we’ll use a JSON file as our database. Create a data directory in the root of your project and a db.json file inside it:</p><pre>{<br>  &quot;posts&quot;: [<br>    { &quot;id&quot;: 1, &quot;title&quot;: &quot;First Post&quot;, &quot;content&quot;: &quot;This is my first post&quot; }<br>  ]<br>}</pre><p>Next, install json-server to create a REST API:</p><pre>npm install json-server</pre><p>Add a script to your package.json to start the JSON server:</p><pre>&quot;scripts&quot;: {<br>  &quot;json-server&quot;: &quot;json-server --watch data/db.json --port 3001&quot;<br>}</pre><p>Start the JSON server:</p><pre>npm run json-server</pre><p>Your API is now running at <a href="http://localhost:3001/posts.">http://localhost:3001/posts.</a></p><h4>Integrating API with Next.js</h4><p>Create a new file lib/api.js to handle API requests:</p><pre>const API_URL = &#39;http://localhost:3001/posts&#39;;</pre><pre>export const fetchPosts = async () =&gt; {<br>  const res = await fetch(API_URL);<br>  return res.json();<br>};</pre><pre>export const createPost = async (post) =&gt; {<br>  const res = await fetch(API_URL, {<br>    method: &#39;POST&#39;,<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;<br>    },<br>    body: JSON.stringify(post)<br>  });<br>  return res.json();<br>};</pre><pre>export const updatePost = async (id, post) =&gt; {<br>  const res = await fetch(`${API_URL}/${id}`, {<br>    method: &#39;PUT&#39;,<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;<br>    },<br>    body: JSON.stringify(post)<br>  });<br>  return res.json();<br>};</pre><pre>export const deletePost = async (id) =&gt; {<br>  const res = await fetch(`${API_URL}/${id}`, {<br>    method: &#39;DELETE&#39;<br>  });<br>  return res.json();<br>};</pre><h4>Creating Pages and Components</h4><p>Now, let’s create our pages and components for CRUD operations.</p><p><strong>1. List Posts</strong></p><p>Create pages/index.js to list all posts:</p><pre>import { useEffect, useState } from &#39;react&#39;;<br>import { fetchPosts } from &#39;../lib/api&#39;;</pre><pre>const Home = () =&gt; {<br>  const [posts, setPosts] = useState([]);</pre><pre>  useEffect(() =&gt; {<br>    const getPosts = async () =&gt; {<br>      const postsData = await fetchPosts();<br>      setPosts(postsData);<br>    };<br>    getPosts();<br>  }, []);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Posts&lt;/h1&gt;<br>      &lt;ul&gt;<br>        {posts.map(post =&gt; (<br>          &lt;li key={post.id}&gt;{post.title}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default Home;</pre><p><strong>2. Create Post</strong></p><p>Create pages/create.js:</p><pre>import { useState } from &#39;react&#39;;<br>import { createPost } from &#39;../lib/api&#39;;</pre><pre>const CreatePost = () =&gt; {<br>  const [title, setTitle] = useState(&#39;&#39;);<br>  const [content, setContent] = useState(&#39;&#39;);</pre><pre>  const handleSubmit = async (e) =&gt; {<br>    e.preventDefault();<br>    const newPost = { title, content };<br>    await createPost(newPost);<br>    setTitle(&#39;&#39;);<br>    setContent(&#39;&#39;);<br>  };</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Create Post&lt;/h1&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          value={title}<br>          onChange={(e) =&gt; setTitle(e.target.value)}<br>          placeholder=&quot;Title&quot;<br>        /&gt;<br>        &lt;textarea<br>          value={content}<br>          onChange={(e) =&gt; setContent(e.target.value)}<br>          placeholder=&quot;Content&quot;<br>        &gt;&lt;/textarea&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Create&lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default CreatePost;</pre><p><strong>3. Update Post</strong></p><p>Create pages/edit/[id].js:</p><pre>import { useEffect, useState } from &#39;react&#39;;<br>import { useRouter } from &#39;next/router&#39;;<br>import { fetchPosts, updatePost } from &#39;../../lib/api&#39;;</pre><pre>const EditPost = () =&gt; {<br>  const router = useRouter();<br>  const { id } = router.query;<br>  const [post, setPost] = useState({ title: &#39;&#39;, content: &#39;&#39; });</pre><pre>  useEffect(() =&gt; {<br>    if (id) {<br>      const getPost = async () =&gt; {<br>        const posts = await fetchPosts();<br>        const selectedPost = posts.find(post =&gt; post.id === Number(id));<br>        setPost(selectedPost);<br>      };<br>      getPost();<br>    }<br>  }, [id]);</pre><pre>  const handleSubmit = async (e) =&gt; {<br>    e.preventDefault();<br>    await updatePost(id, post);<br>    router.push(&#39;/&#39;);<br>  };</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Edit Post&lt;/h1&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          value={post.title}<br>          onChange={(e) =&gt; setPost({ ...post, title: e.target.value })}<br>          placeholder=&quot;Title&quot;<br>        /&gt;<br>        &lt;textarea<br>          value={post.content}<br>          onChange={(e) =&gt; setPost({ ...post, content: e.target.value })}<br>          placeholder=&quot;Content&quot;<br>        &gt;&lt;/textarea&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Update&lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default EditPost;</pre><p><strong>4. Delete Post</strong></p><p>Update pages/index.js to include a delete button:</p><pre>import { useEffect, useState } from &#39;react&#39;;<br>import { fetchPosts, deletePost } from &#39;../lib/api&#39;;</pre><pre>const Home = () =&gt; {<br>  const [posts, setPosts] = useState([]);</pre><pre>  useEffect(() =&gt; {<br>    const getPosts = async () =&gt; {<br>      const postsData = await fetchPosts();<br>      setPosts(postsData);<br>    };<br>    getPosts();<br>  }, []);</pre><pre>  const handleDelete = async (id) =&gt; {<br>    await deletePost(id);<br>    setPosts(posts.filter(post =&gt; post.id !== id));<br>  };</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Posts&lt;/h1&gt;<br>      &lt;ul&gt;<br>        {posts.map(post =&gt; (<br>          &lt;li key={post.id}&gt;<br>            {post.title}<br>            &lt;button onClick={() =&gt; handleDelete(post.id)}&gt;Delete&lt;/button&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default Home;</pre><h4>Conclusion</h4><p>You’ve now implemented a basic CRUD application in Next.js. This setup provides a solid foundation for more advanced features, such as authentication, role-based access, and more complex data models. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bda8322a1814" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>