<?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"><channel><title><![CDATA[dubeyjags]]></title><description><![CDATA[about the frontend code sniipets]]></description><link>https://blog.dubeyjags.cloud</link><generator>RSS for Node</generator><lastBuildDate>Wed, 14 Oct 2026 03:43:59 GMT</lastBuildDate><atom:link href="https://blog.dubeyjags.cloud/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How ChatGPT Understands Your Questions]]></title><description><![CDATA[hi]]></description><link>https://blog.dubeyjags.cloud/how-chatgpt-understands-your-questions</link><guid isPermaLink="true">https://blog.dubeyjags.cloud/how-chatgpt-understands-your-questions</guid><dc:creator><![CDATA[Jags Dubey]]></dc:creator><pubDate>Wed, 01 Jul 2026 13:12:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/678bc495afaa8987c0850d21/175782a1-f761-4a82-b4e9-3818fdc3a3db.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>hi</p>
]]></content:encoded></item><item><title><![CDATA[Setup : Postgressql with Prisma and Neon]]></title><description><![CDATA[A starter project demonstrating how to use Prisma ORM with a PostgreSQL database using the node-postgres (pg) driver adapter.
Prerequisites

Node.js v18+

pnpm v10+

A running PostgreSQL instance (loc]]></description><link>https://blog.dubeyjags.cloud/setup-postgressql-with-prisma-and-neon</link><guid isPermaLink="true">https://blog.dubeyjags.cloud/setup-postgressql-with-prisma-and-neon</guid><dc:creator><![CDATA[Jags Dubey]]></dc:creator><pubDate>Tue, 23 Jun 2026 14:59:36 GMT</pubDate><content:encoded><![CDATA[<p>A starter project demonstrating how to use Prisma ORM with a PostgreSQL database using the <code>node-postgres</code> (<code>pg</code>) driver adapter.</p>
<h2>Prerequisites</h2>
<ul>
<li><p><a href="https://nodejs.org/">Node.js</a> v18+</p>
</li>
<li><p><a href="https://pnpm.io/">pnpm</a> v10+</p>
</li>
<li><p>A running PostgreSQL instance (local or hosted)</p>
</li>
</ul>
<h2>Setup</h2>
<h3>1. Install dependencies</h3>
<pre><code class="language-bash">pnpm add prisma @types/pg typescript @types/node tsx --save-dev
pnpm add @prisma/client @prisma/adapter-pg pg dotenv
</code></pre>
<p>What each package does:</p>
<table>
<thead>
<tr>
<th>Package</th>
<th>Role</th>
</tr>
</thead>
<tbody><tr>
<td><code>prisma</code></td>
<td>Prisma CLI — <code>prisma init</code>, <code>prisma migrate</code>, <code>prisma generate</code>, etc.</td>
</tr>
<tr>
<td><code>@prisma/client</code></td>
<td>Prisma Client library for querying your database</td>
</tr>
<tr>
<td><code>@prisma/adapter-pg</code></td>
<td>node-postgres driver adapter that connects Prisma Client to PostgreSQL</td>
</tr>
<tr>
<td><code>pg</code></td>
<td>node-postgres database driver</td>
</tr>
<tr>
<td><code>dotenv</code></td>
<td>Loads environment variables from <code>.env</code></td>
</tr>
<tr>
<td><code>@types/pg</code></td>
<td>TypeScript type definitions for node-postgres</td>
</tr>
<tr>
<td><code>tsx</code></td>
<td>TypeScript executor — run <code>.ts</code> files directly without compiling</td>
</tr>
<tr>
<td><code>typescript</code> / <code>@types/node</code></td>
<td>TypeScript compiler and Node.js type definitions</td>
</tr>
</tbody></table>
<h3>2. Initialize Prisma</h3>
<pre><code class="language-bash">npx prisma init
</code></pre>
<p>This creates:</p>
<ul>
<li><p><code>prisma/schema.prisma</code> — your schema file</p>
</li>
<li><p><code>.env</code> — with a <code>DATABASE_URL</code> placeholder</p>
</li>
</ul>
<h3>3. Configure environment</h3>
<p>Edit <code>.env</code> with your PostgreSQL connection string:</p>
<pre><code class="language-env">DATABASE_URL="postgresql://USER:PASSWORD@HOST:PORT/DATABASE"
</code></pre>
<p>Example for a local database:</p>
<pre><code class="language-env">DATABASE_URL="postgresql://postgres:password@localhost:5432/mydb"
</code></pre>
<blockquote>
<p>Never commit <code>.env</code> to version control. Add it to <code>.gitignore</code>.</p>
</blockquote>
<h3>4. Define your schema</h3>
<p>Edit <code>prisma/schema.prisma</code>:</p>
<pre><code class="language-prisma">generator client {
  provider = "prisma-client"
  output   = "../lib/generated/prisma"
}

datasource db {
  provider = "postgresql"
}

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  published Boolean @default(false)
  author    User    @relation(fields: [authorId], references: [id])
  authorId  Int
}
</code></pre>
<blockquote>
<p>The <code>output</code> path in the <code>generator</code> block controls where the generated Prisma Client is written. Here it outputs to <code>lib/generated/prisma</code>, which is why the import path is <code>./generated/prisma/client</code>.</p>
</blockquote>
<h3>5. Run migrations</h3>
<pre><code class="language-bash">npx prisma migrate dev
</code></pre>
<p>This creates the tables in your database and generates the Prisma Client automatically.</p>
<p>To regenerate the client without creating a new migration (e.g. after a manual schema edit):</p>
<pre><code class="language-bash">npx prisma generate
</code></pre>
<h3>6. Open Prisma Studio (optional)</h3>
<p>A visual browser-based editor for your database:</p>
<pre><code class="language-bash">npx prisma studio
</code></pre>
<h2>Database client</h2>
<p>Create <code>lib/db.ts</code> to set up a singleton Prisma Client instance:</p>
<pre><code class="language-ts">import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "./generated/prisma/client";

const globalForPrisma = globalThis as unknown as {
  prisma: PrismaClient | undefined;
};

function createPrismaClient() {
  const url = process.env.DATABASE_URL;
  if (!url) {
    throw new Error("DATABASE_URL is not defined");
  }
  const adapter = new PrismaPg({ connectionString: url });
  const client = new PrismaClient({ adapter });
  return client;
}

export const prisma = globalForPrisma.prisma ?? createPrismaClient();

if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
</code></pre>
<blockquote>
<p>The global singleton pattern prevents creating multiple Prisma Client instances during hot reloads in development (e.g. Next.js).</p>
</blockquote>
<h2>Test the connection</h2>
<p>Create <code>script.ts</code> at the project root:</p>
<pre><code class="language-ts">import { prisma } from "./lib/db";

async function main() {
  // Create a user with a post
  const user = await prisma.user.create({
    data: {
      name: "Alice",
      email: "alice@prisma.io",
      posts: {
        create: {
          title: "Hello World",
          content: "This is my first post!",
          published: true,
        },
      },
    },
    include: { posts: true },
  });
  console.log("Created user:", user);

  // Fetch all users with their posts
  const allUsers = await prisma.user.findMany({
    include: { posts: true },
  });
  console.log("All users:", JSON.stringify(allUsers, null, 2));
}

main()
  .then(async () =&gt; {
    await prisma.$disconnect();
  })
  .catch(async (e) =&gt; {
    console.error(e);
    await prisma.$disconnect();
    process.exit(1);
  });
</code></pre>
<p>Run it:</p>
<pre><code class="language-bash">pnpm dlx tsx script.ts
</code></pre>
<h2>Project structure</h2>
<pre><code class="language-plaintext">.
├── lib/
│   ├── db.ts                    # Prisma Client singleton
│   └── generated/prisma/        # Auto-generated Prisma Client (do not edit)
├── prisma/
│   ├── schema.prisma            # Database schema
│   └── migrations/              # Migration history
├── prisma.config.ts             # Prisma CLI configuration
├── script.ts                    # Test / seed script
├── .env                         # Environment variables (not committed)
└── tsconfig.json
</code></pre>
<h2>Common commands</h2>
<table>
<thead>
<tr>
<th>Command</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td><code>npx prisma init</code></td>
<td>Initialize Prisma in a new project</td>
</tr>
<tr>
<td><code>npx prisma migrate dev</code></td>
<td>Create a migration and apply it (dev only)</td>
</tr>
<tr>
<td><code>npx prisma migrate deploy</code></td>
<td>Apply pending migrations (production)</td>
</tr>
<tr>
<td><code>npx prisma generate</code></td>
<td>Regenerate Prisma Client from schema</td>
</tr>
<tr>
<td><code>npx prisma studio</code></td>
<td>Open the visual database browser</td>
</tr>
<tr>
<td><code>npx prisma db push</code></td>
<td>Push schema changes without a migration file</td>
</tr>
<tr>
<td><code>npx prisma db seed</code></td>
<td>Run the seed script defined in <code>package.json</code></td>
</tr>
<tr>
<td><code>pnpm dlx tsx script.ts</code></td>
<td>Run a TypeScript file directly</td>
</tr>
</tbody></table>
]]></content:encoded></item><item><title><![CDATA[Setup : Monorepo-turborepo-tRPC]]></title><description><![CDATA[Multi-repo VS Monorepo

Multirepo - react-frontend, express backend, postgress-db, redis server

Monorepo - sigle repo > one repo can contain frontent, backend, shared utils and types etc example proj]]></description><link>https://blog.dubeyjags.cloud/setup-monorepo-turborepo-trpc</link><guid isPermaLink="true">https://blog.dubeyjags.cloud/setup-monorepo-turborepo-trpc</guid><dc:creator><![CDATA[Jags Dubey]]></dc:creator><pubDate>Tue, 23 Jun 2026 07:17:19 GMT</pubDate><content:encoded><![CDATA[<h2>Multi-repo VS Monorepo</h2>
<ul>
<li><p>Multirepo - react-frontend, express backend, postgress-db, redis server</p>
</li>
<li><p>Monorepo - sigle repo &gt; one repo can contain frontent, backend, shared utils and types etc example project</p>
</li>
<li><p>apps -- web (fully deployed app) -- api // fully deployed backend</p>
</li>
<li><p>packages -- shared // common utils, db connection, schema</p>
</li>
</ul>
<p><strong>Benefits =&gt; code sharing, atomic commits, better team collab, unified cicd &amp; tooling</strong></p>
<p><strong>PNPM =&gt; Performant NPM ,like npm,yarn or bun</strong> // popular in monorepo</p>
<ul>
<li><p>Fast</p>
</li>
<li><p>Disk space efficient</p>
</li>
<li><p>insted of duplicate is store in central place and each time take refrence symlinks</p>
</li>
</ul>
<p>PNPM vs NPM</p>
<p>pnpm-workspaces &gt; depened on each other, import each other, share efficiently, install and run packages together</p>
<h2>Project setup</h2>
<p><code>npm i pnpm</code><br /><code>mkdir monorepo &amp;&amp; cd monorepo</code><br /><code>pnpm init</code> // update with required things</p>
<blockquote>
<p>package.json</p>
</blockquote>
<pre><code class="language-json">{
  "name": "monorepo",
  "private": true,
  "types": "module",
  "packageManager": "pnpm@10.33.4"
}
</code></pre>
<h3>Folder setup</h3>
<p><code>mkdir apps packages apps/api apps/web packages/utils</code></p>
<blockquote>
<p>pnpm-workspace.yaml</p>
</blockquote>
<p>the line that makes it a workspace. Any folder under apps/ or packages/ is now a linkable package:</p>
<pre><code class="language-yml">packages:
  - "apps/*"
  - "packages/*"
