Having trouble with the image compressor not being imported correctly in Next.js?

I've been attempting to compress an image, but when I try to import the ImageCompressor normally like this:

import ImageCompressor from "image-compressor.js";

It throws an error:

Uncaught ReferenceError: window is not defined

This is the section of my code:

              const handleImage = async (e) => {
                const selectedFile = e.target.files[0];
                if (selectedFile) {
                    try {
                        const compressedDataURL = await compressImage(selectedFile);

                        console.log("Compressed dataURL: ", compressedDataURL);

                        setImage(compressedDataURL);
                    } catch (error) {
                        console.error("Error compressing image:", error);
                    }
                }
            };
            //Function for compressing images
            const compressImage = async (file) => {
                return new Promise((resolve, reject) => {
                    new ImageCompressor(file, {
                        quality: 0.5, // Adjust the quality as needed
                        success(result) {
                            const reader = new FileReader();
                            reader.onload = (e) => {
                                const imageData = e.target.result;
                                resolve(`data:image/jpeg;base64,${btoa(imageData)}`);
                            };
                            reader.readAsBinaryString(result);
                        },
                        error(e) {
                            reject(e);
                        },
                    });
                });
            };

Another approach I attempted was importing the image compressor inside the compression function:

const compressImage = async (file) => {
try {
    // Import the ImageCompressor class from the library
    const { ImageCompressor } = await import("image-compressor.js");

    return new Promise((resolve, reject) => {
        new ImageCompressor(file, {
            quality: 0.5, // Adjust the quality as needed
            success(result) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    const imageData = e.target.result;
                    resolve(`data:image/jpeg;base64,${btoa(imageData)}`);
                };
                reader.readAsBinaryString(result);
            },
            error(e) {
                reject(e);
            },
        });
    });
} catch (error) {
    console.error("Error importing ImageCompressor:", error);
   }
  };

However, it resulted in an error stating that it cannot be a state variable.

Answer №1

To efficiently import your image compressor, utilize the useEffect method in this manner:

         useEffect(() => {
            // Conditionally load ImageCompressor if necessary (e.g., within the browser)
            if (typeof window !== "undefined") {
             import("image-compressor.js").then((module) => {
                 // Save it to the window object for later reference
                window.ImageCompressor = module.default || module;
            });
        }
       }, []);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

MongoDB NextJS connection issue "tried to retrieve a connection from a closed connection pool"

I am attempting to establish a connection to my MongoDB database in order to retrieve some information. When setting up the connection without fetching any data, everything works fine. However, when trying to fetch data, the console throws this error: at ...

An effective method for targeting a specific button within a CSS file

I have multiple button tags in my code, but I need to style a specific one using CSS. How can I target this particular button and apply styles only to it while leaving the others unchanged? Do I need to assign the button to a variable and reference that va ...

Discover the method for invoking a Javascript function within a Leaflet popup using HTML

Upon clicking on a marker on the leaflet map, I aim to trigger a popup box that contains five elements: Title Description Image Button (Next Image) Button (Previous Image) To achieve this, I attempted to include a custom popup for each feature ...

Calculating the position of an element in an array passed from a separate file with ReactJS and Ant Design

I'm currently working with a file that contains some JavaScript code featuring an array with multiple objects containing key-value pairs. In my main file (App.jsx), I initialize a State Variable and assign it the array from another JS file. My goal no ...

When does the React state update warning occur on an unmounted component?

When is the appropriate time to verify if a component has been mounted? I frequently encounter a warning in the title when using setState calls. To avoid this warning, I have started declaring a variable and initializing it to true in componentDidMount, t ...

The header that sticks on scroll is annoyingly blocking the content

I managed to create a sticky on-scroll header/navigation bar successfully. Here is how it looks now However, I encountered an issue. When it reaches the top, it automatically 'covers' the top part of my content, which has text on it, and I don& ...

What is the method for rotating a map using JavaScript?

My map built with Leaflet displays a route and a moving car marker. Now, I am looking to implement a feature where the map rotates based on the direction of the car. I have access to both the current coordinates of the car and the target coordinates. ...

Utilizing JQuery toggle feature to display extra content

Having some trouble with my JQuery toggle/collapse function. I added my own class "timelineEventWide" but it's not working as expected. As a JavaScript beginner, could someone please help me with the correct syntax? Thank you! e(".expandAll").toggle( ...

What is the process for renaming a Discord channel through nodeJS and discordJS?

I'm currently developing my first Discord bot using node.js and discord.js. My objective is to provide real-time information about a Minecraft server through Discord. What I aim to achieve is to have a channel that automatically updates its name per ...

Why won't my AngularJS Google Maps marker trigger any events?

My issue is with the marker event not working on a UI Google Map. I am using this link. Here is my view setup: <ui-gmap-markers models="mapResult" fit="true" idkey="mapResult.id" coords="'form_geo'" click="'onclick'" events="mapRe ...

Converting JSON data to HTML using Handlebars

Can you assist me in transforming the following JSON data into a table with 3 columns: property name, property source, and property value? "result": { "total": 100, "config": { "propName1": { "source": "propsrc1", ...

Omit words from list in a route in Express.js

When working with the Express.js Framework, I am faced with a scenario where I have the following route defined: app.post('/:username/:slug', user.fn); I am now looking for a solution to create a regular expression that can validate if the slug ...

Creating wrapped text in Three.js

Is there a way to wrap a Text3d object around a 3D or 2D Path in Three.js? I have looked into some tutorials for r.49 of Three.js and it appears that the current version does not have support for this feature. While I am able to create the text and extru ...

Toggle the class and execute the order within a jQuery script

When the mouse moves in, the jQuery trigger enters the status. $(".test").bind("mouseenter mouseout", function(event) { $(this).toggleClass("entered"); alert("mouse position (" + event.pageX + "," + event.pageY + ")"); }); .entered { ...

ajaxStop and ajaxStart not functioning as expected

Currently working on a project to create a Wikipedia viewer, and running into an issue with the following code snippet: $(document).ready(function() { $(document).on('click', '#search_button', function() { ...

Can someone explain the significance of this in an HTML form?

Can anyone explain the following code snippet found in a web form? I found this button code on a webpage, but I'm having trouble understanding it. Could someone provide some clarity? <input type="submit" name="ctl00$ContentPlaceHolder1$Button8" v ...

Issue with bouncing dropdown menu

I am in the process of enhancing a Wordpress website by implementing a jQuery menu with sub-menus. Below is the jQuery code snippet: $(document).ready(function(){ $('.menu > li').hover(function(){ var position = $(this).position(); ...

Using JavaScript to generate dynamic folders in Alfresco is not functioning as expected

Working with Alfresco 4.0.d community edition (also tested on Alfresco 4.0.c) on an Oracle Linux 64-bit virtual machine using Firefox. I've been developing a script to dynamically create sub-folders as new items are added to a space/folder via a rule ...

Using AJAX in JavaScript within an HTML document is a valuable skill to have

I have the following JavaScript function that I need to call the /print2 function without clicking any buttons. I attempted to use Ajax for this, but I am new to Ajax and JavaScript. Can you help me identify where the issue might be? Thank you... <scr ...

``on click of the back button of the browser, automatically submit the form

I'm facing a specific issue that I need help with. I have created a form with a hidden value, and I want it to be submitted when the user clicks the browser's back button. Although I've managed to control the backspace key, I haven't be ...