React Upload Image With Axios

allow users to select a file, preview and upload it using a POST request to an API
import React, { useState } from 'react';
import axios from 'axios';

const FileUpload = () => {
  const [file, setFile] = useState(null);
  const [preview, setPreview] = useState(null); // Preview for image files

  const handleFileChange = (event) => {
    const selectedFile = event.target.files[0];

    // Client-side validation: Check file type
    const allowedTypes = ['image/jpeg', 'image/png'];
    if (selectedFile && !allowedTypes.includes(selectedFile.type)) {
      alert('Only JPEG or PNG files are allowed');
      return;
    }

    // Client-side validation: Check file size (max 2MB)
    const maxSize = 2 * 1024 * 1024;
    if (selectedFile && selectedFile.size > maxSize) {
      alert('File size exceeds 2MB');
      return;
    }

    setFile(selectedFile);

    // Show a preview if the file is an image
    if (selectedFile && selectedFile.type.startsWith('image/')) {
      const filePreviewURL = URL.createObjectURL(selectedFile);
      setPreview(filePreviewURL);
    }
  };

  const handleFileUpload = async (event) => {
    event.preventDefault();

    if (!file) {
      alert('Please select a file before uploading.');
      return;
    }

    // Create FormData to send the file
    const formData = new FormData();
    formData.append('file', file);

    // Upload file using axios
    try {
      const response = await axios.post('https://examplebbmcode.com/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      if (response.status === 200) {
        alert('File uploaded successfully!');
      } else {
        alert('File upload failed.');
      }
    } catch (error) {
      console.error('Error uploading file:', error);
      alert('An error occurred while uploading the file.');
    }
  };

  return (
    <div>
      <h2>Upload a File</h2>
      <form onSubmit={handleFileUpload}>
        <input type="file" onChange={handleFileChange} />
        <button type="submit">Upload</button>
      </form>

      {/* Display file preview if it's an image */}
      {preview && <img src={preview} alt="Preview" style={{ width: '200px', marginTop: '10px' }} />}
    </div>
  );
};

export default FileUpload;

Js Throttle Function

A throttle function ensures that a given function is only called once within a specified period, even if it’s triggered multiple times during that period.
function throttle(func, limit) {
  let inThrottle;
  return function(...args) {
    const context = this;
    if (!inThrottle) {
      func.apply(context, args);  // Executes the function if not in throttle period
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);  // Sets a delay before next execution is allowed
    }
  };
}
// Basic Usage Example
function onScroll() {
  console.log('Scroll event detected:', new Date().toLocaleTimeString());
}

// Limit the scroll event handler to run once every 1000ms (1 second)
window.addEventListener('scroll', throttle(onScroll, 1000));
// even if the user scrolls rapidly, the onScroll function will only be executed once every second.

Js Remove Non Unique or Unique Array Values

Remove array values that appear more than once and remove all values that appear only once
// remove all values that appear more than once
const removeNonUnique = arr =>
  [...new Set(arr)].filter(i => arr.indexOf(i) === arr.lastIndexOf(i));

removeNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 3, 5]

// remove all values that appear only once
const removeUnique = arr =>
  [...new Set(arr)].filter(i => arr.indexOf(i) !== arr.lastIndexOf(i));

removeUnique([1, 2, 2, 3, 4, 4, 5]); // [2, 4]

jQuery Drag Drop Upload File

Enable drag-and-drop for file uploads.
$('#dropzone').on('dragover', function(e) {
    e.preventDefault();
    e.stopPropagation();
    $(this).addClass('dragging');
}).on('dragleave', function(e) {
    e.preventDefault();
    e.stopPropagation();
    $(this).removeClass('dragging');
}).on('drop', function(e) {
    e.preventDefault();
    e.stopPropagation();
    $(this).removeClass('dragging');
    
    var files = e.originalEvent.dataTransfer.files;
    uploadFiles(files);
});

function uploadFiles(files) {
    var formData = new FormData();
    $.each(files, function(i, file) {
        formData.append('file[]', file);
    });

    $.ajax({
        url: '/upload-files',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            console.log('Files uploaded successfully!');
        }
    });
}

jQuery Auto Save Form Data in LocalStorage

Automatically save form data in local storage so that it persists on page refresh.
$('input, textarea').on('keyup', function() {
    var id = $(this).attr('id');
    var value = $(this).val();
    localStorage.setItem(id, value);
});

// Retrieve saved data
$('input, textarea').each(function() {
    var id = $(this).attr('id');
    if (localStorage.getItem(id)) {
        $(this).val(localStorage.getItem(id));
    }
});

Vuejs watchEffect Filtering and Searching Data

watchEffect automatically filters the user list based on the search query, great for real-time search scenarios.
import { ref, watchEffect } from 'vue';

export default {
  setup() {
    const searchQuery = ref('');
    const users = ref([
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 30 },
      { name: 'Charlie', age: 35 },
    ]);
    const filteredUsers = ref([]);

    watchEffect(() => {
      if (searchQuery.value) {
        filteredUsers.value = users.value.filter(user =>
          user.name.toLowerCase().includes(searchQuery.value.toLowerCase())
        );
      } else {
        filteredUsers.value = users.value;
      }
    });

    return { searchQuery, filteredUsers };
  }
};

Vuejs Watching Window Resize Event

Use watch to respond to changes in window size, which can be useful for making responsive components.
<template>
  <div>
    <p>Window Width: {{ windowWidth }}</p>
    <p v-if="isMobile">You are on a mobile device!</p>
  </div>
</template>

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

export default {
  setup() {
    const windowWidth = ref(window.innerWidth);
    const isMobile = ref(windowWidth.value < 768);

    const updateWidth = () => {
      windowWidth.value = window.innerWidth;
    };

    watch(windowWidth, (newWidth) => {
      isMobile.value = newWidth < 768;
    });

    onMounted(() => {
      window.addEventListener('resize', updateWidth);
    });

    onUnmounted(() => {
      window.removeEventListener('resize', updateWidth);
    });

    return { windowWidth, isMobile };
  },
};
</script>

Vuejs Watch to Trigger API

Use watch to trigger API calls when a value changes under specific conditions.
<template>
  <div>
    <input v-model="username" placeholder="Enter username" />
    <p v-if="error">{{ error }}</p>
  </div>
</template>

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

export default {
  setup() {
    const username = ref('');
    const error = ref('');

    // Watch the username and make an API call when it changes
    watch(username, async (newUsername) => {
      if (newUsername.length >= 3) {
        try {
          const response = await axios.get(`/api/check-username?username=${newUsername}`);
          if (!response.data.available) {
            error.value = 'Username is already taken';
          } else {
            error.value = '';
          }
        } catch (err) {
          error.value = 'Error checking username';
        }
      } else {
        error.value = 'Username must be at least 3 characters long';
      }
    });

    return { username, error };
  },
};
</script>

Vuejs Watching Route Changes

use watch to monitor changes to the current route and react accordingly (e.g., fetch new data when a different page is navigated to).
<script>
import { watch } from 'vue';
import { useRoute } from 'vue-router';

export default {
  setup() {
    const route = useRoute();

    // Watch for changes in the route params or query
    watch(route, (newRoute, oldRoute) => {
      console.log('Route changed:', newRoute.path);
      // trigger a function or fetch data based on the new route
    });

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