allowBuilds:
  esbuild: true
</code></pre>
<h3>Shared package setup</h3>
<blockquote>
<p>packages/utils</p>
</blockquote>
<p><code>pnpm init</code><br /><code>pnpm add -D typescript</code><br /><code>pnpm add zod</code><br /><code>tsc --init</code></p>
<blockquote>
<p>packages/utils/package.json</p>
</blockquote>
<pre><code class="language-json">{
  "name": "@monorepo/utils",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "dev": "tsc --watch",
    "build": "tsc"
  },
  "exports": {
    ".": "./src/index.ts"
  },
  "packageManager": "pnpm@10.33.4",
  "devDependencies": {
    "typescript": "^6.0.3"
  },
  "dependencies": {
    "zod": "^4.4.3"
  }
}
</code></pre>
<blockquote>
<p>packages/utils/tsconfig.json</p>
</blockquote>
<pre><code class="language-json">{
    // Visit https://aka.ms/tsconfig to read more about this file
    "compilerOptions": {
        // File Layout
        "rootDir": "./src", // ts
        "outDir": "./dist", // js

        // Environment Settings
        // See also https://aka.ms/tsconfig/module
        "module": "nodenext",
        "target": "esnext",
        "types": [],
        // For nodejs:
        // "lib": ["esnext"],
        // "types": ["node"],
        // and npm install -D @types/node

        // Other Outputs
        "sourceMap": true,
        "declaration": true,
        "declarationMap": true,

        // Stricter Typechecking Options
        "noUncheckedIndexedAccess": true,
        "exactOptionalPropertyTypes": true,

        // Style Options
        // "noImplicitReturns": true,
        // "noImplicitOverride": true,
        // "noUnusedLocals": true,
        // "noUnusedParameters": true,
        // "noFallthroughCasesInSwitch": true,
        // "noPropertyAccessFromIndexSignature": true,

        // Recommended Options
        "strict": true,
        "jsx": "react-jsx",
        "verbatimModuleSyntax": true,
        "isolatedModules": true,
        "noUncheckedSideEffectImports": true,
        "moduleDetection": "force",
        "skipLibCheck": true
    }
}

</code></pre>
<blockquote>
<p>packages/utils/src/index.ts</p>
</blockquote>
<p>Create Zod schema // for frontend and backend validation</p>
<pre><code class="language-ts">import { z } from 'zod';
export const createUserSchema = z.object({
    name: z.string().min(3, "Name must be at least 3 characters long"),
    email: z.email("Invalid email address"),
    password: z.string().min(6, "Password must be at least 6 characters long")
})

export type CreateUserSchema = z.infer&lt;typeof createUserSchema&gt;; // zod will create schema like this
</code></pre>
<blockquote>
<p>packages/utils/package.json export the index file</p>
</blockquote>
<pre><code class="language-json">"exports":{
    ".":"./src/index.ts"
}
</code></pre>
<blockquote>
<p>packages/utils <code>pnpm build</code></p>
</blockquote>
<h3>Backend setup</h3>
<blockquote>
<p>apps/api</p>
</blockquote>
<p>Backend setup for API</p>
<p><code>pnpm init</code><br /><code>pnpm add express @types/express -D typescript tsx @types/node</code><br /><code>tsc --init</code></p>
<p><strong>update .tsconfig.json</strong></p>
<ul>
<li><p>rootDir</p>
</li>
<li><p>outDir</p>
</li>
<li><p>lib</p>
</li>
<li><p>types</p>
</li>
</ul>
<blockquote>
<p>apps/api/package.json update with</p>
</blockquote>
<pre><code class="language-json">{
  "name": "@monorepo/api",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "dev": "tsx watch src/index.ts",
    "build": "tsc"
  },
  "packageManager": "pnpm@10.33.4",
  "devDependencies": {
    "@types/express": "^5.0.6",
    "@types/node": "^26.0.0",
    "express": "^5.2.1",
    "tsx": "^4.22.4",
    "typescript": "^6.0.3"
  }
}
</code></pre>
<blockquote>
<p>apps/api/src/index.ts</p>
</blockquote>
<p>Basic get request</p>
<pre><code class="language-ts">import express  from "express";
const app = express();
const PORT = 5000;
app.use(express.json());

app.get("/", (req, res) =&gt; {
    return res.json({ message: "Hello from API" });
})

app.listen(PORT, () =&gt; {
    console.log(`Server is running on port ${PORT}`);
});
</code></pre>
<h4>Now import ZOD schema to the backend api</h4>
<blockquote>
<p>apps/api/package.json name:"@projectName/api" // "@repo/api" dependcies:{ "@projectName/utils": "workspace:*" // indicate get from local not version } apps/api <code>pnpm i</code> // insalled and symlinks created</p>
</blockquote>
<blockquote>
<p>apps/api/src/index.ts Import Zod from symlinks or shared folder</p>
</blockquote>
<pre><code class="language-ts">import { createUserSchema } from "@monorepo/utils";
app.post("/users", (req, res) =&gt; {
    const result = createUserSchema.safeParse(req.body);
    if(!result.success) {
        const message = result.error.issues.map((issue) =&gt; issue.message).join(", ")
        return res.status(400).json({success:false, message:message });
    }
    console.log(result.data);
    return res.json({success:true, message: "User created" });
});
</code></pre>
<h3>Frontend setup</h3>
<blockquote>
<p>apps/web</p>
</blockquote>
<p><code>pnpm create next-app .</code><br />remove <strong>pnpm-workspace.yaml</strong> its confilict remove <strong>public</strong> folder</p>
<blockquote>
<p>package/web/package.json update the dependencies "name": "@monorepo/web",// "@repo/utils" <code>pnpm i</code></p>
</blockquote>
<blockquote>
<p>package/web/app/page.tsx</p>
</blockquote>
<pre><code class="language-tsx">"use client";
import { createUserSchema } from "@monorepo/utils";
import axios from "axios";
import { useState } from "react";
import type { SubmitEvent } from "react";

export default function Home() {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    password: "",
  });
  const [errors, setErrors] = useState("");
  const [success, setSuccess] = useState(false);
  const handleSubmt = async (e: SubmitEvent&lt;HTMLFormElement&gt;) =&gt; {
    setSuccess(false);
    setErrors("");
    e.preventDefault();
    const result = createUserSchema.safeParse(formData);
    if (!result.success) {
      const message = result.error.issues
        .map((issue) =&gt; issue.message)
        .join(", ");
      setErrors(message);
      return alert(message);
    }
    console.log(result.data);
    try {
      const res = await axios.post("http://localhost:5000/users", result.data);
      console.log(res);
      setSuccess(true);
    } catch (error) {
      console.log(error);
    }
  };
  return (
    &lt;form onSubmit={handleSubmt} noValidate&gt;
      {errors &amp;&amp; errors.split(", ").map((error, i) =&gt; &lt;p key={i}&gt;{error}&lt;/p&gt;)}
      {success &amp;&amp; &lt;p&gt;Success&lt;/p&gt;}
      &lt;input
        type="text"
        onChange={(e) =&gt; setFormData({ ...formData, name: e.target.value })}
      /&gt;
      &lt;input
        type="email"
        onChange={(e) =&gt; setFormData({ ...formData, email: e.target.value })}
      /&gt;
      &lt;input
        type="password"
        onChange={(e) =&gt; setFormData({ ...formData, password: e.target.value })}
      /&gt;
      &lt;button type="submit"&gt;Submit&lt;/button&gt;
    &lt;/form&gt;
  );
}

</code></pre>
<blockquote>
<p>package/web <code>pnpm i axios</code> and update package/web/app/page.tsx post requiest on submit ""</p>
</blockquote>
<pre><code class="language-ts">const res = await axios.post("http://localhost:5000/users", result.data)
</code></pre>
<p><strong>check for cors error and make form submit</strong></p>
<h3>all in one setup for all</h3>
<p>for all run and build from one place</p>
<blockquote>
<p>package.json</p>
</blockquote>
<pre><code class="language-json">"scripts": {
    "dev": "pnpm -r --parallel dev",
    "build": "pnpm -r build"
  }
</code></pre>
<h2>TurboRepo setup</h2>
<p>package is depandend on each other (dependcy graph). Build in Right order</p>
<h3>Turbo repo // turborepo.dev</h3>
<ul>
<li><p>Build order manage</p>
</li>
<li><p>caching</p>
</li>
<li><p>task orchestration</p>
</li>
<li><p>parrlel excuation</p>
</li>
</ul>
<h3>Add turbo in project</h3>
<p><code>pnpm add -D turbo -w</code> // -w is for do it now</p>
<blockquote>
<p>turbo.json</p>
</blockquote>
<pre><code class="language-json">{
    "$schema":"https://turbo.build/schema.json",
    "ui":"tui", // terminal ui to looks good the console the logs for each server
    "tasks":{
        "build": {
            "dependsOn": ["^build"], // check for dependent other build (resolve dependecy graph)
            "outputs": ["dist/**", "next/**", "!dist/**/node_modules/**", "!next/**/node_modules/**", "!.next/cache/**"] //caching
        },
        "dev":{
            "cache": false, // no need to cache
            "persistent": true // long running
        },
        "prettier":{
            "cache": false,
            "persistent": true
        },
        "lint":{
            "cache": false,
            "persistent": true
        }
    }
}
</code></pre>
<blockquote>
<p>package.json</p>
</blockquote>
<pre><code class="language-json">  "scripts": {
    "dev": "turbo dev",
    "build": "turbo build"
  },
