microsoft / ApplicationInsights-JS

Microsoft Application Insights SDK for JavaScript
MIT License
652 stars 242 forks source link

[BUG] Remove Unload event listeners are deprecated and will be removed. #2427

Open ganesh12301 opened 1 month ago

ganesh12301 commented 1 month ago

import { LightningElement, track, api } from 'lwc'; import createCase from '@salesforce/apex/CaseCreationController.createCase'; import uploadFile from '@salesforce/apex/CaseCreationController.uploadFile'; import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class ParkEntryApplication extends LightningElement { // Fields companyToVisit = ''; contactPerson = ''; Email = ''; purposeOfEntry = ''; requestorFullName = ''; requestorCompanyName = ''; requestorEmail = ''; parkEntryDate; duration = ''; peopleEntering = ''; vehiclePlateNumber = ''; uploadedFileUrl; recordId; fileData; file; base64; filename;

// Duration options for combobox
get durationOptions() {
    return [
        { label: '1', value: '1' },
        { label: '3', value: '3' },
        { label: '5', value: '5' }
    ];
}

// Handle field changes
handleInputChange(event) {
    const field = event.target.dataset.id;
    this[field] = event.target.value;
}

// Handle form submission
async handleSubmit() {
    let isValid = this.validateForm();

    if (!isValid) {
        console.error('Form is invalid, cannot submit');
        return;
    }

    try {
        // Prepare case data
        const caseObj = {
            "companyToVisit": this.companyToVisit,
            "contactPerson": this.contactPerson,
            "Email": this.Email,
            "purposeOfEntry": this.purposeOfEntry,
            "requestorFullName": this.requestorFullName,
            "requestorCompanyName": this.requestorCompanyName,
            "requestorEmail": this.requestorEmail,
            "parkEntryDate": this.parkEntryDate,
            "duration": this.duration,
            "peopleEntering": this.peopleEntering,
            "vehiclePlateNumber": this.vehiclePlateNumber,
            "uploadedFileUrl": this.uploadedFileUrl
        };

        // Create case
        this.recordId = await createCase({ caseData: caseObj });
        this.showToast('Success', 'Case Created Successfully', 'success');

        // If there's a file, upload it
        if (this.filename) {
            await this.handleFileUpload();
        }

        // Clear form data after submission
        this.clearFormData();

    } catch (error) {
        console.error('Error creating case or uploading file:', error);
        this.showToast('Error', 'Failed to create case or upload file', 'error');
    }
}

// Validate the form
validateForm() {
    let isValid = true;
    const requiredFields = [
        'companyToVisit', 'contactPerson', 'Email', 'purposeOfEntry',
        'requestorFullName', 'requestorCompanyName', 'requestorEmail',
        'parkEntryDate', 'duration', 'vehiclePlateNumber'
    ];

    requiredFields.forEach(field => {
        const inputField = this.template.querySelector(`[data-id="${field}"]`);
        if (!this[field] || !inputField.value) {
            inputField.setCustomValidity('This field is required');
            isValid = false;
        } else {
            inputField.setCustomValidity('');
        }
        inputField.reportValidity();
    });

    return isValid;
}

// Handle file selection
openfileUpload(event) {
    this.file = event.target.files[0];
    this.filename = this.file.name;
    const reader = new FileReader();
    reader.onload = () => {
        this.base64 = reader.result.split(',')[1];
    };
    reader.readAsDataURL(this.file);
}

// Upload the file to the server
async handleFileUpload() {
    this.fileData = {
        'filename': this.filename,
        'base64': this.base64,
        'recordId': this.recordId
    };
    const { base64, filename, recordId } = this.fileData;

    try {
        await uploadFile({ base64, filename, recordId });
        this.showToast('Success', 'File Uploaded Successfully', 'success');
        this.template.querySelector('input[type="file"]').value = ''; // Clear file input
    } catch (error) {
        console.error('Error uploading file:', error);
        this.showToast('Error', 'File upload failed', 'error');
    }
}

// Show toast messages
showToast(title, message, variant) {
    const toastEvent = new ShowToastEvent({
        title,
        message,
        variant
    });
    this.dispatchEvent(toastEvent);
}

// Clear form data after submission
clearFormData() {
    this.companyToVisit = '';
    this.contactPerson = '';
    this.Email = '';
    this.purposeOfEntry = '';
    this.requestorFullName = '';
    this.requestorCompanyName = '';
    this.requestorEmail = '';
    this.parkEntryDate = null;
    this.duration = '';
    this.peopleEntering = '';
    this.vehiclePlateNumber = '';
    this.uploadedFileUrl = '';
    this.filename = '';
}

}

MSNev commented 1 month ago

I'm not quite sure what your asking with the detail provided, but to "glean" your request from the title, I think you asking about how to "stop" us from registering the unload event...

If however, you want us to "stop" hooking one or more of the unload events we have a configuration where you can provide the "event" names that you don't want use to register

However, there is 1 catch. We NEED to hook at least 1 of these events to ensure that we can correctly handle the page unload scenario, so if you tell us to ignore several events and the active runtime doesn't support any of the remaining ones we will STILL turn around and hook all of the default one (effectively ignoring your requested config).