I am using a Next.js app where users can upload images through an API, and the API returns the images to me in an array. I am trying to figure out how

Instead of using CKEditor to upload images, I have implemented my own API for image uploading.

When a user uploads an image on my website, I make a call to the API to safely upload the image and return a URL in the Public Domain. The API returns the following object:

{
    "uploadedUrls": [
        "http://example.com/community/question/insta.jpg",
        "http://example.com/community/question/pin.jpg"
    ]
}

In my Next.js website, the function behind the API works as follows:

  const handleUpload = async () => {
  const fileInput = document.getElementById('file-upload'); 
  if (fileInput && fileInput.files.length > 0) {
    const formData = new FormData();
    const files = Array.from(fileInput.files);

    files.forEach((file, index) => {
      formData.append("files", fileInput.files[index], file.name);
    });

    formData.append("folderName", "community/question");

    try {
      const uploadImage = await communityDTO.uploadImage(formData);
      if (uploadImage) {
        if (typeof uploadImage.uploadedUrls === 'string') {
            uploadImage.uploadedUrls = [uploadImage.uploadedUrls];
        }
        console.log(uploadImage); //This functionality is working perfectly fine
        uploadImage.uploadedUrls.map((item)=>(
            setInputBody(inputBody + "\n" + 
                <img className="my-2" src={item} alt={"Image " + item} />
            ))
        );
      }
    } catch (error) {
      console.error('Error:', error);
    }
  } else {
    console.error('No files selected');
  }
};

I receive successful results from console.log(uploadImage) in my console.

Here is how my CKEditor configuration looks like:

<CKEditor
    editor={ClassicEditor}
    data={inputBody}
    onChange={(event, editor) => {
    const data = editor.getData();
    setInputBody(data); //inputBody uses useState hook
    }}
    config={{
    toolbar: {
        items: [
        "undo",
        "redo",
        "|",
        "bold",
        "italic",
        "blockQuote",
        "link",
        "numberedList",
        "bulletedList",
        "|",
        "heading",
        ],
        shouldNotGroupWhenFull: true,
    },
    placeholder: "Write your Answer...",
    }}
/>

Everything is functioning correctly, and here is how I have declared inputBody:

const [inputBody, setInputBody] = useState("");

Whenever I upload an image, it should be embedded in CKEditor even if multiple images are uploaded...

After successfully uploading an image through the API, I update the inputBody using the following code:

uploadImage.uploadedUrls.map((item)=>(
   setInputBody(inputBody + "\n" + 
      <img className="my-2" src={item} alt={"Image " + item} />
   ))
);

However, instead of embedding the image, I am getting the result as shown in this output image: Output Image

The result I get is displayed as [object Object], rather than showing the image.

(I now understand how stackoverflow handles image uploading using this format [description](imageurl)). It would be great if the free version of CKEditor supports this feature. If it does, please suggest it to me. In the meantime, can you help me with my code above?

Answer №1

Error: Resolved

I managed to solve the issue on my own. The only modification I made was creating an instance of CKEditor using the useRef hook. Although I had tried this before and it didn't work, I forgot to mention it earlier...

Although the following code was provided by chatGPT, it still did not work for me:

const editor = editorRef.current.editor; // Access CKEditor instance from the ref
  uploadImage.uploadedUrls.forEach(url => {
   editor.model.change(writer => {
      const imageElement = writer.createElement('image', {
         src: url // Set the source URL for the image
      });
      editor.model.insertContent(imageElement);
   });
});

However, I modified the code myself within the editor instance:

const editor = editorRef.current.editor; // Access CKEditor instance from the ref

   uploadImage.uploadedUrls.forEach(url => {
      editor.model.change(writer => {
         editor.setData( `${inputBody} \n <img src=${url} alt=${url} />` );
   });
});

The above code is now functioning perfectly, even though I believe it may not be the most appropriate use of the writer object. Nevertheless, since it works, I have decided not to make any further changes to it...

Thank you StackOverflow

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

Using Angular Material for creating tabs with identical content

I am using material with angularjs and have encountered an issue with my two md-tabs. Both tabs have a similar DOM structure, but contain some unique content. Instead of duplicating the common DOM twice, I am looking for an alternative solution. Is it poss ...

JavaScript method to clear a variable

Can JavaScript prototype be used to add a method to a variable that is undefined? For instance, we can use the following code: var foo = "bar"; String.prototype.doTheFoo = function(){ console.log("foo is better than you"); }; foo.doTheFoo(); This c ...

Calling JavascriptInterface in an H5 environment is not permitted

