I am making a text editor using ReactQuill for iOS, however I keep on getting this issue- Unable to resolve module ‘react-dom.js’

My code:

    import React from "react";
    import ReactQuill from 'react-quill'
    import 'quill/dist/quill.snow.css'

    const Article = () => {
  
      var modules = {
        toolbar: [
          [{ size: ["small", false, "large", "huge"] }],
          ["bold", "italic", "underline", "strike", "blockquote"],
          [{ list: "ordered" }, { list: "bullet" }],
          ["link", "image"],
          [
            { list: "ordered" },
            { list: "bullet" },
            { indent: "-1" },
            { indent: "+1" },
            { align: [] }
          ],
          [{ "color": ["#000000", "#e60000", "#ff9900", "#ffff00", "#008a00", "#0066cc", "#9933ff",       "#ffffff", "#facccc", "#ffebcc", "#ffffcc", "#cce8cc", "#cce0f5", "#ebd6ff", "#bbbbbb", "#f06666", "#ffc266", "#ffff66", "#66b966", "#66a3e0", "#c285ff", "#888888", "#a10000", "#b26b00", "#b2b200", "#006100", "#0047b2", "#6b24b2", "#444444", "#5c0000", "#663d00", "#666600", "#003700", "#002966",   "#3d1466", 'custom-color'] }],
        ]
      };

      var formats = [
        "header", "height", "bold", "italic",
        "underline", "strike", "blockquote",
        "list", "color", "bullet", "indent",
        "link", "image", "align", "size",
      ];

      const handleProcedureContentChange = (content) => {
        console.log("content---->", content);
      };

      return (
         <div >
          <h1 style={{ textAlign: "center" }}>Text Editor In React JS</h1>
          <div style={{ display: "grid", justifyContent: "center"}}>
            <ReactQuill
              theme="snow"
              modules={modules}
              formats={formats}
              placeholder="write your content ...."
              onChange={handleProcedureContentChange}
              style={{ height: "220px" }}
            >
            </ReactQuill>
          </div>
        </div>

     );

    }

    export default Article;

I first imported react-dom.js by accident, and ever since, its giving out an error saying it cannot resolve the module, i deleted it from package.json, but the problem still persists.
I also tried to import quill/dist/quill.snow.css, but Snack is unable to resolve the dependency. I am running the code on expo v48.0.0, since the newer versions do not work on iOS.
i am expecting the output to be something like this:
Text editor, expected output

HTMX: Page position changed undesirably when I manually trigger the event

I need to update table content when some events happen. To do this, I manually trigger the event with the htmx.trigger() command. After this, the table successfully updated, but the position (vertical scroll) was undesirably shifted to the new position. However, if I try to use the straightforward htmx button (for test purposes), then the update is performed without shifting.

Backend is django, and I have double-checked that the response is the same in all cases.

Further, I show a demo and my code. For this demo-test I placed three buttons above the table:

  • first button with straightforward hx- commands;
  • second with htmx.trigger() in js
  • third with dispatchEvent() in js

In the first column, I place a random string, so we can see the table is updating every time we click the buttons.

enter image description here

As you can see, common htmx request do not shift the table. But after a request with an event fired from javasript, page position is shifted.

There is my code:

True-HTMX reload

<button class="btn btn-primary"
        hx-get="{% url 'orders:operation_inline_table' orderid %}"
        hx-target="#op-table">
    TRUE-HTMX RELOAD
</button>

Reload with htmx.trigger

<button id="tst2" class="btn btn-primary">
    RELOAD WITH htmx.trigger
</button>
<script>
    buttonRef = document.getElementById('tst2')
    buttonRef.addEventListener("click", function() {
        htmx.trigger(htmx.find('body'), 'operationTableRefresh')
    }, false);
</script>

Reload with dispatchEvent

<button id="tst3" class="btn btn-primary">
    RELOAD WITH dispatchEvent
</button>
<script>
    buttonRef = document.getElementById('tst3')
    buttonRef.addEventListener("click", function() {
        const elem = document.querySelector("body");
        elem.dispatchEvent(new Event('operationTableRefresh'));
    }, false);
</script>

Table container:

<div class="...">
    <h4>Operations</h4><br>

    <table id="op-table" class="table table-bordered"
           hx-get="{% url 'orders:operation_inline_table' orderid %}"
           hx-trigger="load, operationTableRefresh from:body">
    </table>
</div>

Question

So, my question is: how do I make the page not move after manual htmx triggering?

There is a problem reaching the app – SDK initialization timed out

Trying to publish a new manifest on our app to the store. When the MS people from India are trying to validate they are getting “There is a problem reaching the app”.

They use the same APP as in production to test the manifest so all of our customer is using the same “code”.

The teams application is written in Vue SPA.
After loading Vue i do:

await this.microsoftTeams.app.initialize();
and directly after this.microsoftTeams.appInitialization.notifyAppLoaded();

Before i had Vue loading after initialize() and after Vue was finished loading i did notifyAppLoaded() but it did not change anything to any of this and none of our customers has any issues about this.

Only change thing changed in manifest is that i have added “showLoadingIndicator”: true

I could see the error on their video and its “SDK initialization timed out”.
Is there anything i can do to fix this?
I have the same manifest on my local dev app and on our test setup for x amount of people to use/test and none of us has this issue with same manifest.

Cannot reproduce in any way im kinda lost here. Anyone had this issue?

react-admin pass props Main->layout->appBar

I have a react-admin app to manage users. Now I need to access some props in the custom header (appBar) that I created, but can’t figure out how to get those accessible there.

Here some of the code.

Main.js

class Main extends React.Component
{

  render()
  {
    // const { }   = this.state;
    const { t } = this.props;
    const _this = this;

    return (
      <Admin dataProvider={dataProvider} {..._this.props.props} layout={CustomLayout}>
        <Resource name="users"
                  list={<UserList {..._this.props.props} />}
                  edit={<UserEdit {..._this.props.props} />}
                  create={<UserCreate {..._this.props.props} />}
        />
      </Admin>
    );
  }
}

export default Main;

From above code CustomLayout

const CustomLayout = (props) => <Layout
  {...props}
  appBar={Header}
  sidebar={Sidebar}
/>;

export default CustomLayout;

From above code Header

class Header extends React.Component {


  // ---> Lifecycle functions <---

  constructor(props)
  {
    super(props);

    // Here I need to access props... 
    
    this.selectCustomer = this.selectCustomer.bind(this);

    this.state = {
      selectedCustomerId: this.props.selectedCustomerId,
    };
  }


    return (
      <div>...</div>
    );
  }
}


export default Header;

How do I get props from Main -> CustomLayout -> Header? If in CustomLayout.js I change appBar={Header} to appBar={<Header {...props} />}, I get Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

I guess it needs to be the component-name. Is there any way to achieve this?

draggable issue it’s not working in Next js React js

Hi i have used to draggable lib in my Next js 14 version but it’s not working can any help suggest me to what is error of this code

we call to this components

{
            openPersonaliseModal ? <PersonaliseModel  openPersonaliseModal={openPersonaliseModal} data={data} setOpenPersonaliseModal={setOpenPersonaliseModal}/> : ""
        }

and my componets data is

   "use client"
import styles from './PersonaliseModel.module.scss';
import {useRef, useEffect, useState} from "react";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";


const PersonaliseModel = ({setOpenPersonaliseModal, openPersonaliseModal, data}:any)=>{
    const dataLis = data && data.length > 0 ? data : [];
    const [listData, setListData] = useState(dataLis);
    const popupRef = useRef<HTMLDivElement | null>(null);
    const handleOnDragEnd = (result:any) => {
        console.log('result',result)
        if (!result.destination) return; // Dropped outside the list
    
        const updatedListData = [...listData];
        const [movedItem] = updatedListData.splice(result.source.index, 1);
        updatedListData.splice(result.destination.index, 0, movedItem);
    
        // Update order IDs
        updatedListData.forEach((item, index) => {
          item.order = index + 1;
        });
        console.log(updatedListData);
        setListData(updatedListData);
    };
    const handleClickOutside = (event:any) => {
        if (popupRef.current && !popupRef.current.contains(event.target)) {
          setOpenPersonaliseModal(false);
        }
      };
  
      const handleEscapeKey = (event:any) => {
        if (event.key === 'Escape') {
          setOpenPersonaliseModal(false);
        }
      };
    useEffect(() => {
        if (openPersonaliseModal) {
          document.addEventListener('mousedown', handleClickOutside);
          document.addEventListener('keydown', handleEscapeKey);
        }
        return () => {
          document.removeEventListener('mousedown', handleClickOutside);
          document.removeEventListener('keydown', handleEscapeKey);
        };
      }, [openPersonaliseModal]);
    return (
        <div className={styles.wraper}>
            <div className={styles.perWrap} ref={popupRef} >
                <div className={styles.header}>
                    Personalise Your View
                </div>
                <div className={styles.body}>
                    <div className={styles.topHeader}>
                        <span className={styles.leftTxt}>Default Views</span>
                        <span className={styles.createBtn}>Create New View</span>
                    </div>
                    <div className={styles.bodySec}>
                        {
                            listData.length > 0 ? <DragDropContext onDragEnd={handleOnDragEnd}>
                            <Droppable droppableId="list" key={listData.length}>
                                {(provided:any= {}, snapshot:any = {}) => (
                                <ul {...provided.droppableProps} ref={provided.innerRef} className="list">
                                    {listData.map((list:any, index:any) => {
                                      return (
                                        <Draggable key={`${list.viewId}-${index}`} draggableId={`${list.viewId}-${index}`}  index={index}>
                                            {(provided:any = {}) => {
                                              return (
                                                <li
                                                    ref={provided.innerRef} 
                                                    {...provided.draggableProps} 
                                                    {...provided.dragHandleProps}
                                                    >
                                                    <span className={styles.itemTxt}>{list.name}</span>
                                                    <span className={styles.removeItem}></span>
                                                </li>
                                              )
                                            }}
                                        </Draggable>
                                      )
                                    })}
                                    {provided.placeholder}
                                </ul>
                                )}
                            </Droppable>
                        </DragDropContext> : ""
                        }
                        
                    </div>
                </div>
                <div className={styles.footer}>
                    <span className={styles.updateBtn}>Save Changes</span>
                </div>
            </div>
        </div>
    )
}

export default PersonaliseModel;

and in console we show to this error of type

app-index.js:35 Warning: Connect(Droppable): Support for defaultProps will be removed from memo components in a future major release. Use JavaScript default parameters instead.

enter image description here

and also set to my element some class dragable
enter image description here

console.js:213 react-beautiful-dndUnable to find draggable with id: 240-1

Simple express-mongoose functions

I’m trying to create a simple API using express and mongoose to query and process data from Mongo DB.

and from front end I’ll use axios to call this and return the result and based on this result I’ll route the app.

I created below simple function and it works as expected it fetches the object if it exists in the DB,
and return the object, but now I would like to assign this to a variable and compare the result? how to do it ?

Login

async function login(username,password){
    try{
        mongoose.connect('mongodb://localhost:27017/test');
        const query=await UserModel.findOne({username:username, password:password});
        
        mongoose.connection.close();
        console.log(query);
    }
    catch(error){
        console.log(error);
    }
}

assuming this user exist in the db it will return the object like this:

{
  _id: new ObjectId('65b9db9578f42ed5f3fa685e'),
  username: 'userxyz',
  password: '123456',
  __v: 0
}

but how to validate this if I assign to variable and compare with with passed user name and password it returns:Promise { <pending> }, what is best way to achieve this? because I couldn’t assign this function to variable and check it results to perform input validation

How to extract a lot of env variable in terms of array in Javascript? [duplicate]

I have more than 10 API account and keys stored in .env

My .env:

API_ACCOUNT_1="11111"
API_SECRET_1="12121"

API_ACCOUNT_2="22222"
API_SECRET_2="232323"

API_ACCOUNT_3="33333"
API_SECRET_3="343434"

API_ACCOUNT_4="44444"
API_SECRET_4="454545"
...