</code></pre>
<p>at Root folder <code>pnpm dev</code> <code>pnpm build</code></p>
<h2>tRPC (Remote procedure calls)</h2>
<p>clinet will call the remote server RPC concept call without "stings" call the direct methods impelentation (gRPC and tRPC)</p>
<h3>Packages or share utils</h3>
<blockquote>
<p>packages/trpc <code>pnpm init</code> <code>pnpm add -D typescript</code> <code>pnpm add @trpc/server</code> <code>tsc --init</code> packages/trpc/package.json</p>
</blockquote>
<pre><code class="language-json">"name":"@monorepo/trpc"
private:true
export:trpc
dependies:{
    "@monorepo/utils": "workspace:*",
}
scripts:{
    "dev":"tsc --watch",
    "build":"tsc"
}
</code></pre>
<blockquote>
<p>packages/trpc/src/trpc.ts</p>
</blockquote>
<pre><code class="language-ts">import { initTRPC } from '@trpc/server';
const t = initTRPC.create();
export const router = t.router; // rotuer &gt; function declare
export const procedure = t.procedure; // functions
</code></pre>
<blockquote>
<p>packages/trpc/src/router.ts</p>
</blockquote>
<pre><code class="language-ts">import { procedure, router } from "./trpc.js";
import { createUserSchema } from "@peer-class/utils";
export const appRouter = router({
    health: procedure.query(() =&gt; {
        return {
            message: "healthy"
        }
    }),
    register: procedure
        .input(createUserSchema)
        .mutation(({ input }) =&gt; {
            // TODO: persist user to DB
            console.log("register", input);
            return {
                message: "User Registered Successfully"
            }
        }),
});

export type AppRouter = typeof appRouter;
</code></pre>
<blockquote>
<p>packages/trpc/src/index.ts</p>
</blockquote>
<pre><code class="language-ts">export { appRouter } from './router.js';
export type { AppRouter } from './router.js';
</code></pre>
<p><code>pnpm i</code></p>
<h3>Backend</h3>
<blockquote>
<p>apps/api/ <code>pnpm add @trpc/server</code></p>
</blockquote>
<p>add trpc package at package.json <code>pnpm i</code></p>
<blockquote>
<p>apps/api/src/index.ts</p>
</blockquote>
<pre><code class="language-ts">import { createExpressMiddleware } from "@trpc/server/adapters/express";
import { appRouter } from "@peer-class/trpc";
// remove app.get (no need of rest api)
app.use(
    "/trpc",
    createExpressMiddleware({
        router: appRouter
    })
);
</code></pre>
<h3>Frontend</h3>
<blockquote>
<p>apps/web <code>pnpm add @trpc/client @tanstack/react-query @trpc/react-query</code> app/web/trpc/trpc.ts</p>
</blockquote>
<pre><code class="language-ts">import { createTRPCReact } from "@trpc/react-query";
import type { AppRouter } from "@peer-class/trpc";
export const trpc = createTRPCReact&lt;AppRouter&gt;();
</code></pre>
<blockquote>
<p>app/web/trpc/Provider.tsx</p>
</blockquote>
<pre><code class="language-tsx">'use client';
import { useState } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { httpBatchLink } from "@trpc/client";
import { trpc } from "./trpc";

export function Provider({ children }: { children: React.ReactNode }) {
    // React Query client — manages server state caching, background refetching, etc.
    const [queryClient] = useState(() =&gt; new QueryClient());

    // tRPC client — batches multiple procedure calls into a single HTTP request to /trpc
    const [trpcClient] = useState(() =&gt;
        trpc.createClient({
            links: [
                httpBatchLink({
                    url: "http://localhost:5000/trpc",
                }),
            ],
        })
    );

    // trpc.Provider bridges tRPC with React Query so tRPC hooks use the shared queryClient
    return (
        &lt;trpc.Provider client={trpcClient} queryClient={queryClient}&gt;
            &lt;QueryClientProvider client={queryClient}&gt;{children}&lt;/QueryClientProvider&gt;
        &lt;/trpc.Provider&gt;
    );
}

/*
 * What this file does:
 * ---------------------
 * Sets up the tRPC + React Query context for the entire Next.js app.
 *
 * - QueryClient      → React Query's cache store. Holds all server-state (queries/mutations).
 * - trpcClient       → HTTP client that sends batched requests to the Express backend at
 *                      http://localhost:5000/trpc using tRPC's httpBatchLink.
 * - trpc.Provider    → Makes tRPC hooks (trpc.*.useQuery / useMutation) available in the tree.
 * - QueryClientProvider → Makes React Query hooks (useQuery, useMutation) available in the tree.
 *
 * Both providers share the same queryClient so tRPC and React Query stay in sync.
 * Wrap the root layout (layout.tsx) with this Provider to enable tRPC across the whole app.
 */
</code></pre>
<blockquote>
<p>apps/web/app/layout.tsx</p>
</blockquote>
<pre><code class="language-tsx">import { Provider } from "../trpc/Provider";
&lt;Provider&gt;{children}&lt;/Provider&gt; // get everywhere for query and mutations
</code></pre>
<blockquote>
<p>apps/web/app/health/page.tsx</p>
</blockquote>
<pre><code class="language-tsx">'use client';
import { trpc } from "@/trpc/trpc"
export default function Health(){
    const health = trpc.health.useQuery();
    console.log(health.data);
    return (
        &lt;div&gt;
            &lt;h1&gt;Healthy&lt;/h1&gt;
        &lt;/div&gt;
    )
}
</code></pre>
<p>Final commad at root to run all<br /><code>pnpm dev</code><br /><code>pnpm build</code></p>
]]></content:encoded></item><item><title><![CDATA[Template Literals in JavaScript]]></title><description><![CDATA[Template Literals is the Javascript Syntax to handle the statement like when we have string with some of var or value included. so we can fix it through this syntax (``).
let name = "Jags";
const mess]]></description><link>https://blog.dubeyjags.cloud/template-literals-in-javascript</link><guid isPermaLink="true">https://blog.dubeyjags.cloud/template-literals-in-javascript</guid><dc:creator><![CDATA[Jags Dubey]]></dc:creator><pubDate>Fri, 19 Jun 2026 16:09:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/678bc495afaa8987c0850d21/709fab42-e0e0-4702-8ff1-75e94947c879.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Template Literals is the Javascript Syntax to handle the statement like when we have string with some of var or value included. so we can fix it through this syntax (``).</p>
<pre><code class="language-javascript">let name = "Jags";
const message = `my name is ${name}` // my name is Jags
console.log(message)
</code></pre>
<h3>We can use numbers too</h3>
<pre><code class="language-javascript">let age = 35;
const message = `my age is ${age}` 
console.log(message) // my age is 35
</code></pre>
<h3>Its shows line break as implementation</h3>
<pre><code class="language-javascript">let place = "noida"
const message = `I live in ${place}
its is in the UP India.`
console.log(message)
//I live in noida
//its is in the UP India.
</code></pre>
<h3>Also can perform calculations</h3>
<pre><code class="language-javascript">const message = `do you know 85 * 76 = ${85 * 76}`
console.log(message) //do you know 85 * 76 = 6460
</code></pre>
<h3>Summary</h3>
<p>Template Literals helps the developer to reduce the syntex in coding to show the value is the string.</p>
]]></content:encoded></item><item><title><![CDATA[Array Flatten in JavaScript]]></title><description><![CDATA[Array can store all data types of value like, String, number, boolean, object and Array too. yes Arary can store another array in the single value in it. so,

If Array has values of another Arrays so ]]></description><link>https://blog.dubeyjags.cloud/array-flatten-in-javascript</link><guid isPermaLink="true">https://blog.dubeyjags.cloud/array-flatten-in-javascript</guid><category><![CDATA[js]]></category><category><![CDATA[array]]></category><category><![CDATA[array methods]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Jags Dubey]]></dc:creator><pubDate>Fri, 08 May 2026 16:30:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/678bc495afaa8987c0850d21/85974580-1364-4700-8d4c-f394d7515252.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Array can store all data types of value like, String, number, boolean, object and Array too. yes Arary can store another array in the single value in it. so,</p>
<blockquote>
<p>If Array has values of another Arrays so we call it Nested Arrays</p>
</blockquote>
<pre><code class="language-javascript">let numbers = [1, 2, [3, 4], [5, 6]];
</code></pre>
<ul>
<li><p>Main array contains normal values</p>
</li>
<li><p>It also contains smaller arrays inside it</p>
</li>
</ul>
<h2>Nested arrays are common in:</h2>
<ul>
<li><p>API responses</p>
</li>
<li><p>Menu structures</p>
</li>
<li><p>Categories/subcategories</p>
</li>
<li><p>Matrix data</p>
</li>
<li><p>Tree-like structures</p>
</li>
</ul>
<blockquote>
<p><code>Sometimes we need all values in one simple array.</code></p>
</blockquote>
<pre><code class="language-js">[1, [2, 3], [4, 5]] // nested arrays
[1, 2, 3, 4, 5] // flatten arrays
</code></pre>
<h2>Flatten Arrays</h2>
<blockquote>
<p>Flattening converts a nested structure into a single flat list</p>
</blockquote>
<h2>Approches to convert nested to flatten arrays</h2>
<h3>1) Using .flat() (modern js)</h3>
<pre><code class="language-js">let arr = [1, 2, [3, 4], [5, 6]]; //nested array 
let result = arr.flat(); // flatten and store on another var
console.log(result); //[1, 2, 3, 4, 5, 6]
</code></pre>
<p><code>.flat() Flatten all levels of arrays</code></p>
<h3>2) Using Loops</h3>
<pre><code class="language-js">let arr = [1, 2, [3, 4]];
let result = [];

for (let i = 0; i &lt; arr.length; i++) {
  if (Array.isArray(arr[i])) {
    result = result.concat(arr[i]);
  } else {
    result.push(arr[i]);
  }
}

console.log(result);
</code></pre>
<p>When flattening arrays:</p>
<ul>
<li><p>Check each item</p>
</li>
<li><p>If normal value → add directly</p>
</li>
<li><p>If array → take values out</p>
</li>
<li><p>Repeat until fully flat</p>
</li>
</ul>
<h3>3) Using Recursion</h3>
<pre><code class="language-js">function flatten(arr) {
  let result = [];

  for (let item of arr) {
    if (Array.isArray(item)) {
      result = result.concat(flatten(item));
    } else {
      result.push(item);
    }
  }

  return result;
}

console.log(flatten([1, [2, [3, 4]]]));
</code></pre>
<table>
<thead>
<tr>
<th>Method</th>
<th>Best For</th>
</tr>
</thead>
<tbody><tr>
<td><code>flat()</code></td>
<td>Simple and modern</td>
</tr>
<tr>
<td>Loop + concat</td>
<td>Beginner understanding</td>
</tr>
<tr>
<td>Recursion</td>
<td>Interviews and deep nesting</td>
</tr>
</tbody></table>
<h2>Summary</h2>
<p>Nested arrays = arrays inside arrays<br />Flattening = converting into one simple array<br />Use .flat() for easy cases<br />Learn recursion<br />Always think step-by-step while solving</p>
<p><a href="https://dubeyjags.hashnode.dev/javascript-arrays-101">Array Basics</a></p>
]]></content:encoded></item><item><title><![CDATA[Array Methods You Must Know]]></title><description><![CDATA[Arrays become really powerful when we use array methods. like:

add/remove items

transform data

filter values

calculate totals

loop through arrays easily


So lets start to deep dive into Array
Ar]]></description><link>https://blog.dubeyjags.cloud/array-methods-you-must-know</link><guid isPermaLink="true">https://blog.dubeyjags.cloud/array-methods-you-must-know</guid><category><![CDATA[array]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[array methods]]></category><dc:creator><![CDATA[Jags Dubey]]></dc:creator><pubDate>Fri, 08 May 2026 16:29:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/678bc495afaa8987c0850d21/d5bda8fa-4594-46e5-97bd-5ecc681bca2e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Arrays become really powerful when we use <strong>array methods</strong>. like:</p>
<ul>
<li><p>add/remove items</p>
</li>
<li><p>transform data</p>
</li>
<li><p>filter values</p>
</li>
<li><p>calculate totals</p>
</li>
<li><p>loop through arrays easily</p>
</li>
</ul>
<p>So lets start to deep dive into Array</p>
<h2>Array Property <code>.length</code></h2>
<pre><code class="language-javascript">let bus = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]

console.log(bus.length)// 13 count the items of the array 
</code></pre>
<h2>Lets discuss about the Arrays methods</h2>
<h3>.at() and .indexOf are used to the passenger</h3>
<pre><code class="language-javascript">let friends= ["driver","hitesh","piyush","anirudh","JD"]

console.log(friends.at(2)) //piyush 
//provide the 2nd item (start with 0) 

console.log(friends.indexOf("JD")) //4 
// provide position of item
</code></pre>
<h2><strong>.fill() and .concat()</strong></h2>
<pre><code class="language-javascript">let friends= ["driver","hitesh","piyush","anirudh","JD"]

// .fill() used for update all value at once
friends.fill(1) // [1,1,1,1,1]

//.concat() used for add another array value in an array
let fruits =["mango","apple"]

friends.concat(fruits) 
// ["driver","hitesh","piyush","anirudh","JD""mango","apple"]
</code></pre>
<h2><strong>.push() and .pop()</strong></h2>
<blockquote>
<p>add and remove items at ends of the array(list)</p>
</blockquote>
<pre><code class="language-javascript">let friends= ["driver","hitesh","piyush","anirudh","JD"]

console.log(friends.push('another'))// add the last like
//["driver","hitesh","piyush","anirudh","JD","another"]

console.log(friends.pop('another'))// remove from the last like
//["driver","hitesh","piyush","anirudh","JD"]
</code></pre>
<h3><strong>.unshift() and .shift()</strong></h3>
<blockquote>
<p>add and remove items at the start of the array(list)</p>
</blockquote>
<pre><code class="language-javascript">let queue = ["Anu", "Ravi"];

queue.unshift("Priya");   // add to front
console.log(queue);       // ["Priya", "Anu", "Ravi"]

const first = queue.shift();   // remove from front
console.log(first);        // "Priya"
console.log(queue);        // ["Anu", "Ravi"]
</code></pre>
<h2><strong>.find(), .some(), .every(), .includes(), and .filter()</strong></h2>
<blockquote>
<p>checking for values like:</p>
</blockquote>
<ul>
<li><p>.find() // check for any lady passenger by name</p>
</li>
<li><p>.some() // check for any lady passenger by boolean</p>
</li>
<li><p>.every() // check for all passenger is women</p>
</li>
<li><p>.filter() // give me the ladies passenger list</p>
</li>
</ul>
<pre><code class="language-javascript">const passengers = [
{ name: 'Driver', gender: "M", ticket: false },
{ name: 'Conductor', gender: "M", ticket: false },
{ name: 'Divya', gender: "F", ticket: true },
{ name: 'Kavya', gender: "F", ticket: true },
{ name: 'Sandya', gender: "F", ticket: true },
{ name: 'Vandya', gender: "F", ticket: true },
{ name: 'Hitesh', gender: "M", ticket: true },
{ name: 'Piyush', gender: "M", ticket: true },
{ name: 'Anirudh', gender: "M", ticket: false },
{ name: 'Jagdamba', gender: "M", ticket: true },
{ name: 'Dubey', gender: "M", ticket: true }
];

const arrFind = passengers.find(item =&gt; item.gender==="F");
console.log('arrFind ', arrFind ) 
// return the Divya details first F gender passenger

const arrSome = passengers.some(item =&gt; item.gender==="F"); 
console.log('arrSome ', arrSome )
// return TRUE bacause of some passengers gender are F

const arrEvery = passengers.every(item =&gt; item.gender==="F"); 
console.log('arrEvery ', arrEvery )
// return FALSE because not every passengers gender is F

const arrInclude = passengers.includes(item =&gt; item.gender==="F"); 
console.log('arrInclude ', arrInclude )
// return FALSE because not every passengers gender is F

const arrFilter = passengers.filter(item =&gt; item.ticket === false); 
console.log('arrFilter ', arrFilter )
// return list of ticket false list
</code></pre>
<h3>.includes()</h3>
<blockquote>
<p>check for value incluedes</p>
</blockquote>
<pre><code class="language-javascript">
const names = ["Divya", "Kavya", "Hitesh"];
const arrInclude = names.includes("Divya");
console.log('arrInclude', arrInclude); //true
</code></pre>
<h3><strong>.map(), .flat() and .flatMap()</strong></h3>
<pre><code class="language-javascript">//.map(): used for any performance with each element
gents = ["Hitesh","Piyush","Jagdamba","Dubey"]
const isFriend = gents.map((f, i)=&gt; f+" is my freind");
console.log(isFriend)
// ['Hitesh is my freind', 'Piyush is my freind', 'Jagdamba is my freind', 'Dubey is my freind']

//.flat(): used for combining multiple arrays into a single array
staff = ["dirver", "conductor"]
ladies = ["Divya","Kavya","Sita","Geeta"]
const newArr = [staff , ladies ].flat(); // merge arrays
console.log(newArr ); 
//(6) ['dirver', 'conductor', 'Divya', 'Kavya', 'Sita', 'Geeta']

// .flatMap compbined all values
const bus = [staff, ladies, gents].flatMap(p =&gt; p + ' in the bus'); 
console.log(bus);
//  ['dirver,conductor in the bus', 'Divya,Kavya,Sita,Geeta in the bus', 'Hitesh,Piyush,Jagdamba,Dubey in the bus']
</code></pre>
<h2><strong>.split() and .join()</strong></h2>
<pre><code class="language-javascript">let myFriends = "Hitesh,Piyush,Jagdamba,Dubey"
//.split(',') create array with diffence of given value
const friendArr = myFriends.split(',')
console.log(friendArr) //['Hitesh', 'Piyush', 'Jagdamba', 'Dubey']

// .join() create string from arrays
const names = frinedArr.join(',')
console.log(names) // 'Hitesh,Piyush,Jagdamba,Dubey'
</code></pre>
<h3><strong>.slice()</strong></h3>
<blockquote>
<p>.slice() does not modified original array</p>
</blockquote>
<pre><code class="language-javascript">let bus = ["Hitesh","Piyush","Jags","Students"]
const sliceBus = bus.slice(2)
console.log(bus) // ['Hitesh', 'Piyush', 'Jags', 'Students']
console.log(sliceBus)  // ['Jags', 'Students']
</code></pre>
<h3><strong>.splice()</strong></h3>
<blockquote>
<p>.splice() update the original array and credendial</p>
</blockquote>
<pre><code class="language-javascript">let bus = ["Hitesh","Piyush","Jags","Students"]
const sliceBus = bus.splice(2)
console.log(bus) // ['Hitesh', 'Piyush']
console.log(sliceBus)  // ['Jags', 'Students']
</code></pre>
<h3></h3>
<p><strong>.reduce()</strong></p>
<blockquote>
<p>.reduce() is used for some calculations with all elements. like the total collection of bus tickets.</p>
</blockquote>
<pre><code class="language-javascript">let ticketSold = [10,15,20,30,40,50,5];
let totalSold = ticketSold.reduce((total,perticket) =&gt; total + perticket,0); //returns 170
</code></pre>
<h2>Surprise ... (create your own methods)</h2>
<pre><code class="language-javascript">Array.prototype.ticketDone = function(mes){ 
let pList = []; 
for(let i = 0; i &lt; this.length; i++){ 
    pList.push(mes(this[i])); 
} 
return pList; 
}

let bus = ["p1","p2","p3","p4","p5","p6","p7","p8"]
bus.ticketDone(pas =&gt; pas + " ticket kat gaya");
// ['p1 ticket kat gaya', 'p2 ticket kat gaya', 'p3 ticket kat gaya', 'p4 ticket kat gaya', 'p5 ticket kat gaya', 'p6 ticket kat gaya', 'p7 ticket kat gaya', 'p8 ticket kat gaya']
</code></pre>
<h2>Summary</h2>
<p>Now code summary is code try to better understand this.</p>
<pre><code class="language-javascript">const myArr = [1,2,3,4,5.5] myArr.length() 
// returns the array length ( count of items the array is 5)
myArr.at(n) 
// get the value of nth position ( 4th position value is 5.5)
myArr.indexOf(4) 
// get the position of value (5 is at 4th position)
myArr.concat(4,[45,56,76,86]) 
// add more value into the array (also can be single value or can be another array itself)
myArr.fill(0); 
// fill all the position with passed value
myArr.find((item) =&gt; item &lt; 7) 
// check for the first item to match the condition
myArr.some((item) =&gt; item &lt; 7) 
// check for the some item to match the condition
myArr.every((item) =&gt; item &lt; 7) 
// check for all items to match the contions with iterations with true and false
myArr.includes(item); 
// return booleans if item avilable or not in the array
myArr.filter((item) =&gt; item &gt;4) 
// return the list of the array with matched the conditions m
myArr.map(item =&gt; item * 2) 
// return the new array with any actions performed with each elements
myArr.flat(); 
// convert in the single array from multilevel array
myArr.flatMap(item =&gt; item + "a") 
// maping and also flat the array if there is multilevel array
myArr.join('-') 
// return string with all value differnciate with mentioned value
myArr.split('-') 
// return array with split value myArr.push(7) // add new item in the last of the array myArr.pop // removed and returns the last item of the array
myArr.unshift(0) 
// add new item or items in the start of array
myArr.shift() 
// removed first item from array
myArr.splice(start, count) 
// returns removed form old array and return the new array from start to number of counts
myArr.slice(count) 
// just slice removed or sliced from start to count
arr.reduce((total,item) =&gt; total+item,intial) 
// return the sum of the array with intial if added
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Understanding Objects in JavaScript]]></title><description><![CDATA[Object are the collection of uncategoried data which can be stored in the variable. Collection of values in key value pair or we can say that complex data can store in the object make code more readab]]></description><link>https://blog.dubeyjags.cloud/understanding-objects-in-javascript</link><guid isPermaLink="true">https://blog.dubeyjags.cloud/understanding-objects-in-javascript</guid><category><![CDATA[js]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Objects]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Jags Dubey]]></dc:creator><pubDate>Mon, 04 May 2026 17:21:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/678bc495afaa8987c0850d21/5634512a-5cc9-4056-b8f0-93923fe21e92.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Object are the collection of uncategoried data which can be stored in the variable. Collection of values in key value pair or we can say that complex data can store in the object make code more readable and organized. like and value can be every type of data.</p>
<blockquote>
<p>collection of value with their labels can store in the variables</p>
</blockquote>
<pre><code class="language-javascript">let person = {
  name: "JD",      // key: "name",  value: "Aryan"
  age:  36,          // key: "age",   value: 22
  city: "Noida",     // key: "city",  value: "Delhi"
  isStudent: true   // values can be any type
};
</code></pre>
<h3>Access values/properties</h3>
<blockquote>
<p>2 ways of access value (dot and bracket notations)</p>
</blockquote>
<pre><code class="language-javascript">let person = {
  name: "JD",      // key: "name",  value: "Aryan"
  age:  36,          // key: "age",   value: 22
  city: "Noida",     // key: "city",  value: "Delhi"
  isStudent: true   // values can be any type
};

// Access value through dot notations
console.log(person.name) // JD

// Access value through Bracket notations
console.log(person[age]) // 36

// both ways can access the any type of values
</code></pre>
<h3>Updating Values</h3>
<pre><code class="language-javascript">let person = {
  name: "JD",      // key: "name",  value: "Aryan"
  age:  36,          // key: "age",   value: 22
  city: "Noida",     // key: "city",  value: "Delhi"
  isStudent: true   // values can be any type
};

console.log(person.city) // Noida

person.city = "Delhi"

console.log(person.city) // Delhi
</code></pre>
<blockquote>
<p>we can update values through both dot and bracket notations</p>
</blockquote>
<h2>Adding &amp; Deleting Properties</h2>
<pre><code class="language-javascript">let person = {
  name: "JD",      // key: "name",  value: "Aryan"
  age:  36,          // key: "age",   value: 22
  city: "Noida",     // key: "city",  value: "Delhi"
  isStudent: true   // values can be any type
};

person.email = "name@example.com"

console.log(person) 
//{name: 'JD', age: 36, city: 'Noida', isStudent: true, email: 'name@example.com'}

delete person.age
console.log(person) 
//{name: 'JD', city: 'Noida', isStudent: true, email: 'name@example.com'}
</code></pre>
<blockquote>
<p><code>delete</code> can help you to remove key and value</p>
</blockquote>
<blockquote>
<p>we can add values through both dot and bracket notations</p>
</blockquote>
<h3>Loop for Object</h3>
<p><code>for... in</code> loop can be used for object key and values like:</p>
<pre><code class="language-javascript">let person = {
  name: "JD",      // key: "name",  value: "Aryan"
  age:  36,          // key: "age",   value: 22
  city: "Noida",     // key: "city",  value: "Delhi"
  isStudent: true   // values can be any type
};

for (let key in person){
    console.log(key, " value is ", person[key])
}

// name  value is  JD
// age  value is  36
// city  value is  Noida
// isStudent  value is  true
</code></pre>
<h3>Object vs Array</h3>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Object</th>
<th>Array</th>
</tr>
</thead>
<tbody><tr>
<td>Structure</td>
<td>key-value</td>
<td>indexed list</td>
</tr>
<tr>
<td>Access, add and update values</td>
<td><code>obj.key</code></td>
<td><code>arr[0]</code></td>
</tr>
<tr>
<td>Use</td>
<td>real-world entities</td>
<td>lists of items</td>
</tr>
<tr>
<td>loop</td>
<td>for...in</td>
<td>for.. of</td>
</tr>
</tbody></table>
<h3>Summary</h3>
<p>An object is a collection of related data and/or functionality. Unlike an array, which is an ordered list, an object is a structure where you give every piece of data a "label" (the <strong>key</strong>) so you can find it easily.</p>
<ul>
<li><p>Objects store <strong>related data together</strong></p>
</li>
<li><p>Use <strong>dot notation</strong> for simple access</p>
</li>
<li><p>Use <strong>bracket notation</strong> for dynamic keys</p>
</li>
<li><p>Use <code>for...in</code> to loop through properties</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[JavaScript Arrays 101]]></title><description><![CDATA[Array is the group of values to store in single variable, till now we store single value in the variable, but what if we have group of values like fruits or friends,
Simple variables
let friend1 = "Hi]]></description><link>https://blog.dubeyjags.cloud/javascript-arrays-101</link><guid isPermaLink="true">https://blog.dubeyjags.cloud/javascript-arrays-101</guid><category><![CDATA[array]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Loops]]></category><dc:creator><![CDATA[Jags Dubey]]></dc:creator><pubDate>Mon, 04 May 2026 15:58:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/678bc495afaa8987c0850d21/378c6566-b0ca-46c2-b1ab-855f4f429acb.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Array is the group of values to store in single variable, till now we store single value in the variable, but what if we have group of values like fruits or friends,</p>
<p>Simple variables</p>
<pre><code class="language-javascript">let friend1 = "Hitesh"
let friend2 = "Piyush"
let friend3 = "Anirudh"
let friend4 = "Jai"
let friend5 = "Jags"
</code></pre>
<p>But with Arrays</p>
<pre><code class="language-javascript">let friends = ["Hitesh","Piyush","Anirudh","Jai","Jags"]
// single group of collections of the list
</code></pre>
<h3>Accessing Elements</h3>
<p>with index we can acces the values like:</p>
<blockquote>
<p>Index starts with 0</p>
</blockquote>
<pre><code class="language-javascript">// index           0       1        2        3      4
let friends = ["Hitesh","Piyush","Anirudh","Jai","Jags"]

//print values (Access values)

console.log(friends[0]) // Hitesh
console.log(friends[2]) // Anirudh
</code></pre>
<h3>Updating values</h3>
<p>yes, we can update values from the list like:</p>
<pre><code class="language-javascript">let friends = ["Hitesh","Piyush","Anirudh","Jai","Jags"]

friends[2] = "Big Boss"

//now array will be
console.log(friends) 
// ['Hitesh', 'Piyush', 'Big Boss', 'Jai', 'Jags']
</code></pre>
<h3>Array Length (count value of the arrays)</h3>
<pre><code class="language-javascript">let friends = ["Hitesh","Piyush","Anirudh","Jai","Jags"]
// count the values of the arrays
console.log(friends.length) // 5
</code></pre>
<h2>Looping Over Arrays</h2>
<p>If you want do some action or any calculation use <code>for of</code> loop</p>
<pre><code class="language-javascript">let friends = ["Hitesh","Piyush","Anirudh","Jai","Jags"]
// count the values of the arrays
for (let friend of friends ) {
  console.log(friend + ' is my Friend');
}
// Hitesh is my Friend
// Piyush is my Friend
// Anirudh is my Friend
// Jai is my Friend
// Jags is my Friend
</code></pre>
<h3>Summary</h3>
<p>Array is the collection of values in a variable. it could be <code>string</code>, <code>number,</code> <code>boolean</code> all of the values can be</p>
<ul>
<li><p>we can create array with <code>[]</code></p>
</li>
<li><p>Array can acccess with <code>index</code> like <code>myArray[index]</code></p>
</li>
<li><p>Array can be updated with index and assgin value like <code>myArray[index] = newvalue</code></p>
</li>
<li><p>Array can loop with <code>for of</code> loop</p>
</li>
</ul>
<pre><code class="language-javascript">let movies = ["Movie1", "Movie2", "Movie3", "Movie4", "Movie5"];

console.log(movies[0]); // Movie1

movies[2] = "Movie2";

for (movie of movies) {
  console.log(movie);
}
</code></pre>
<h3></h3>
]]></content:encoded></item><item><title><![CDATA[JavaScript : Function Declaration vs Function Expression]]></title><description><![CDATA[Lets understand function as var can store the value same as function store the single or multiple line of code which we can use where we need.

Instead of writing the same code again and again, you wr]]></description><link>https://blog.dubeyjags.cloud/javascript-function-declaration-vs-function-expression</link><guid isPermaLink="true">https://blog.dubeyjags.cloud/javascript-function-declaration-vs-function-expression</guid><category><![CDATA[js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[functions]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[function]]></category><dc:creator><![CDATA[Jags Dubey]]></dc:creator><pubDate>Sun, 03 May 2026 10:41:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/678bc495afaa8987c0850d21/d3e3dbe4-7e7f-4bad-ae47-57f5c5309630.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Lets understand <code>function</code> as var can store the value same as function store the single or multiple line of code which we can use where we need.</p>
<blockquote>
<p>Instead of writing the same code again and again, you wrap it inside a function and call it whenever needed.</p>
</blockquote>
<p>like:</p>
<pre><code class="language-javascript">function add(a, b) {// syntax for creating function with vars 
  return a + b; // now code for adding 2 numbers
}
// now we call function with values which we need to perform action
console.log(add(2, 3)); // 5
// add is function and 2,3 are the values of 'a' and 'b' which functions required
</code></pre>
<p>as we see above this is f<code>unction declaration</code>,</p>
<h3>Function Type</h3>
<ul>
<li><p>function declartion</p>
</li>
<li><p>function expression</p>
</li>
</ul>
<pre><code class="language-javascript">//function declation as we already seen lets discuss both again
// Function Declaration
function add(a, b) {
  return a + b;
}

