Skip to content

Could not find a valid element for given id or classname #418

Open
@ismail-trailfive

Description

@ismail-trailfive

i have next js project and i embeed react-email-editor and when i navigate to the edit page and load the template . first time the template will be loaded but when i refresh the template 2 to 3 three times it give this error Could not find a valid element for given id or classname.
here is my code :
"use client"
import { useParams, useRouter } from 'next/navigation'
import React, { useEffect, useRef, useState } from 'react'
import Button from '../Button/Button'
import EmailEditor, { EmailEditorProps,EditorRef } from 'react-email-editor';
import { useMutation, useQuery } from '@tanstack/react-query';
import { getUserTemplateById, updateTemplate } from '@/services/templates/templates';
import axios from 'axios';
import { API_URL, config } from '@/services/api/api';
import Modal from '../Modal/Modal';
import Loader from '../Loader/Loader';
import Toaster from '../Toaster/Toaster';

type Props = {}

const EditTemplate = (props: Props) => {
const params = useParams()
const router = useRouter()
const { templateid } = params
const TemplateId = Array.isArray(templateid) ? templateid[0] : templateid;
const emailEditorRef: any = useRef<EditorRef | null>(null);
const [openModal, setOpenModal] = useState(false)
const [templateData, setTemplateData] = useState({
name:"",
description:""
})
console.log("EditorRef", emailEditorRef)

const { data, error, isFetching, isLoading, refetch, status, isFetched } =
    useQuery({
        queryKey: ["GetUserTemplate", TemplateId],
        queryFn: () => getUserTemplateById(TemplateId),
        enabled: false,
    });

useEffect(() => {
    refetch();
}, [TemplateId]);

useEffect(() => {
    if(status === "success"){
       setTemplateData({
        name: data?.data?.data?.name,
        description: data?.data?.data?.description
       })
    } else if (status === "error") {
        console.log("error", error);
    }
},[status,error,data])

const {mutate,isPending,reset} = useMutation({
    mutationFn:updateTemplate,
    onSuccess(data) {
        console.log("updated",data)
        Toaster("Template Update Successfully","success")
        router.back()
    },
    onError(error) {
        reset()
        console.log("error",error)
    },
})

const exportHtml = (e: any) => {
    e.preventDefault();

    emailEditorRef.current.editor.exportHtml((data: any) => {
        const { design, html } = data;
        console.log('exportHtml', html);
        console.log('designJson', design);

        // Ensure UTF-8 encoding
        const utf8Html = unescape(encodeURIComponent(html)); // Convert to a safe format
        const encodeHtml = btoa(utf8Html); // Base64 encode

        mutate({
            body: encodeHtml,
            design_json: JSON.stringify(design),
            template_id: TemplateId,
            ...templateData
        });
    });
};

useEffect(() => {
    const loadDesignAsync = async () => {
        if (data && emailEditorRef?.current) {
            try {
                console.log("in")
                console.log("data", data)
                console.log("IN emailEditorRef", emailEditorRef)

                const parsedDesignJson = JSON?.parse(data?.data?.data?.design_json);
                await emailEditorRef?.current?.editor?.loadDesign(parsedDesignJson);
            } catch (error) {
                console.log("out")
                console.error("Error loading design:", error);
            }
        }
    };
    loadDesignAsync()
}, [data]);


const onReady = () => {
    // editor is ready
    console.log('onReady');
};

return (

      <div className='w-full flex justify-end mb-4'>
          <Button text='Save Template' variant='secondary' clicked={() => setOpenModal(true)}  />
      </div>

      <EmailEditor
          key="email-editor"
          ref={emailEditorRef}
          onReady={onReady}
          style={{ border: "1px solid gray", borderRadius: "8px", overflow: "hidden" }}
          minHeight={"750px"}
      /> 

    
  </div>

)
}

export default EditTemplate

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions