Vuejs Watching Form Input Validation

use watch to monitor form input fields and validate them in real-time.
<template>
  <div>
    <label>Email:</label>
    <input v-model="email" type="email" />
    <span v-if="emailError">{{ emailError }}</span>
  </div>
</template>

<script>
import { ref, watch } from 'vue';

export default {
  setup() {
    const email = ref('');
    const emailError = ref('');

    // Watch email input for changes and validate it
    watch(email, (newEmail) => {
      const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailPattern.test(newEmail)) {
        emailError.value = 'Invalid email format';
      } else {
        emailError.value = '';
      }
    });

    return { email, emailError };
  },
};
</script>

JS Default Object With Object Assign

Default objects with Object.assign
const menuConfig = {
  title: "Order",
  buttonText: "Send",
  cancellable: true
};

function createMenu(config) {
  config = Object.assign(
    {
      title: "Foo",
      body: "Bar",
      buttonText: "Baz",
      cancellable: true
    },
    config
  );

  // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}
}

createMenu(menuConfig);

// bad code [X]
function createMenu(config) {
  config.title = config.title || "Foo";
  config.body = config.body || "Bar";
  config.buttonText = config.buttonText || "Baz";
  config.cancellable =
    config.cancellable !== undefined ? config.cancellable : true;
}

Vuejs Axios Call Api

The best practices for API calls in Vue.js 3 Composition API.
// src/services/apiService.js
import axios from 'axios';

const apiClient = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 1000,
  headers: { 'Content-Type': 'application/json' },
});

// Define your API methods
export default {
  getUsers() {
    return apiClient.get('/users');
  },
  getUser(id) {
    return apiClient.get(`/users/${id}`);
  },
};


// src/composables/useFetchUsers.js
import { ref } from 'vue';
import apiService from '../services/apiService';

export function useFetchUsers() {
  const data = ref(null);
  const loading = ref(false);
  const error = ref(null);

  const fetchUsers = async () => {
    loading.value = true;
    try {
      const response = await apiService.getUsers();
      data.value = response.data;
    } catch (err) {
      error.value = 'Error fetching users';
    } finally {
      loading.value = false;
    }
  };

  return { data, loading, error, fetchUsers };
}


// src/components/UsersComponent.vue
<template>
  <div>
    <button @click="fetchUsers">Load Users</button>
    <div v-if="loading">Loading...</div>
    <ul v-if="data">
      <li v-for="user in data" :key="user.id">{{ user.name }}</li>
    </ul>
    <div v-if="error">{{ error }}</div>
  </div>
</template>

<script>
import { onMounted } from 'vue';
import { useFetchUsers } from '../composables/useFetchUsers';

export default {
  setup() {
    const { data, loading, error, fetchUsers } = useFetchUsers();
    
    onMounted(() => fetchUsers()); // Fetch users when the component is mounted

    return { data, loading, error, fetchUsers };
  },
};
</script>

// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import UsersComponent from './components/UsersComponent.vue';

createApp(App)
  .component('UsersComponent', UsersComponent)
  .mount('#app');
src/
├── composables/
│   └── useFetchUsers.js   # Composable for fetching users
├── services/
│   └── apiService.js      # Centralized API service layer
├── components/
│   └── UsersComponent.vue # Component using the API and composable
└── main.js                # Main entry point for Vue app

Js Sort Array Object

Sort an array of objects by property in JavaScript
// Sorting by a String Property
const people = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 },
  { name: "Charlie", age: 35 }
];

people.sort((a, b) => a.name.localeCompare(b.name));

console.log(people);
// Output: [{ name: "Alice", age: 30 }, { name: "Bob", age: 25 }, { name: "Charlie", age: 35 }]

// Sorting by a Numeric Property
const people = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 },
  { name: "Charlie", age: 35 }
];

people.sort((a, b) => a.age - b.age);

console.log(people);
// Output: [{ name: "Bob", age: 25 }, { name: "Alice", age: 30 }, { name: "Charlie", age: 35 }]

// Sorting by a Date Property
const events = [
  { title: "Event 1", date: new Date('2023-09-01') },
  { title: "Event 2", date: new Date('2023-08-01') },
  { title: "Event 3", date: new Date('2023-07-01') }
];

events.sort((a, b) => a.date - b.date);

console.log(events);
// Output: [{ title: "Event 3", date: 2023-07-01 }, { title: "Event 2", date: 2023-08-01 }, { title: "Event 1", date: 2023-09-01 }]

// Sorting in Descending Order
people.sort((a, b) => b.age - a.age);

console.log(people);
// Output: [{ name: "Charlie", age: 35 }, { name: "Alice", age: 30 }, { name: "Bob", age: 25 }]

Js Await Async in for Loop

using await-async in a for loop in JavaScript
async function fetchData(urls) {
  for (const url of urls) {
    try {
      const response = await fetch(url);
      const data = await response.json();
      console.log(`Data from ${url}:`, data);
    } catch (error) {
      console.error(`Error fetching data from ${url}:`, error);
    }
  }
}

const urls = [
  'https://jsonplaceholder.typicode.com/posts/1',
  'https://jsonplaceholder.typicode.com/posts/2',
  'https://jsonplaceholder.typicode.com/posts/3',
];

fetchData(urls);

fetchData is an async function that takes an array of URLs.
It loops through the urls array, and for each url, it waits for the fetch call to resolve using await.
The result of the fetch is then parsed as JSON using await response.json(), and the data is logged.
This ensures that each fetch operation waits for the previous one to complete before moving to the next URL in the loop.

Nodejs Mongoose Connection

set up and manage a connection to MongoDB using Mongoose.
// Import Mongoose
const mongoose = require('mongoose');

// MongoDB connection URI
const mongoURI = 'mongodb://localhost:27017/your_database_name'; // Replace with your actual URI and database name

// Mongoose connection options
const options = {
  useNewUrlParser: true,    // Use new URL string parser instead of deprecated one
  useUnifiedTopology: true, // Use new server discovery and monitoring engine
  useCreateIndex: true,     // Use MongoDB's createIndex() function
  useFindAndModify: false,  // Use native findOneAndUpdate() rather than findAndModify()
};

// Connect to MongoDB
mongoose.connect(mongoURI, options)
  .then(() => {
    console.log('Connected to MongoDB successfully!');
  })
  .catch((error) => {
    console.error('Error connecting to MongoDB:', error);
  });

// Optional: Handle connection events
const db = mongoose.connection;

db.on('error', (error) => {
  console.error('MongoDB connection error:', error);
});

db.on('disconnected', () => {
  console.log('MongoDB disconnected');
});

// Handle process termination, close Mongoose connection
process.on('SIGINT', async () => {
  await mongoose.connection.close();
  console.log('MongoDB connection closed due to app termination');
  process.exit(0);
});