// Function Expression just same as above but it store in var
const addExp = function(a, b) {
  return a + b;
};

console.log(add(2, 3));     // 5 // calling way is the same 
console.log(addExp(2, 3));  // 5 // for function declation and expression
</code></pre>
<h3>Hoisting</h3>
<p>hosting is the issue when fuction call before creation.</p>
<ul>
<li><p><code>function declaration</code> never create this issue</p>
</li>
<li><p><code>function expression</code> has the issue of hoisting because it store it the variable</p>
</li>
</ul>
<pre><code class="language-javascript">console.log(multiply(2, 5)); // ✅ works

console.log(multiplyExp(2, 5)); // ❌ error

function multiply(a, b) {
  return a * b;
}

const multiplyExp = function(a, b) {
  return a * b;
};
// both works here
console.log(multiply(2, 5)); // ✅ works

console.log(multiplyExp(2, 5)); //✅ works
</code></pre>
<blockquote>
<p>Hoisting means JavaScript <strong>moves declarations to the top</strong></p>
</blockquote>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Function Declaration</th>
<th>Function Expression</th>
</tr>
</thead>
<tbody><tr>
<td>Syntax</td>
<td><code>function name()</code></td>
<td><code>const name = function()</code></td>
</tr>
<tr>
<td>Hoisting</td>
<td>✅ Yes</td>
<td>❌ No</td>
</tr>
<tr>
<td>Use Before Definition</td>
<td>✅ Works</td>
<td>❌ Error</td>
</tr>
</tbody></table>
<h3>Summary</h3>
<p>Functions is block of code which can process the different values which can be used in multple places which different values.</p>
<h3>Use Function Declaration:</h3>
<ul>
<li><p>When you want to define reusable functions early</p>
</li>
<li><p>When you may call it before writing it</p>
</li>
<li><p>simple, hoisted, beginner-friendly</p>
</li>
</ul>
<h3>Use Function Expression:</h3>
<ul>
<li><p>When assigning functions to variables</p>
</li>
<li><p>When using functions as values (common in modern JS)</p>
</li>
<li><p>flexible, used more in modern JavaScript</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[JavaScript Operators: The Basics You Need to Know]]></title><description><![CDATA[Operators in JS is the tool to play with values. like if you want to do some actions or calucations with values the js provides the Opertors like +,=,x ,/ and some more Basic opertaions like:
Arithmet]]></description><link>https://blog.dubeyjags.cloud/javascript-operators-the-basics-you-need-to-know</link><guid isPermaLink="true">https://blog.dubeyjags.cloud/javascript-operators-the-basics-you-need-to-know</guid><category><![CDATA[js]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Operators]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[calculation]]></category><dc:creator><![CDATA[Jags Dubey]]></dc:creator><pubDate>Sat, 02 May 2026 12:02:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/678bc495afaa8987c0850d21/c14996ec-a081-49e1-aac6-82c305d29548.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Operators in JS is the tool to play with values. like if you want to do some actions or calucations with values the js provides the Opertors like +,=,x ,/ and some more Basic opertaions like:</p>
<h3>Arithmetic Operations for Calculations</h3>
<pre><code class="language-javascript">let a = 10;
let b = 3;

console.log(a + b); // 13 (addition)
console.log(a - b); // 7  (subtraction)
console.log(a * b); // 30 (multiplication)
console.log(a / b); // 3.33 (division)
console.log(a % b); // 1 (remainder)
</code></pre>
<h3>Assignment Opertations</h3>
<p>Used to assign or update values like:</p>
<pre><code class="language-javascript">let num = 10; // Assigining the values
// if we use  Arithmetic  then we can update assigned values
num += 5; // num = num + 5 → 15
num -= 3; // num = num - 3 → 12
</code></pre>
<h3>Comparion Operations</h3>
<p>this is intersting things let discuss</p>
<pre><code class="language-javascript">// like as earlier discussed
let a = 5 // single '='  is used for assign the value
let b = '5' // assigning number as string right?

// now '==' is used to compare the values
console.log(a == b) // true

// also '===' is used for compare value and its type
console.log(a ===b) // false because its number and string 
</code></pre>
<blockquote>
<p>Let know some more things</p>
</blockquote>
<pre><code class="language-javascript">let a = 5
let b = 10
// '&lt;' '&gt;' '!'
console.log(a &gt; b) // false "is a is greater then b"
console.log(a &lt; b) // true "is a is let then b"
console.log(a != b) // false "check for not eqal"
// ! is used for false or not.
</code></pre>
<h3>Logical Opertaions</h3>
<p>let go for more deeper for comparing values with combined coditions. Just Remember :</p>
<ul>
<li><p><code>&amp;&amp;</code> is used <strong>AND</strong> conditions</p>
</li>
<li><p><code>||</code> is used for <strong>OR</strong> condtions</p>
</li>
<li><p><code>!</code> is used to check the not or falsy values</p>
</li>
</ul>
<pre><code class="language-javascript">let age = 20;

console.log(age &gt; 18 &amp;&amp; age &lt; 30); // true
console.log(age &lt; 18 || age &gt; 15); // true
console.log(!(age &gt; 18)); // false
// go slow and revise it. there is 2 condtions which compared so 
//"&amp;&amp;" is used to check the both condtion is true and 
// "||" is used for to check at least 1 condition the true 
// "!" is checkign condition is false and it make opposite whatever condition is.
</code></pre>
<p>| A | B | A &amp;&amp; B | A || B | ! for A |
| --- | --- | --- | --- | --- |
| true | true | true | true | false |
| true | false | false | true | false |
| false | true | false | true | true |
| false | false | false | false | true |</p>
<h3>Summary</h3>
<p>JS is tools to play with data with some operators like</p>
<ul>
<li><p>Use <code>+ - * / %</code> for math</p>
</li>
<li><p>Use <code>===</code> instead of <code>==</code></p>
</li>
<li><p>Use <code>&amp;&amp;</code> and <code>||</code> for combining conditions</p>
</li>
<li><p>Use <code>+=</code>, <code>-=</code> for cleaner updates</p>
</li>
<li><p>AND (<code>&amp;&amp;</code>) → strict (needs both true)</p>
</li>
<li><p>OR (<code>||</code>) → flexible (needs one true)</p>
</li>
<li><p>NOT (<code>!</code>) → reverses result</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Control Flow in JavaScript: If, Else, and Switch]]></title><description><![CDATA[Everything is not availale for everyone.
Control Flow: The order in which code runs based on the conditions.Instead of code run all line by line it has to ignore some lines through some coditions.
Use]]></description><link>https://blog.dubeyjags.cloud/control-flow-in-javascript-if-else-and-switch</link><guid isPermaLink="true">https://blog.dubeyjags.cloud/control-flow-in-javascript-if-else-and-switch</guid><category><![CDATA[control flow]]></category><category><![CDATA[js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[if-else]]></category><category><![CDATA[SWITCH]]></category><dc:creator><![CDATA[Jags Dubey]]></dc:creator><pubDate>Sat, 02 May 2026 04:41:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/678bc495afaa8987c0850d21/c3da44f3-2e80-43d7-963e-7e60182038e1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><code>Everything is not availale for everyone.</code></p>
<p>Control Flow: The order in which code runs based on the conditions.<br />Instead of code run all line by line it has to ignore some lines through some coditions.</p>
<h3>Use <code>if</code> conditions</h3>
<pre><code class="language-javascript">let marks = 40

if(marks &gt; 33){ // if with condtion of 33 value
    console.log('you are passed') // condtion true then run
}
// console.log (print) will only run if condtion match the values
</code></pre>
<h3>Handle the other conditions</h3>
<pre><code class="language-javascript">let marks = 40

if(marks &gt; 33){ 
    console.log('you are passed')
} else {
    console.log('you are failed') //here is the others condition 
}
// In this code. console.log(print) statement will run. 
</code></pre>
<blockquote>
<p>now we execute the condition with <code>if</code> and <code>else</code> one condition will run always</p>
</blockquote>
<h3>Lets add more conditions to discuss like</h3>
<pre><code class="language-javascript">let marks = 40

