Search This Blog

Showing posts with label Tips. Show all posts
Showing posts with label Tips. Show all posts

Monday, January 13, 2025

How to configure JWT interceptor in Angular

 


Define and export the jwtInterceptor function as below: (save in jwtInterceptor.ts)

import { HttpRequest, HttpHandlerFn } from '@angular/common/http';

import { inject } from '@angular/core';
import { AuthService } from '../services/auth.service'; // Replace with the actual path to your AuthService

export function jwtInterceptor(req: HttpRequest<any>, next: HttpHandlerFn) {
// Inject the AuthService to get the authentication token
const authToken = inject(AuthService).getToken();

// Clone the request and set the Authorization header
const newReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${authToken}`),
});

// Pass the cloned request to the next handler
return next(newReq);
}

Configurein AppConfig.js like below:


import { jwtInterceptor } from './interceptor/jwtInterceptor';// Import the function

export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideClientHydration(withEventReplay()),
provideHttpClient(withFetch(),withInterceptors([jwtInterceptor]),),
]
};

Note: Way to do int Angular 15+


That's it, you are set, Happy Conding !!

Cheers,
Kapil

Friday, January 3, 2025

How to Prevent the "Cannot Read Property 'map' of Undefined" Error

  

    One of the most common errors encountered by JavaScript developers, especially when working with arrays and React, is the infamous:

TypeError: Cannot read property 'map' of undefined

This error indicates that the code is trying to call the map method on a value that is undefined. Here, we’ll break down the causes of this error and provide actionable solutions to prevent it.


Understanding the Problem

The map method is used to iterate over an array and transform its elements. If the value you’re trying to call map on isn’t an array (e.g., undefined, null, or another non-array type), JavaScript will throw this error.

Common Scenarios

  1. Undefined or null data:

    const items = undefined;
    items.map(item => console.log(item)); // TypeError
  2. Asynchronous data loading: When fetching data from an API, the array might not be available immediately.

    const [data, setData] = useState();
    useEffect(() => {
        fetch('/api/data')
            .then(response => response.json())
            .then(fetchedData => setData(fetchedData));
    }, []);
    
    data.map(item => console.log(item)); // TypeError
  3. Incorrect initial value: You might set the state to undefined or forget to initialize it as an empty array.


Strategies to Prevent the Error

1. Initialize Variables Properly

Always initialize variables that will hold arrays with an empty array. This ensures the map method can be safely called.

const items = [];
items.map(item => console.log(item)); // Safe, no error

2. Use Optional Chaining

Optional chaining (?.) prevents accessing properties or methods on undefined or null.

items?.map(item => console.log(item)); // No error, but does nothing if items is undefined

3. Provide Default Values

Using default parameters or the || operator ensures a fallback array if the value is undefined.

Example 1: Default Parameter

function processItems(items = []) {
    items.map(item => console.log(item));
}

Example 2: Logical OR

(items || []).map(item => console.log(item));

4. Check the Type Before Calling map

Explicitly validate the type of the variable to ensure it is an array.

if (Array.isArray(items)) {
    items.map(item => console.log(item));
} else {
    console.log('items is not an array');
}

5. Handle Asynchronous Data Gracefully

When working with APIs or asynchronous operations, make sure to handle the loading state properly.

const [data, setData] = useState([]); // Initialize with an empty array

useEffect(() => {
    fetch('/api/data')
        .then(response => response.json())
        .then(fetchedData => setData(fetchedData))
        .catch(error => console.error('Error fetching data:', error));
}, []);

return (
    <div>
        {data.map(item => (
            <p key={item.id}>{item.name}</p>
        ))}
    </div>
);

Debugging Tips

If you encounter this error, follow these steps to debug it:

  1. Log the Variable: Use console.log to check the value of the variable before calling map.

    console.log(items);
  2. Check Data Flow: Trace the origin of the variable to ensure it’s being set correctly.

  3. Handle Edge Cases: Consider scenarios where the variable might be undefined or null, especially when working with dynamic or external data.


Happy Coding 

Cheers,
Kapil

Tuesday, December 31, 2024

How to update node application without server restart


Updating Node.js Applications Without Manual Restart Using Nodemon

When developing Node.js applications, manually restarting the server every time you make changes to your code can be both time-consuming and tedious. Thankfully, tools like Nodemon simplify the development workflow by automatically restarting your Node.js application whenever a file changes. This article explores how to set up and use Nodemon to enhance your productivity.

What is Nodemon?

Nodemon is a utility that monitors changes in your Node.js application files and automatically restarts the server when a change is detected. It’s particularly useful for developers who need rapid feedback while coding.

Key Features of Nodemon

  • Automatic server restarts on file changes.

  • Supports custom configurations for monitoring specific files or directories.

  • Compatible with most Node.js frameworks and libraries.

  • Lightweight and easy to set up.

Installing Nodemon

To get started with Nodemon, you’ll need to have Node.js and npm (Node Package Manager) installed on your system.

  1. Open your terminal.

  2. Install Nodemon globally by running:

    npm install -g nodemon

Alternatively, you can add it as a development dependency to your project:

    npm install --save-dev nodemon

Running Your Application with Nodemon

Using Nodemon to run your application is simple. Instead of starting your app with node, use nodemon:

nodemon app.js

and if nodemon is not installed globally then execute following:

./node_modules/.bin/nodemon app.js

Here, app.js is the entry point of your application. Nodemon will now monitor your project files and automatically restart the server when any changes are detected.

Customizing Nodemon

Using a Configuration File

Nodemon allows you to create a configuration file for more advanced setups. By default, it looks for a nodemon.json file in the root of your project. Here’s an example configuration:

{
  "watch": ["src"],
  "ext": "js,json,html",
  "ignore": ["node_modules"],
  "exec": "node src/index.js"
}
  • watch: Specifies the directories or files to monitor.

  • ext: Defines the file extensions to watch.

  • ignore: Excludes specific files or directories from monitoring.

  • exec: Specifies the command to run your application.

Command-Line Options

Nodemon also supports various command-line options for customization:

  • Watch Specific Files/Directories:

    nodemon --watch src
  • Ignore Files/Directories:

    nodemon --ignore logs
  • Specify Extensions to Watch:

    nodemon --ext js,html

Enhancing Productivity with Nodemon

Here are a few tips to make the most of Nodemon:

  1. Combine with Environment Variables: Use environment variables to manage different configurations:

    nodemon -e js --exec "NODE_ENV=development node app.js"
  2. Integrate with npm Scripts: Define a script in your package.json for easy use:

    "scripts": {
      "start:dev": "nodemon app.js"
    }

    Then run:

    npm run start:dev
  3. Use Debugging Tools: Nodemon works seamlessly with Node.js debugging tools. Start your app in debug mode:

    nodemon --inspect app.js

Conclusion

Nodemon is a powerful tool that eliminates the hassle of manually restarting your Node.js server during development. With its flexibility and ease of use, it’s a must-have for any Node.js developer looking to streamline their workflow.

Set up Nodemon today and enjoy a smoother, more efficient development experience!

Cheers,

Kapil 

Thursday, April 20, 2023

Warning: bundle initial exceeded maximum budget - Angular

 

If we get following warning :

Warning: bundle initial exceeded maximum budget.

then to solev this we need to increase budget in angular.json 

            "budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},

Cheers,


Saturday, October 3, 2015

Install Gradle and Setup with Eclipse


Step 1 : Install Gradle from the following link:
https://gradle.org/gradle-download/
(binary or full)

Step 2: set gradle path at environment Path variable  :



Step 3 : Open  command Prompt and run command "gradle" , it should prompt following message



Setup Gradle with eclipse :


Step 1 : Click Help - > Install Software ->

https://github.com/eclipse/buildship/blob/master/docs/user/Installation.md

Eclipse Version


Mars (4.5)

release

http://download.eclipse.org/buildship/updates/e45/releases/1.0


Luna (4.4)

release

http://download.eclipse.org/buildship/updates/e44/releases/1.0


Kepler (4.3)

release

http://download.eclipse.org/buildship/updates/e43/releases/1.0


Juno (4.2)

release

http://download.eclipse.org/buildship/updates/e42/releases/1.0


Indigo (3.7)

release

http://download.eclipse.org/buildship/updates/e37/releases/1.


Helios (3.6)

release

http://download.eclipse.org/buildship/updates/e36/releases/1.0



Step 2 : Click Next -> Until Finish

Step 3 : Click Window -> Preferecne - > Gradle ( to view gradle setting)

You are done

Cheers ,
Kapil

Popular Posts