What I want to achieve but not working:

import dotenv from "dotenv"

dotenv.config()

let accountInfo = []

for (let i = 1; i < 6; i++){
    // it is not the correct syntax
    accountInfo.push([process.env.`'API_ACCOUNT_${i}'`, process.env.`'API_SECRET_${i}'`])  
}

Keyboard does not appear on iOS when use setTimeout in html

I am experiencing an issue when running a script on Safari, specifically WebKit. Here is a sample HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <script>
        function delayedFocus(e) {
            e.preventDefault();
            setTimeout(function() {
                e.target.focus();
            }, 1000); // Adjust the delay time as needed (in milliseconds)
        }
    </script>
</head>
<body>
    <ul>
        <li>
            <input type="text" id="testtext" onmousedown="delayedFocus(event)">
        </li>
    </ul>
</body>
</html>

The logic behind this script is to introduce a 1-second delay when the user clicks on the textbox. After 1 second, the keyboard should appear. Testing on Android mobile devices shows the expected behavior. However, on iPhones, the textbox receives focus, but the keyboard does not appear. This issue has been observed on various iOS versions, with the script working only on iOS 15.

If you have any insights or solutions to address this compatibility issue, it would be greatly appreciated. Thank you.

How to use querySelectorAll to select classes in a section div rather than the whole page?

Let say I have the following code:

let testA = document.querySelectorAll('.vehicle')

Let say I have this html

<div class="vehicle">
// some stuff
</div>

<div class="vehicle">
// some stuff
</div>

I know querySelectorAll will select all the classes on the page but is there a way to use querySelectorAll to just select the items from the first vehicle div class to do something. Then use querySelectorAll from the second vehicle div class to do something?

I’m setting the category as the url in django and i’m getting error that ‘;’ expected.javascript

I’m setting the category as the url in django and i’m getting error that ‘;’ expected.javascript

{% for category in all_categories %}
    <div onclick="location.href='{% url 'category' category.category %}';"
        style="box-shadow:0 5px 30px 0 rgba(0,0,0,.05);"
        class="hover:scale-105 hover:transform transition duration-300 cursor-pointer bg-gray-900 rounded-lg h-40 w-full my-4 text-center p-5 grid place-items-center">
        <div>
            <p class='text-4xl my-2'><i
                    class="bi bi-tags text-transparent bg-clip-text bg-gradient-to-r from-cyan-200 to-blue-500"></i>
            </p>
            <p class='text-base'>{{ category.category }}</p>
        </div>
    </div>
    {% endfor %}

Updating state when some prop changes without useEffect

I’ve come across React’s recommendation to avoid using useEffect for internal React updates. While the suggested solutions in the link work, they might be challenging to manage and extend.

Currently, I’m using below hook, and it seems to be working well. However, I’m unsure if there are any performance advantages to using useEffect or if there are better solutions available. Could someone provide insights or recommendations, please?”

const shouldUpdate = (dependencies = [], prevDependencies = []) => {
  if (!prevDependencies) return true;
  if (!dependencies.length) return false;

  for (const index in dependencies) {
    if (!Object.is(dependencies[index], prevDependencies[index])) return true;
  }

  return false;
};

export function useMyEffect(callBack, dependencies = [], shouldRunFirstTime = true) {
  const [prevDependencies, setPrevDependencies] = useState(() =>
    shouldRunFirstTime ? null : dependencies
  );

  if (shouldUpdate(dependencies, prevDependencies)) {
    callBack();
    setPrevDependencies([...dependencies]);
  }
}

string of only numbers as FontFace() family value not parsed correctly

If font.newFileName in new FontFace and setProperty is changed to an arbitrary string, say 'x' for example, the script below works. Therefore, I know the issue has something to do with the value of font.newFileName or the way in which it is being parsed.

...