if(marks &gt; 33){ 
    console.log('you are passed')
if (marks &gt; 90){ // add more condition with another values
    console.log('Got Grade A') 
if (marks &gt; 75){ // add more condition with another values
    console.log('Got Grade B') 
} else {
    console.log('you are failed') 
}
</code></pre>
<blockquote>
<p>runs code by checking conditions one by one and print the statement as per condition</p>
</blockquote>
<h2>Switch Statement</h2>
<p>Used when you compare <strong>one value with many options</strong></p>
<pre><code class="language-javascript">let day = 2;

switch (day) {            // difines variables 
  case 1:                 // case used for match the values 
    console.log("Monday");// if true then print 
    break;                // done and skip next (flow break)
  case 2:                     // previous not match 
    console.log("Tuesday");   // what need to be done
    break;                    // if match the end it
  case 3:
    console.log("Wednesday");
    break;
  case 4:
    console.log("Thursday");
    break;
  case 5:
    console.log("Friday");
    break;
  case 6:
    console.log("Saturday");
    break;
  case 7:
    console.log("Sunday");
    break; 
  default:                 // if none of condition matched 
    console.log("Invalid day");// run this code 
}
</code></pre>
<blockquote>
<p>We can use Switch if we have multiple conditions with fixed values</p>
</blockquote>
<h3>When to use of <code>if -else</code> or <code>switch</code></h3>
<table>
<thead>
<tr>
<th>Use Case</th>
<th>Best Choice</th>
</tr>
</thead>
<tbody><tr>
<td>Checking ranges (age &gt; 18)</td>
<td>if-else</td>
</tr>
<tr>
<td>Multiple specific values</td>
<td>switch</td>
</tr>
<tr>
<td>Complex logic</td>
<td>if-else</td>
</tr>
<tr>
<td>Clean fixed options</td>
<td>switch</td>
</tr>
</tbody></table>
<h3>Summary</h3>
<p>if we have conditions to run the code then <strong>Control flows</strong> comes in the pictures</p>
<ul>
<li><p>Use <code>if</code> → single condition</p>
</li>
<li><p>Use <code>if-else</code> → two paths</p>
</li>
<li><p>Use <code>else if</code> → multiple conditions</p>
</li>
<li><p>Use <code>switch</code> → many fixed values</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Understanding Variables and Data Types in JavaScript]]></title><description><![CDATA[On the Internet or Web Everthing is DATAVariable are the containers for the storing the data , It could be text, number, or any other information about anything. For using of the data we store in cont]]></description><link>https://blog.dubeyjags.cloud/understanding-variables-and-data-types-in-javascript</link><guid isPermaLink="true">https://blog.dubeyjags.cloud/understanding-variables-and-data-types-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[js-basic]]></category><dc:creator><![CDATA[Jags Dubey]]></dc:creator><pubDate>Sat, 02 May 2026 04:39:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/678bc495afaa8987c0850d21/9ab4ebcf-0060-4da6-b90a-7c00699abfa8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><code>On the Internet or Web Everthing is DATA</code><br />Variable are the containers for the storing the data , It could be text, number, or any other information about anything. For using of the data we store in container. Insteand of updating the details everytime or everywhere, we will use that container name at everyplaces so that if we need to update then we just update once. like</p>
<pre><code class="language-javascript">var name = "hello world";
// name is the container and hello World is the value/data
</code></pre>
<p>lets discuss about container, <code>var</code> is not the only way to assign the container, we have <code>let</code> and <code>const</code> which can also assign the container to store the values/data like:</p>
<pre><code class="language-javascript">var name = "hello world"; 
let age = 28;
const isStudent = true;
</code></pre>
<h3>Key Differnces of <code>var</code>, <code>let</code> and <code>const</code></h3>
<table>
<thead>
<tr>
<th>Features</th>
<th>var</th>
<th>let</th>
<th>const</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Scope</strong></td>
<td>Function</td>
<td>Block</td>
<td>Block</td>
</tr>
<tr>
<td><strong>Hoisting</strong></td>
<td>Hoisted <code>Initalized with undefined</code></td>
<td>Hoisted<code>temporal dead zone</code></td>
<td>Hoisted<code>temporal dead zone</code></td>
</tr>
<tr>
<td><strong>Re-declaration</strong></td>
<td>Allowed</td>
<td>Not Allowed in same Scope</td>
<td>Not Allowed in same Scope</td>
</tr>
<tr>
<td><strong>Re-assignment</strong></td>
<td>Allowed</td>
<td>Allowed</td>
<td>Not allowed</td>
</tr>
<tr>
<td><strong>Global Assignment</strong></td>
<td>Yes (window.varName)</td>
<td>No</td>
<td>No</td>
</tr>
<tr>
<td><strong>Best Use</strong></td>
<td>Avoid Using(old method)</td>
<td>When value may update</td>
<td>when value not to be updated</td>
</tr>
</tbody></table>
<h3>Data/Values could be in multiple types...</h3>
<p>Yes also we have multiple types of data. <strong>Primitive data types</strong> likes: text, number, truthy and so on...</p>
<pre><code class="language-javascript">let name = "hello JD" // 'String' for text or any other information
let age = 32 // 'number' can be data to be stored
let isWorking = true // 'boolean' is also data to be stored
let nothing = null // 'null' blank for now filled in the future
let notDefined = undefined // 'undefined' shows its not defined at
</code></pre>
<blockquote>
<p>Basic for now for better understanding...</p>
</blockquote>
<h2>Scope</h2>
<p>Scope is the area in where the can the access the container to get the values.<br />yes, we can control the container availability to be accessed</p>
<pre><code class="language-javascript">var gVar = "I am global" // called 'global scoped'
let gLet = "I am global" // can be accessed at everywhere
const gConst = "I am global"// till this file available

