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

Encountering a problem in Next.js when trying to redirect within a higher-order component

I have created a Higher Order Component that redirects unAuthenticated users: export const ProtectRoute = ({ children }) => { const { isAuthenticated, isLoading } = useAuth(); const router = useRouter() if (isLoading){ return (<><Hea ...

Selenium in Perl: Facing a puzzling JavaScript error while attempting to resize window

Utilizing the Perl Selenium package known as WWW::Selenium, I have encountered a perplexing JavaScript error while attempting to resize the browser window. The error message reads: "Threw an exception: missing ; before statement". Below is the code snippe ...

What steps should I take to make my Vue JS delete function operational?

As I work on developing my website, I've encountered some challenges. Being new to coding, I'm struggling with creating a functional delete user button. When I click delete, it redirects me to the delete URL but doesn't remove the entry from ...

Insufficient module names remaining in NPM

Starting to release modules on NPM has been on my mind, but I can't help but worry about the limited availability of sensible module names in the public domain. Is there a way to create a public NPM module that organizes all my module names within a ...

React component will automatically rerender if the cache is disabled in the Chrome browser

In my React application, I am utilizing 'react-image-pan-zoom-rotate' to display images. Visit the GitHub repository here The image I am displaying is sourced from an external service and passed to both libraries for rendering. Lately, I have ...

Leveraging Selenium for extracting data from a webpage containing JavaScript

I am trying to extract data from a Google Scholar page that has a 'show more' button. After researching, I found out that this page is not in HTML format but rather in JavaScript. There are different methods to scrape such pages and I attempted t ...

CAUTION: Attempted to load angular multiple times while loading the page

I encountered a warning message while working on my project, causing errors in calling backend APIs due to duplicate calls. Despite attempting previously suggested solutions from the forum, I am stuck and seeking assistance. Can anyone provide guidance? Be ...

Tips for implementing ajax and codeigniter to load additional comments on a web page

Is it possible to customize Codeigniter's default pagination to achieve a "viewMore" link style when loading more records using AJAX? The challenge lies in creating a div that automatically expands to handle large numbers of records, such as 10,000 a ...

Tips for preserving both existing data and new data within React's useState hook in React Native or ReactJS?

As I dive into learning reactjs, one question that has been on my mind is how to store both previous and upcoming data in useState. Is there a special trick for achieving this? For example: Imagine I enter "A" and then follow it with "B". My goal is to ha ...

Modifying a Sass variable using a Knockout binding or alternative method

Is it feasible to dynamically alter a sass variable using data-binding? For instance, I am seeking a way to modify the color of a variable through a button click. I am considering alternative approaches apart from relying on Knockout.js. $color: red; ...

Struggling to update the previousCode state with the useState hook in React

I'm having trouble understanding why the state isn't changing when using setPreviousCode in React and JavaScript. I'm trying to store the previously scanned text in the variable previousCode. import React, { useEffect, useState } from " ...

Using discord.js to conveniently set up a guild along with channels that are equipped with custom

When Discord devs introduced this feature, I can't seem to wrap my head around how they intended Discord.GuildManager#create to function. How could they possibly have expected it to work with Discord.GuildCreateOptions#channels[0], for instance, { ...

Updating lodash when it depends on jshint: A guide to NPM

After successfully passing an audit in npm, I received the following results: Now, I am attempting to update my lodash package but I'm unsure of the correct method to do so. I attempted using npm -i --save lodash, however this created another package ...

Switch between a list of labels dynamically with checkboxes in React

I'm currently working on a React component that displays an array of cars. I want to show a list of labels with the names of all diesel cars by default, and then have a checkbox that, when clicked, toggles to show all cars. interface ICars { name ...

Which specific html container or element can be found on the mymsn pages?

When accessing mymsn, users have the ability to personalize the content and layout of their webpage. I am curious about what type of container is being utilized for this customization - does it involve an html element, or perhaps javascript, or something e ...

Modify the color of every element by applying a CSS class

I attempted to change the color of all elements in a certain class, but encountered an error: Unable to convert undefined or null to object This is the code I used: <div class="kolorek" onclick="changeColor('34495e');" style="background-c ...

Challenges with fading images using jQuery

I am currently working on animating a 5 image slideshow by creating a fading effect between the images rather than just switching abruptly. Here is my HTML structure: <div id="slides"> <ul class="pics"> <li><img src="imag ...

How to send out an Array and a Variable at the same time using socket.io

Currently expanding my knowledge with Node.js, Express.js, and Socket.io. I successfully created a chat application that is functional at the moment. Now I am interested in letting the Client know when a user enters or exits the chat by emitting a variab ...

Exploring the properties of individual Vue components on a single page with v-for loop

Struggling to render a Vue component in a Rails app by iterating through an array of data fetched via Ajax. The Slim template (index.html.slim) for the index page includes a custom_form_item component, where items represent custom forms data from Rails and ...

Using VueMultiselect with Vue 3: A guide for beginners

I'm currently experimenting with the vue multiselect component, but when I include it in the template, I am encountering a series of warnings and errors. <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email ...