fontList.forEach(font => {

  const
    ff = new FontFace(font.newFileName, `url('${font.newFilePath.replace(/\/g, '/')}')`),
    fontItem = fontItemTemplate.content.cloneNode(true),
    fontNameElement = fontItem.querySelector('.font-name')

  ff.load().then(
    () => document.fonts.add(ff),
    err => console.error('ERROR:', err)
  )

  fontNameElement.style.setProperty('--font-family', font.newFileName)
  fontNameElement.style.fontFamily = 'var(--font-family)'

  ...

font.newFileName is a string, but strings of numbers: 000001101, 000001102, 000001103, so on and so forth.

Does anybody know what is preventing these values from being parsed correctly?

I’ve coded an email contact using Node.js. “It works on my machine,” but not on Vercel

I created this email contact form for my portfolio using a form to send the inputted information to the specific code in the Node server that sends the email using Nodemailer. “It works on my machine”, but on Vercel, it’s not functioning. My routes are entirely correct and working, but they are not working on Vercel, and I don’t know why.

These are my HTML forms (“/enviar-email” means “/send-email”):

<section id="contact">
    <header id="contact-header"></header>
    <form id="contactForm" action="/enviar-email" method="POST">
        <h2>Converse Comigo!</h2>
        <label for="userName">Seu nome:</label>
        <input type="text" name="userName" id="userName" placeholder="Gustavo Faustino">
        <label for="userEmail">Seu e-mail:</label>
        <input type="email" name="userEmail" id="userEmail" placeholder="[email protected]">
        <label for="userMessage">Escreva sobre o que quiser:</label>
        <textarea name="userMessage" id="userMessage" cols="30" rows="10" placeholder="..."></textarea>
        <button type="submit">Contactar</button>
    </form>
    <span>Pode contar com uma resposta rápida</span>
</section>

This is my code for sending the email in Node:

app.post('/enviar-email', (req, res) => {
    const userName = req.body.userName;
    const userEmail = req.body.userEmail;
    const userMessage = req.body.userMessage;

    const transporter = nodemailer.createTransport({
        service: "gmail",
        host: "smtp.gmail.net",
        port: 465,
        secure: true,
        auth: {
            user: process.env.STANDARD_EMAIL,
            pass: process.env.APP_PASSWORD,
        },
        tls: {
            rejectUnauthorized: false
        }
    });

    const mailOptions = {
        from: {
            name: userName,
            address: userEmail
        },
        to: [process.env.STANDARD_EMAIL],
        subject: "E-mail do Portfólio!",
        html: `<b>Email do Sender (Remetente):</b> ${userEmail} <br/> ${userMessage}`,
    }

    const sendMail = async (transporter, mailOptions) => {
        try {
            await transporter.sendMail(mailOptions)
            console.log('email has been sent')
            res.redirect('/agradecimento');
        } catch (error) {
            console.error(error)
        }
    }
    sendMail(transporter, mailOptions)
})

I’m attempting to use the ‘Vercel rewrite,’ but it doesn’t assist in sending the email and navigating to the thank-you page with the /agradecimento (thanks) route.

This is my vercel.json

{
  "rewrites": [
    {
      "source": "/enviar-email",
      "destination": "/enviar-email"
    },
    {
      "source": "/agradecimento",
      "destination": "/thank-you.html"
    }
  ]
}

There are no logs in vercel console, but this is what I get when clicking to send the info. A 404 error

Could someone help me understand what might be causing this issue?

Cannot read properties of undefined (reading ‘_context’) using tRPC with getUserFiles in React component

I’m encountering an error “Cannot read properties of undefined (reading ‘_context’)” when using the getUserFiles procedure from my tRPC client within a React component. I should be able to get the correct type for my data but it gives “any”. The error occurs on my Dashboard, specifically, on my const { data: files, isLoading } = trpc.getUserFiles.useQuery();

Prisma schema where I define my files

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider  = "postgresql"
  url       = env("DATABASE_URL")
  directUrl = env("DIRECT_URL")
}

model User {
  id    String @id @unique
  email String @unique

  File File[]

  stripeCustomerId       String?   @unique @map(name: "stripe_customer_id")
  stripeSubscriptionId   String?   @unique @map(name: "stripe_subscription_id")
  stripePriceId          String?   @map(name: "stripe_price_id")
  stripeCurrentPeriodEnd DateTime? @map(name: "stripe_current_period_end")
}

enum UploadStatus {
  PENDING
  PROCESSING
  FAILED
  SUCCESS
}

model File {
  id   String @id @default(cuid())
  name String

  uploadStatus UploadStatus @default(PENDING)
  url          String
  key          String

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  User   User?   @relation(fields: [userId], references: [id])
  userId String?
}

Here’s my getUserFiles

import { db } from "@/db";
import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
import { TRPCError } from "@trpc/server";
import { privateProcedure, publicProcedure, router } from "./trpc";

export const appRouter = router({
  authCallback: publicProcedure.query(async () => {
    // Get the user from the KindeServer session
    const { getUser } = getKindeServerSession();
    const user = await getUser();

    // If the user is not authenticated, throw an error
    if (!user || !user.id || !user.email)
      throw new TRPCError({ code: "UNAUTHORIZED" });

    // check if the user is in the database
    const dbUser = await db.user.findFirst({
      where: {
        id: user.id,
      },
    });

    if (!dbUser) {
      // create user in db
      await db.user.create({
        data: {
          id: user.id,
          email: user.email,
        },
      });
    }

    // Check if user exists in the database
    return { success: true };
  }),

  // Get user files from the database
  getUserFiles: privateProcedure.query(async ({ ctx }) => {
    // Extract the user ID from the context
    const { userId } = ctx;

    // Query the database for files belonging to the user
    return await db.file.findMany({
      where: {
        userId,
      },
    });
  }),
});

export type AppRouter = typeof appRouter;

Here’s my private procedure

import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
import { TRPCError, initTRPC } from "@trpc/server";

const t = initTRPC.create();
const middleware = t.middleware;

const isAuth = middleware(async (opts) => {
  const { getUser } = getKindeServerSession();
  const user = await getUser();

  if (!user || !user.id) {
    throw new TRPCError({ code: "UNAUTHORIZED" });
  }

  return opts.next({
    ctx: {
      userId: user.id,
      user,
    },
  });
});

export const router = t.router;
export const publicProcedure = t.procedure;
export const privateProcedure = t.procedure.use(isAuth);

Here’s where the error occurs

import { trpc } from "@/app/_trpc/client";
import UploadButton from "./UploadButton";
import { Ghost } from "lucide-react";

const Dashboard = () => {
  const { data: files, isLoading } = trpc.getUserFiles.useQuery();

  return (
    <main className="mx-auto max-w-7xl md:p-10">
      <div className="mt-8 flex flex-col items-start justify-between gap-4 border-b border-gray-200 pb-5 sm:flex-row sm:items-center sm:gap-0">
        <h1 className="mb-3 font-bold text-5xl text-gray-900">My Files</h1>

        <UploadButton />
      </div>

      {/* Display All User Files */}
      {files && files?.length !== 0 ? (
        <div></div>
      ) : isLoading ? (
        <div></div>
      ) : (
        <div className="mt-16 flex flex-col items-center gap-2">
          <Ghost className="h-8 text-zinc-800" />
          <h3 className="font-semibold text-xl">
            Let&apos;s upload your first PDF.
          </h3>
        </div>
      )}
    </main>
  );
};

export default Dashboard;

Issue with Height Increase in jquery.prettyPhoto.js After Upgrading jQuery from 1.4.2 to 1.9.0

After upgrading jQuery from version 1.4.2 to 1.9.0, I successfully resolved all the issues in my application, except for one related to jquery.prettyPhoto.js. The problem I’m facing is the height of the element increases dramatically, causing layout issues.

I have attempted to debug the issue by inspecting elements and checking the console for errors. I have temporarily rolled back to jQuery 1.4.2 to confirm that the issue is specific to the jQuery upgrade.

I am seeking assistance from the community to identify the root cause of this height increase issue with jquery.prettyPhoto.js after upgrading from jQuery 1.4.2 to 1.9.0.

enter image description here enter image description here

References:
https://github.com/scaron/prettyphoto

Any insights, suggestions, or solutions would be greatly appreciated.

Thank you in advance for your help!