function outer(){ // just remember this bracket {function Scoped}
    var oVar = "I am outer (var)" // can be accessed
    let oLet = "I am outer (let)" // only inside the brackets
    const oConst = "I am outer (const)" // not accesble outside

    if(true){ // Again Brackets for area {block scoped}
        var bVar = "I am block (var)"
        let bLet = "I am block (let)"
        const bConst = "I am block (const)"
    }
}
</code></pre>
<h3>Summary</h3>
<p>As we understaind about In the web world every thing is data, so we use container (<code>var</code>,<code>let</code>,<code>coist</code>) to store. so the we have value at one place and use container name to avoid the rework at the time of value updation. Also we have some differences in between them (re-check table). And also we have multiple types of data/values to store basics for now. Scope (area of availabilty) for the container.</p>
<ul>
<li><p>use <code>let</code> if value updates</p>
</li>
<li><p>use <code>const</code> if value is fixed</p>
</li>
<li><p><code>var</code> avoid using for future code.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Fetch Requests (reuseable layer for API client services)]]></title><description><![CDATA[Service/apiClient.js (at the same level as src folder)

class ApiClient {
  constructor() {
    this.baseURL = 'http://localhost:3000/api/v1';
    this.defaultHeaders = {
      'Content-Type': 'applic]]></description><link>https://blog.dubeyjags.cloud/fetch-requests-reuseable-layer-for-api-client-services</link><guid isPermaLink="true">https://blog.dubeyjags.cloud/fetch-requests-reuseable-layer-for-api-client-services</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[ChaiCohort]]></category><dc:creator><![CDATA[Jags Dubey]]></dc:creator><pubDate>Wed, 18 Mar 2026 01:32:44 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p>Service/apiClient.js (at the same level as src folder)</p>
</blockquote>
<pre><code class="language-js">class ApiClient {
  constructor() {
    this.baseURL = 'http://localhost:3000/api/v1';
    this.defaultHeaders = {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    };
  }

  async customFetch(endpoint, options = {}) {
    try {
      const url = `\({this.baseURL}\){endpoint}`;
      const response = await fetch(url, {
        ...options,
        headers: { ...this.defaultHeaders, ...options.headers },
        credentials: 'include',  // Send Cookies
        // 'include' on Same-origin + cross-origin 
        // default 'same-origin' and 
        // use 'omit' for public apis
      });
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return await response.json();
    } catch (e) {
      console.log('API Error:', e);
    }
  }

  signup(name, email, password) {
    return this.customFetch('/user/signup', {
      method: 'POST',
      body: JSON.stringify({ name, email, password }),
    });
  }
}
const apiClient = new ApiClient();
export default apiClient;
</code></pre>
<h2>uses of apiClient</h2>
<pre><code class="language-js">// Import at the top
import apiClient from './apiClient';

// GET req
try {
  const users = await apiClient.get('/users');
  console.log(users);
} catch (err) {
  console.error(err);
}

// POST req
const data = {
  email: 'test@test.com',
  password: '123456',
};
await apiClient.post('/login', data);

//PUT Req
await apiClient.put('/users/1', {
  name: 'John',
});

//Delete req
await apiClient.delete('/users/1');

// Cutom header
await apiClient.get('/users', {
  headers: {
    'x-custom-header': 'hello',
  },
});

// Query Params
const role = 'admin';
await apiClient.get(`/users?role=${role}`);
</code></pre>
<pre><code class="language-JS">// React Example
import { useEffect, useState } from 'react';
import apiClient from './apiClient';

function Users() {
  const [users, setUsers] = useState([]);

  useEffect(() =&gt; {
    const fetchUsers = async () =&gt; {
      try {
        const data = await apiClient.get('/users');
        setUsers(data);
      } catch (err) {
        console.error(err);
      }
    };

    fetchUsers();
  }, []);

  return (
    &lt;div&gt;
      {users.map(u =&gt; (
        &lt;p key={u.id}&gt;{u.name}&lt;/p&gt;
      ))}
    &lt;/div&gt;
  );
}
</code></pre>
<h2>Steps on Form Submission</h2>
<ul>
<li>Prevent default behavior of form.  </li>
<li>Show loading state.  </li>
<li>Call apiClient.signup(...) and wait for response.  </li>
<li>Handle the response (e.g., redirect on success).  </li>
<li>Catch and log any errors.</li>
</ul>
<pre><code class="language-js">const handleSubmit = async (e) =&gt; {
  e.preventDefault();
  if (!name || !email || !password) return setError('All fields required');

  setLoading(true);
  setError('');
  try {
    const data = await apiClient.signup(name, email, password);
    if (data?.success) navigate('/login');
    else setError(data?.message || 'Signup failed');
  } catch (e) {
    setError('Error occurred');
  } finally {
    setLoading(false);
  }
};
</code></pre>
<pre><code class="language-html">{error &amp;&amp; &lt;p&gt;{error}&lt;/p&gt;}
&lt;form onSubmit={handleSubmit}&gt;
  &lt;input value={name} onChange={(e) =&gt; setName(e.target.value)} /&gt;
  &lt;input value={email} onChange={(e) =&gt; setEmail(e.target.value)} /&gt;
  &lt;input value={password} onChange={(e) =&gt; setPassword(e.target.value)} /&gt;
  &lt;button type="submit"&gt;{loading ? 'Signing up...' : 'Signup'}&lt;/button&gt;
&lt;/form&gt;
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Learned Array with Bus and Passengers..]]></title><description><![CDATA[An array is a simple group or list of basic data types (String, Number, boolean, array, and object or null and undefined ). Array items could be a single datatype of all of them ex: ["String", 4, true, ["another", "list", "of", "data"], {name:"chaiCo...]]></description><link>https://blog.dubeyjags.cloud/learned-array-with-bus-and-passengers</link><guid isPermaLink="true">https://blog.dubeyjags.cloud/learned-array-with-bus-and-passengers</guid><category><![CDATA[dubeyjags]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[array]]></category><dc:creator><![CDATA[Jags Dubey]]></dc:creator><pubDate>Fri, 14 Feb 2025 07:21:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1739516500955/36f85933-1728-4813-9c60-97e75b4c0255.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>An array is a simple group or list of basic data types (String, Number, boolean, array, and object or null and undefined ). Array items could be a single datatype of all of them ex: ["String", 4, true, ["another", "list", "of", "data"], {name:"chaiCode"}] Here we learn javascript arrays with a simple example of bus and passengers with #chaicode</p>
<h2 id="heading-length">.length</h2>
<p>.length is used to get the total element count.</p>
<p><code>let bus = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]</code><br /><code>bus.length // 13 returns the array length ( count of items the array is 5)</code></p>
<h2 id="heading-at-and-indexof">.at() and .indexOf()</h2>
<p>.at() and .indexOf are used to the passenger</p>
<p><code>let bus2 = ["driver","hitesh","piyush","anirudh","main bhi hu"]</code><br /><a target="_blank" href="http://bus2.at"><code>bus2.at</code></a><code>(3) // return anirudh it start from the 0 (doesn't include drive seat only passengers)</code><br /><code>bus.indexOf("main bhi hu") // Return 4 position of the the value and starts with 0</code></p>
<h2 id="heading-fill-and-concat">.fill() and .concat()</h2>
<p>.fill(1): Fill all the seats with 1 passenger<br />.concat(): add another bus passenger to your bus</p>
<p><code>bus3 = bus.fill(1) // update all values with 1</code><br /><code>bus3 = bus2.concat(bus) //add new array with the old array</code></p>
<h2 id="heading-push-and-pop">.push() and .pop()</h2>
<p>add and remove items at ends of the array(list)<br />.push() // board new passenger from the back gate<br />.pop() // deboard passenger from the back gate</p>
<p><code>bus4 = bus.push('gents'); // gents boarded bus from back gate</code><br /><code>bus4 = bus.pop('gents'); // after destination gents deboarded bus from back gate</code></p>
<h2 id="heading-unshift-and-shift">.unshift() and .shift()</h2>
<p>add and remove items at the start of the array(list)<br />.unshift() // boarded ladies passengers from front gate<br />.shift() // deboarded ladies passengers from front gate</p>
<h2 id="heading-find-some-every-includes-and-filter">.find(), .some(), .every(), .includes(), and .filter()</h2>
<p>some other important methods of arrays<br />.find() // check for any lady passenger by name<br />.some() // check for any lady passenger by boolean<br />.every() // check for all passenger is women<br />.include() // any lady passenger by name<br />.filter() // give me the ladies passenger list</p>
<p><code>let ticketPrize = [5,7,10,15,20,30,40,60,80]</code><br /><code>ticketPrize.find(item =&gt; item === 10) // return 10 the value if true</code><br /><code>ticketPrize.some(item =&gt; item &lt; 10) // return true beacuse of value 5 is lesser</code><br /><code>ticketPrize.every(item =&gt; item &lt; 10) // return false beacause of other value is higher</code><br /><code>ticketPrize.includes(5) // return true because 5 is in the list</code><br /><code>ticketPrize.filter(item =&gt; item &lt;= 9) // [5, 7] retrun the value</code></p>
<p><code>const passengers = [</code><br /><code>{ name: 'Driver', gender: "M", ticket: false },</code><br /><code>{ name: 'Conductor', gender: "M", ticket: false },</code><br /><code>{ name: 'Divya', gender: "F", ticket: true },</code><br /><code>{ name: 'Kavya', gender: "F", ticket: true },</code><br /><code>{ name: 'Sandya', gender: "F", ticket: true },</code><br /><code>{ name: 'Vandya', gender: "F", ticket: true },</code><br /><code>{ name: 'Hitesh', gender: "M", ticket: true },</code><br /><code>{ name: 'Piyush', gender: "M", ticket: true },</code><br /><code>{ name: 'Anirudh', gender: "M", ticket: false },</code><br /><code>{ name: 'Jagdamba', gender: "M", ticket: true },</code><br /><code>{ name: 'Dubey', gender: "M", ticket: true }</code><br /><code>];</code></p>
<p><code>passengers.find(item =&gt; item.gender==="F"); // return the Divya details first F gender passenger</code><br /><code>assengers.some(item =&gt; item.gender==="F"); // return TRUE bacause of some passengers gender are F</code><br /><code>assengers.every(item =&gt; item.gender==="F"); // return FALSE because not every passengers gender is F</code><br /><code>assengers.filter(item =&gt; item.ticket === false); return list of ticket false list</code></p>
<h2 id="heading-map-flat-and-flatmap">.map(), .flat() and .flatMap()</h2>
<p>.map(): used for any performance with each element</p>
<p>ticketPrize = [5,7,10,15,20,30,40,60,80] dobledPrize = <a target="_blank" href="http://ticketPrize.map">ticketPrize.map</a>(prize =&gt; prize * 2) // new array with doubled prize</p>
<p>.flat(): used for combining multiple arrays into a single array<br /><code>staff = ["dirver", "conductor"]</code><br /><code>ladies = ["Divya","Kavya","Sita","Geeta"]</code><br /><code>gents = ["Hitesh","Piyush","Jagdamba","Dubey"]</code><br /><code>bus = [staff, ladies, gents].flat(); // get all value in one</code></p>
<p>bus = [staff, ladies, gents].flatMap(p =&gt; p + ' in the bus'); // get all value in one</p>
<h2 id="heading-split-and-join">.split() and .join()</h2>
<p>.split() used for creating array<br />let myFriends = "Hitesh,Piyush,Jagdamba,Dubey"<br /><code>frinedArr = myFriends.split(','); // create element on the based of ,</code><br />.join() is used for array to string<br /><code>names = frinedArr.join(',') // array convert back to string</code></p>
<h2 id="heading-slice-and-splice">.slice() and .splice()</h2>
<p>.slice()</p>
<p>this is used to slice the list bus Doesn't modify the original array and returns a new array with selected elements like: ticket done for some passenger some are pending but all are in the bus<br /><code>let bus7 = ["driver","conductor","Hitesh","Piyush","Jags","Students"]</code><br /><code>bus7.slice(2) // first 2 dirver and conductor does not require tickets</code><br /><code>bus7.slice(2,5) // first 2 and after and after 5 (dirver and conductor and stundents and so not required)</code></p>
<p>.splice()</p>
<p>Modifies the original array and returns removed elements like: some of the passengers deboarded the bus but some still in the bus<br /><code>let bus8 = ["driver","conductor","Hitesh","Piyush","Jags","Students"]</code><br /><code>busSplice = bus8.splice(2) // store only passengers and bus8 has only dirver and conductor</code><br /><code>busSplice = bus8.splice(2,3) // first value start from and second value count of delete/splice</code></p>
<h2 id="heading-reduce">.reduce()</h2>
<p>reduce is used for some calculations with all elements. like the total collection of bus tickets.<br /><code>let ticketSold = [10,15,20,30,40,50,5];</code><br /><code>let totalSold = ticketSold.reduce((total,perticket) =&gt; total + perticket,0); //returns 170</code></p>
<h2 id="heading-surprise-mee">Surprise Mee</h2>
<p>surprise is that you can create your methods and surprise anyone which called polyfill lets create</p>
<p>I need to add the text "ticket kat gaya" for all bus passengers for tickets</p>
<p><code>Array.prototype.ticketDone = function(mes){ let pList = []; for(let i = 0; i &lt; this.length; i++){ pList.push(mes(this[i])); } return pList; }</code></p>
<p><code>let bus = ["p1","p2","p3","p4","p5","p6","p7","p8"]</code><br /><code>bus.ticketDone(pas =&gt; pas + " ticket kat gaya");</code></p>
<h2 id="heading-conclusion-revision">Conclusion + Revision</h2>
<p><code>const myArr = [1,2,3,4,5.5] myArr.length() // returns the array length ( count of items the array is 5)</code><br /><a target="_blank" href="http://myArr.at"><code>myArr.at</code></a><code>(n) // get the value of nth position ( 4th position value is 5.5)</code><br /><code>myArr.indexOf(4) // get the position of value (5 is at 4th position)</code><br /><code>myArr.concat(4,[45,56,76,86]) // add more value into the array (also can be single value or can be another array itself)</code><br /><code>myArr.fill(0); // fill all the position with passed value</code><br /><code>myArr.find((item) =&gt; item &lt; 7) // check for the first item to match the condition</code><br /><code>myArr.some((item) =&gt; item &lt; 7) // check for the some item to match the condition</code><br /><code>myArr.every((item) =&gt; item &lt; 7) // check for all items to match the contions with iterations with true and false</code><br /><code>myArr.includes(item); // return booleans if item avilable or not in the array</code><br /><code>myArr.filter((item) =&gt; item &gt;4) // return the list of the array with matched the conditions</code> <a target="_blank" href="http://myArr.map"><code>m</code></a><br /><code>myArr.map(item =&gt; item * 2) // return the new array with any actions performed with each elements</code><br /><code>myArr.flat(); // convert in the single array from multilevel array</code><br /><code>myArr.flatMap(item =&gt; item + "a") // maping and also flat the array if there is multilevel array</code><br /><code>myArr.join('-') // return string with all value differnciate with mentioned value</code><br /><code>myArr.split('-') // return array with split value myArr.push(7) // add new item in the last of the array myArr.pop // removed and returns the last item of the array</code><br /><code>myArr.unshift(0) // add new item or items in the start of array</code><br /><code>myArr.shift() // removed first item from array</code><br /><code>myArr.splice(start, count) // returns removed form old array and return the new array from start to number of counts</code><br /><code>myArr.slice(count) // just slice removed or sliced from start to count</code><br /><code>arr.reduce((total,item) =&gt; total+item,intial) // return the sum of the array with intial if added</code></p>
<p>Polyfill to create your custom methods</p>
<p><code>Array.prototype.myMap = function(fn){</code><br /><code>myArr = []</code><br /><code>for(let i=0; i&lt;this.length; i++){</code><br /><code>myArr.push(fn(this[i]))</code><br /><code>}</code><br /><code>return myArr;</code><br /><code>}</code></p>
]]></content:encoded></item></channel></rss>