Utilizing the power of vue, I created an immersive h5 page within the application framework. The seamless connection between the page and the app relies on the use of window.JSInterface for communication. My current challenge lies in invoking the JSInterfa ...

Encountering an issue following the installation and integration of an npm module within a Meteor

I recently started a project using the latest version of Meteor. I added a new package by running the command: meteor npm install --save name_of_package Since this package is meant for the client side, I created a file called mypackage.js inside the /cli ...

Improving the visualization of large GPS tracks on Google Earth Plugin

I need to display GPS routes on Google Earth using the Google Earth API. However, with approximately 20,000 points per route, the performance is not optimal. The code I have implemented successfully draws the tracks but struggles with rendering time and tr ...

How to eliminate spacing between slides in a 3D Carousel Slider using Bootstrap 5

My website utilizes Bootstrap along with a carousel slider, which is functioning properly. However, I am encountering an issue when the slider transitions from right to left. It briefly displays a white space between slides, which I wish to eliminate. I wa ...

Store additional data with the visitor ID WEB in Fingerprint JS V3

After browsing through similar questions, I couldn't find a solution that fits my needs. Basically, I have a website where a random emoji is generated and stored in local storage. However, this method is not effective as users can easily delete their ...

Leveraging AngularJS to enhance the dynamic HTML content within Datatables

My angular application includes a Datatable where I alter cell content to include HTML elements. In the given code snippet, I specifically modify the cell content of the 5th column to incorporate links. Additionally, I intend to implement a tooltip featur ...

Decoding GeoJSON: Extracting a feature from an array

I am currently working on a map project where I am drawing polygons with properties pulled from a JSON file. Each polygon is colored based on feature values in the JSON file. Here's an example of a feature in the JSON file: { "type": "Feature", " ...

Ways to automatically run Java script again when new elements are included in the document model

Recently, I added paging and filtering to a page displaying a list of products. @model ProductFiltersViewModel ... <div class="row"> <aside class="col-3"> <nav class="sidebar card py-2 mb-4"> ...

What is the best way to set a value for a variable within a UI component in React?

I'm still learning the ropes with React and JavaScript. My current challenge involves declaring a temporary variable and assigning the value of companyData.name to it, as I need to gather data from two variables like companyData.name. Below is my cod ...

Converting Emoji to PNG or JPG using Node.js - What's the Procedure?

Currently, I am working on a project that requires me to create an image file from emoji characters, preferably using Apple emoji. Initially, I thought this task would be simple to accomplish, but I have encountered obstacles with each tool I have tried. ...

Issues encountered when attempting to utilize removeEventListener() with multiple elements within a for loop in Javascript

After experimenting, I have been exploring ways to avoid encountering repeated event listeners The script provided below iterates through all buttons with a specific attribute. However, the issue is that it only functions effectively for a single button ...

Unable to process despite clicking button (no error messages)

I'm in the process of setting up an options page for my very first extension. As a beginner in coding, I might have made some rookie mistakes along the way. However, I am facing challenges with basic functionality that was previously working seamlessl ...

Adding the AJAX response to the specified element's ID

I'm having trouble inserting radio buttons into a <div> on my page using an AJAX response. The code I have looks like this: // AJAX form for updating tests after category selection $('#categories').change(function(){ category_id ...

I have the ability to generate a create-react-app, but unfortunately I lack the skill to

Has anyone encountered any difficulties when using the npx create-next-app [project name] command? I've been executing these commands in Visual Studio Code Terminal. While create-react-app works without any issues for me, I face an error whenever I ...

Display exclusively on indexes 0 and 3

Here is the code snippet I am working with: {(type === 'NEW') && ((index === 0) || (index === 3)) && <hr className={styles.hr}/>} I would like to combine these conditions into a single expression that w ...

The jQuery response appears blank in the browser, despite the fact that it works fine with

Utilizing jQuery's .ajax() function to communicate with a local Django runserver and retrieve a response. Observing the server console, the JSON request is received properly, a correct JSON response is generated, and all appears in order. However, i ...

How does NodeJs handle ongoing tasks and processes seamlessly?

One interesting concept is the Event Loop, which accepts callbacks and executes them as needed. As far as I understand, this operates on a single thread event loop, meaning only one callback is executed at a time. Consider the following example: setInterv ...

Showcase multiple examples of three.js on a single webpage

I need to showcase several 3D objects on my web app within different containers. Currently, I'm creating multiple three.js renderers, each for a separate container. However, I encountered an error message: "WARNING: Too many active WebGL contexts. Old ...