react quill TypeError: moduleClass is not a constructor

I’m trying to use react-quill in my nextJS project but am getting this error :


 1 of 1 unhandled error

Unhandled Runtime Error
TypeError: moduleClass is not a constructor

Call Stack
SnowTheme.addModule
node_modulesquilldistquill.js (6130:0)
SnowTheme.addModule
node_modulesquilldistquill.js (6774:0)
eval
node_modulesquilldistquill.js (6122:0)
Array.forEach
<anonymous>
SnowTheme.init
node_modulesquilldistquill.js (6120:0)
new Quill
node_modulesquilldistquill.js (1163:0)
ReactQuill.createEditor
node_modulesreact-quilllibindex.js (223:0)
ReactQuill.instantiateEditor
node_modulesreact-quilllibindex.js (187:0)
ReactQuill.componentDidMount
node_modulesreact-quilllibindex.js (152:0)
commitLifeCycles
node_modulesreact-domcjsreact-dom.development.js (20663:0)
commitLayoutEffects
node_modulesreact-domcjsreact-dom.development.js (23426:0)
HTMLUnknownElement.callCallback
node_modulesreact-domcjsreact-dom.development.js (3945:0)
Object.invokeGuardedCallbackDev
node_modulesreact-domcjsreact-dom.development.js (3994:0)
invokeGuardedCallback
node_modulesreact-domcjsreact-dom.development.js (4056:0)
commitRootImpl
node_modulesreact-domcjsreact-dom.development.js (23151:0)
unstable_runWithPriority
node_modulesschedulercjsscheduler.development.js (468:0)
runWithPriority$1
node_modulesreact-domcjsreact-dom.development.js (11276:0)
commitRoot
node_modulesreact-domcjsreact-dom.development.js (22990:0)
performSyncWorkOnRoot
node_modulesreact-domcjsreact-dom.development.js (22329:0)
eval
node_modulesreact-domcjsreact-dom.development.js (11327:0)
unstable_runWithPriority
node_modulesschedulercjsscheduler.development.js (468:0)
runWithPriority$1
node_modulesreact-domcjsreact-dom.development.js (11276:0)
flushSyncCallbackQueueImpl
node_modulesreact-domcjsreact-dom.development.js (11322:0)
flushSyncCallbackQueue
node_modulesreact-domcjsreact-dom.development.js (11309:0)
scheduleUpdateOnFiber
node_modulesreact-domcjsreact-dom.development.js (21893:0)
dispatchAction
node_modulesreact-domcjsreact-dom.development.js (16139:0)
checkForUpdates
node_modulesuse-subscriptioncjsuse-subscription.development.js (85:0)
eval
node_modulesnextdistsharedlibloadable.js (183:44)
Set.forEach
<anonymous>
LoadableSubscription._update
node_modulesnextdistsharedlibloadable.js (183:24)
eval
node_modulesnextdistsharedlibloadable.js (164:17)

and here is the code shows how imported It and how I rendered it :

import React, { useState, useEffect, useCallback } from 'react';
import 'react-quill/dist/quill.snow.css';
import { Box, TextField, Button, Typography, Input } from '@mui/material';
import { getStorage, ref, uploadBytes, getDownloadURL } from 'firebase/storage';
import { getFirestore, collection, addDoc } from 'firebase/firestore';
import dynamic from 'next/dynamic';

const ReactQuill = dynamic(() => import('react-quill'), { ssr: false, loading: () => <p>Loading...</p> });
const Quill = dynamic(() => import('react-quill'), { ssr: false, loading: () => <p>Loading...</p> });
const ImageUploader = dynamic(() => import('quill-image-uploader'), { ssr: false, loading: () => <p>Loading...</p> });

const CreatePost = () => {
  const [titles, setTitles] = useState({
    title_ar: '',
    title_en: '',
    title_fr: '',
    title_tr: '',
  });
  const [body, setBody] = useState('');
  const [mainImage, setMainImage] = useState(null);
  const [uploading, setUploading] = useState(false);

  const storage = getStorage();
  const db = getFirestore();

  useEffect(() => {
    if (Quill && Quill.register) {
      Quill.register('modules/imageUploader', ImageUploader);
    }
  }, []);

  const handleTitleChange = useCallback((e) => {
    const { name, value } = e.target;
    setTitles((prevTitles) => ({ ...prevTitles, [name]: value }));
  }, []);

  const handleEditorChange = useCallback((content) => {
    setBody(content);
  }, []);

  const handleMainImageChange = (e) => {
    setMainImage(e.target.files[0]);
  };

  const uploadImage = async (image) => {
    if (!image) {
      throw new Error('No image provided');
    }
    
    const storageRef = ref(storage, `images/${image.name}`);
    await uploadBytes(storageRef, image);
    return getDownloadURL(storageRef);
  };

  const uploadInBodyImage = async (image) => {
    if (!image) {
      return Promise.reject(new Error('No image provided'));
    }

    const storageRef = ref(storage, `images/${image.name}`);
    return uploadBytes(storageRef, image).then(() => {
      return getDownloadURL(storageRef).then((url) => {
        return url;
      });
    }).catch((error) => {
      console.error('Error uploading image or getting URL:', error);
      throw error;
    });
  };

  const modules = {
    toolbar: [
      [{ 'header': '1'}, {'header': '2'}, { 'font': [] }],
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      ['bold', 'italic', 'underline'],
      ['link', 'image'],
      ['clean']
    ],
    imageUploader: {
      upload: async (file) => {
        try {
          const url = await uploadInBodyImage(file);
          return url;
        } catch (error) {
          console.error('Image upload failed:', error);
          throw error;
        }
      },
    },
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setUploading(true);

    try {
      let mainImageUrl = '';
      if (mainImage) {
        mainImageUrl = await uploadImage(mainImage);
      }

      await addDoc(collection(db, 'Article'), {
        ...titles,
        body,
        mainImageUrl,
        createdAt: new Date(),
      });

      alert('Article created successfully!');
      setTitles({
        title_ar: '',
        title_en: '',
        title_fr: '',
        title_tr: '',
      });
      setBody('');
      setMainImage(null);
    } catch (error) {
      console.error('Error creating article:', error);
      alert('Failed to create article.');
    } finally {
      setUploading(false);
    }
  };

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h5" gutterBottom>Create a New Article</Typography>
      <form onSubmit={handleSubmit}>
        <Box mb={2}>
          <TextField
            fullWidth
            label="Title (Arabic)"
            name="title_ar"
            value={titles.title_ar}
            onChange={handleTitleChange}
            variant="outlined"
          />
        </Box>
        <Box mb={2}>
          <TextField
            fullWidth
            label="Title (English)"
            name="title_en"
            value={titles.title_en}
            onChange={handleTitleChange}
            variant="outlined"
          />
        </Box>
        <Box mb={2}>
          <TextField
            fullWidth
            label="Title (French)"
            name="title_fr"
            value={titles.title_fr}
            onChange={handleTitleChange}
            variant="outlined"
          />
        </Box>
        <Box mb={2}>
          <TextField
            fullWidth
            label="Title (Turkish)"
            name="title_tr"
            value={titles.title_tr}
            onChange={handleTitleChange}
            variant="outlined"
          />
        </Box>
        <Box mb={2}>
          <Typography variant="h6" gutterBottom>Body</Typography>
          <ReactQuill
            value={body}
            onChange={handleEditorChange}
            modules={modules}
            style={{ height: '400px' }}
          />
        </Box>
        <Box mb={2}>
          <Input
            type="file"
            accept="image/*"
            onChange={handleMainImageChange}
            fullWidth
          />
        </Box>
        <Button type="submit" variant="contained" color="primary" disabled={uploading}>
          {uploading ? 'Uploading...' : 'Create Article'}
        </Button>
      </form>
    </Box>
  );
};

export default CreatePost;

JS GC in closure

hi i have a query and was unable to get exact answer. I have a below closure function

function closure() {let innerVal; return function() {innerVal = innerVal+10}}
let inst = closure();
inst();
console.log('end');

will innerVal be cleared during GC after inst() is called or not?

Stripping HTML tags on a complex web page to retain just plain text

I want to check whether it’s possible to extract plain text from web pages such as this one:

https://www.homedepot.com/p/Acclaim-Lighting-Lily-3-Light-Polished-Nickel-Sconce-with-Fabric-Shade-and-Crystal-Accent-IN41050PN/306216165

I’m expecting to extract product-specific details from the page. I don’t mind if extraneous details are captured.

I tried various online platforms such as Strip HTML, but they don’t work.

Vertical scrollbar not visible but working in domLayout ‘autoHeight’

I was previously using ag grid v28 and now migrated to ag-grid v32.
I am using domLayout as ‘autoHeight’ in my gridOptions.
And in my styling I was given around 250px for .ag-body-viewport and overflow-y: auto; as given below.

.ag-body-viewport {
  height: 250px;
  overflow-y: auto;
  overflow-x: hidden;
}

But after upgrading, the vertical scroll is working but the scrollbar is hidden.
Someone help

Previously the vertical scrollbar was visible with same code in v28, there is nowhere mentioned about this in their upgrade notes.

If I give scrollbar-width: thin ! important;
I am able to see the thin scrollbar, but I am expecting the old behaviour

Right shift operator can change number sign

We can read about Right shift operator >> on MDN

… the sign of the resulting number is the same as the sign of the first operand.

However, 3332508426 >> 24 === -58 in my Chrome 127.0.6533.120.

How that could be explained?

By the way, 3332508426 is decimal representation of IP 198.162.11.10.

Webdriverio V9 : – Unable to upload file in headless mode

Recently I have updated from v8 to v9, and file upload was working fine in non-headless mode. But the same code fails in headless mode. It would be good, if anyone help on this.

    capabilities: [
        {
            maxInstances: 1,
            browserName: 'chrome',
            acceptInsecureCerts: true,
            'goog:chromeOptions': {
                args: [
                    'headless', 'disable-gpu',
                    '--window-size=1920,1080'
                ],
            },
        },

Code:

    async uploadFile(file) {
        const filePath = path.join(process.cwd(), DEFAULT_FILEPATH, file);
        console.debug("File path: ", filePath);
        const remoteFilePath = await browser.uploadFile(filePath);
        await fileuploadPage.inputFileUpload.setValue(remoteFilePath);
        await fileuploadPage.submitButton.click();
    }

log:

[0-0] RUNNING in chrome - file:///src/test/specs/sanitySuite/test.dscreation.sanity.js
[0-0] File path:  /home/mahadev/Desktop/WDIO_V9_upgrade/ui_automation/src/utilities/files/Reorder.csv
[0-0] Error in "Mammoth Data Source Creation Sanity Tests.File upload @sanity"
Error: The uploadFile command is not available in chrome-headless-shell
    at async Utils.uploadFile (file:///home/mahadev/Desktop/WDIO_V9_upgrade/ui_automation/src/utilities/utils.js:63:32)
    at async Context.<anonymous> (file:///home/mahadev/Desktop/WDIO_V9_upgrade/ui_automation/src/test/specs/sanitySuite/test.dscreation.sanity.js:98:9)
[0-0] FAILED in chrome - file:///src/test/specs/sanitySuite/test.dscreation.sanity.js

 "spec" Reporter:
------------------------------------------------------------------
[chrome-headless-shell 126.0.6478.126 linux #0-0] Running: chrome-headless-shell (v126.0.6478.126) on linux
[chrome-headless-shell 126.0.6478.126 linux #0-0] Session ID: 5b0e1cf78bc61aeeb43979a0a73bc7f6
[chrome-headless-shell 126.0.6478.126 linux #0-0]
[chrome-headless-shell 126.0.6478.126 linux #0-0] » /src/test/specs/sanitySuite/test.dscreation.sanity.js
[chrome-headless-shell 126.0.6478.126 linux #0-0] Mammoth Data Source Creation Sanity Tests
[chrome-headless-shell 126.0.6478.126 linux #0-0]    ✖ File upload @sanity
[chrome-headless-shell 126.0.6478.126 linux #0-0]
[chrome-headless-shell 126.0.6478.126 linux #0-0] 1 failing (14.8s)
[chrome-headless-shell 126.0.6478.126 linux #0-0]
[chrome-headless-shell 126.0.6478.126 linux #0-0] 1) Mammoth Data Source Creation Sanity Tests File upload @sanity
[chrome-headless-shell 126.0.6478.126 linux #0-0] The uploadFile command is not available in chrome-headless-shell
[chrome-headless-shell 126.0.6478.126 linux #0-0] Error: The uploadFile command is not available in chrome-headless-shell

How to have @createdBy and @updatedBy annotation in prisma schema?

In a nestjs and prisma api, I would like to add audit columns to my database.

Writting the mapping to get the user.idin each create/update method of each of my entities is cumbursome. In spring data rest, this is how they do auditing:

  @CreatedBy
  private User user;

  @CreatedDate
  private DateTime createdDate;

In prisma for example, I can use @updatedAt annotation in my schema to have the updatedData columns without writing code.

I would like to have @createdBy and @updatedBy audit annotation, either in prisma or in my nestJS code to audit the connected user.id who made the creation or modification of a row.

How is this possible?

event.targetTouches generates javascript error on some browsers

I’ve built a custom carousel with momentum and all works fine on my own browsers. However, Sentry gives me the following error “Cannot read properties of undefined (reading ‘0’)” for some Windows browsers, referring to my line of code: event.targetTouches[0].pageX.

Since not all browsers support targetTouches, I added a condition if’(TouchEvent’ in window), but still the same error message appears.

Does anybody know a method to receive the mouse/touch position which works for all browsers (or with proper error handling for browsers that don’t support)

My current code to detect mouse-position:

function getSwipeMousePosition(event) {
    if ('TouchEvent' in window) return {
       ‘x’: event.pageX || event.targetTouches[0].pageX,
       'y': event.pageY || event.targetTouches[0].pageY
    };
}

In case it helps, my full code can be found at takeyourbackpack.com (search for getSwipeMousePosition)

CommonJS vs. ES Modules: this Behavior with call(null) and call(undefined)

I saved the following code as index.cjs so that node considers it as a CommonJS module.

console.log(this);
function getThis() {
    console.log("this", this);
}

getThis.call(null); 
getThis.call(undefined);

I ran the above file using the command
$ node index.cjs

I am using node v18.17.0. I am getting the output as – empty object({}), global object, global object

When I run the above file with .mjs extension, i.e. when node treats it as an ES module, I am getting the output
undefined, null, undefined

**Why there is a difference in the output? **

While trying to find the answer, I came across the following points but they do not fully justify the output which I am getting.

  1. Node.js CommonJS modules are wrapped in a function and executed with the this value set to module.exports.
    This explains why empty object is printed in CJS at top-level.
  2. this substitution does not takes place in strict mode and modules by default runs in strict mode.
    When running the file as CJS module, it seems this substituition takes place. Hence it prints gloal object even when I call the function by setting its context explicitly to null and undefined.

Furthermore, when I add the statement use strict in index.cjs, the output is –
{}
this null
this undefined

React – Jittery animation on modal entry

I have built this custom modal component that does an animation on entering and leaving. However i’ve run into a problem where sometimes, more oftan than not – when opening the modal the animation seems to stutter or jitter a bit. But the closing animation is always flawless.

What is also strange is, if I comment out setModalAnimation("ModalEntryAnim") part in the useEffect, the entry animation still plays, but the exit animation does not(?)

Greatful for any ideas behind what could cause the stutter/jitteryness and/or being able to explain why commenting out that line of code causes the entry animation to still play. Thanks!

import { useClickOutside } from "hooks/useClickOutside"
import { ModalContentContainer, ModalText, ModalTitle, StyledCloseButton, StyledModal, StyledModalOverlay } from "./Modal.styles"
import { ReactNode, useEffect, useRef, useState } from "react"
import "./Modal.css"

type Props = {
    readonly state: "open" | "closed"
    readonly children: ReactNode

    readonly onClose: () => void
}

export const Modal = ({state, children, onClose}: Props) => {
    const modalRef = useRef<HTMLDivElement>(null)
    const [closed, setClosed] = useState<boolean>(true)

    const [modalAnimation, setModalAnimation] = useState<string>("")
    const [overlayAnimation, setOverlayAnimation] = useState<string>("")

    useClickOutside(modalRef, () => {
        if (state === "open" && !closed) {
            onClose()
        }
    })

    useEffect(() => {
        let timer: NodeJS.Timeout

        if (state === "open") {
            setModalAnimation("ModalEntryAnim")
            setOverlayAnimation("OverlayEntryAnim")
            setClosed(false)

        } else if (state === "closed") {
            setModalAnimation("ModalExitAnim")
            setOverlayAnimation("OverlayExitAnim")
            timer = setTimeout(() => {
                setClosed(true)
            }, 250)
        }

        return () => clearTimeout(timer)

    }, [state])


    if (state === "closed" && closed) return null

    return (
        <StyledModalOverlay className={overlayAnimation}>
            <StyledModal className={modalAnimation} ref={modalRef}>
                <StyledCloseButton onClick={onClose}/>
                {children}
            </StyledModal>
        </StyledModalOverlay>
    )
}

animations

@keyframes ModalEntryAninmation {
    from {
        transform: translateY(2rem);
    }

    to {
        transform: translateY(0rem);
    }
}

@keyframes ModalExitAninmation {
    from {
        transform: translateY(0rem);
    }

    to {
        transform: translateY(-4rem);
    }
}

@keyframes ModalOverlayEntryAninmation {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }
}

@keyframes ModalOverlayExitAninmation {
    from {
        opacity: 1;
    }

    to {
        opacity: 0;
    }
}

.ModalEntryAnim {
    animation: ModalEntryAninmation 250ms forwards;
}

.ModalExitAnim {
    animation: ModalExitAninmation 250ms forwards;
}

.OverlayEntryAnim {
    animation: ModalOverlayEntryAninmation 250ms forwards;
}

.OverlayExitAnim {
    animation: ModalOverlayExitAninmation 250ms forwards;
}

How to get clipboard HTML contents without style?

I am using event.clipboardData.getData('text/html'); to get the HTML from clipboard.

However, the problem is that the HTML doesn’t represent what’s actually been copied, e.g.

Copying this HTML as rendered in the browser:

<p class="mt_6 first:mt_0 lh_1.75rem">Panda provides a <code class="bd-w_1px bd-c_rgba(0,_0,_0,_0.04) dark:bd-c_rgba(255,_255,_255,_0.1) bg_rgba(0,_0,_0,_0.03) dark:bg_rgba(255,_255,_255,_0.1) ov-wrap_break-word ff_mono bdr_md py_0.5 px_0.25em fs_0.9em" dir="ltr">RecipeVariantProps</code> type utility that can be used to infer the variant properties of a recipe.</p>

I receive this in the clipboard:

<p class="mt_6 first:mt_0 lh_1.75rem" style="margin-top: var(--spacing-6); margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding: 0px; box-sizing: border-box; border-width: 0px; border-style: solid; border-color: var(--colors-neutral-800); overflow-wrap: break-word; --blur: ; --brightness: ; --contrast: ; --grayscale: ; --hue-rotate: ; --invert: ; --saturate: ; --sepia: ; --drop-shadow: ; --backdrop-blur: ; --backdrop-brightness: ; --backdrop-contrast: ; --backdrop-grayscale: ; --backdrop-hue-rotate: ; --backdrop-invert: ; --backdrop-opacity: ; --backdrop-saturate: ; --backdrop-sepia: ; --gradient-from-position: ; --gradient-to-position: ; --gradient-via-position: ; --scroll-snap-strictness: proximity; --border-spacing-x: 0; --border-spacing-y: 0; --translate-x: 0; --translate-y: 0; --rotate: 0; --rotate-x: 0; --rotate-y: 0; --skew-x: 0; --skew-y: 0; --scale-x: 1; --scale-y: 1; line-height: 1.75rem; color: rgb(243, 244, 246); font-family: ui-sans-serif, system-ui, -apple-system, &quot;system-ui&quot;, &quot;Segoe UI&quot;, Roboto, &quot;Helvetica Neue&quot;, Arial, &quot;Noto Sans&quot;, sans-serif, &quot;Apple Color Emoji&quot;, &quot;Segoe UI Emoji&quot;, &quot;Segoe UI Symbol&quot;, &quot;Noto Color Emoji&quot;; font-size: 14.4px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(17, 17, 17); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">Panda provides a<span> </span><code class="bd-w_1px bd-c_rgba(0,_0,_0,_0.04) dark:bd-c_rgba(255,_255,_255,_0.1) bg_rgba(0,_0,_0,_0.03) dark:bg_rgba(255,_255,_255,_0.1) ov-wrap_break-word ff_mono bdr_md py_0.5 px_0.25em fs_0.9em" dir="ltr" style="margin: 0px; padding: 0px; box-sizing: border-box; border-width: 1px; border-style: solid; border-color: rgba(255, 255, 255, 0.1); --font-mono-fallback: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,&quot;Liberation Mono&quot;,&quot;Courier New&quot;; font-feature-settings: &quot;rlig&quot;, &quot;calt&quot;, &quot;ss01&quot;; font-variation-settings: normal; font-family: var(--fonts-mono); font-size: 0.9em; --blur: ; --brightness: ; --contrast: ; --grayscale: ; --hue-rotate: ; --invert: ; --saturate: ; --sepia: ; --drop-shadow: ; --backdrop-blur: ; --backdrop-brightness: ; --backdrop-contrast: ; --backdrop-grayscale: ; --backdrop-hue-rotate: ; --backdrop-invert: ; --backdrop-opacity: ; --backdrop-saturate: ; --backdrop-sepia: ; --gradient-from-position: ; --gradient-to-position: ; --gradient-via-position: ; --scroll-snap-strictness: proximity; --border-spacing-x: 0; --border-spacing-y: 0; --translate-x: 0; --translate-y: 0; --rotate: 0; --rotate-x: 0; --rotate-y: 0; --skew-x: 0; --skew-y: 0; --scale-x: 1; --scale-y: 1; -webkit-box-decoration-break: clone; overflow-wrap: break-word; border-radius: var(--radii-md); background: rgba(255, 255, 255, 0.1); padding-block: var(--spacing-0.5); padding-inline: 0.25em;">RecipeVariantProps</code><span> </span>type utility that can be used to infer the variant properties of a recipe.</p>

How do I get HTML that more closely resembles the original HTML?

I could sanitize HTML to remove style= attribute, but then the HTML itself is not accurate representation of what was copied (notice the added spans).

(same HTML with style removed)

<p class="mt_6 first:mt_0 lh_1.75rem">Panda provides a<span> </span><code class="bd-w_1px bd-c_rgba(0,_0,_0,_0.04) dark:bd-c_rgba(255,_255,_255,_0.1) bg_rgba(0,_0,_0,_0.03) dark:bg_rgba(255,_255,_255,_0.1) ov-wrap_break-word ff_mono bdr_md py_0.5 px_0.25em fs_0.9em" dir="ltr">RecipeVariantProps</code><span> </span>type utility that can be used to infer the variant properties of a recipe.</p>

Adding a playerMove function in JS game. “keyDown” input and method not working

First question here. Im trying to create a small game and i have my character object containing some attributes as well as functions. When trying to implement a playerMove function to get my rectangle to move, i’m getting the “playerMove” is not defined error from the addEventlistener call to the function. What am I doing wrong here?
Is my way of thinking even possible? Should the eventlistener be in the main game file and pass the event to the character function instead?

Below is the code for the character object:

'use strict';
import Display from './gamearea.js'; 
import { gameArea } from './gamearea.js';

class Character {
    constructor (name, race, weapon) {
    this.name = name;
    this.race = race;
    this.weapon = weapon;
    this.locationX = 0;
    this.locationY = 125;
    this.characterWidth = 25;
    this.characterHeight = 12.5;
    this.color = "red";

    }
    sayHello() {
        console.log(`I'm named ${this.name}. I'm a ${this.race} using a        ${this.weapon}`);
}

    drawCharacter() {
        let ctx = gameArea.getContext('2d');
        ctx.fillStyle = this.color;
        ctx.fillRect(this.locationX, this.locationY, this.characterWidth,     this.characterHeight);
    document.gameArea.appendChild(ctx);
}

    //Eventlisteners for keydown movement
    input = document.addEventListener("keydown", (e) => {playerMove(e)});

    playerMove(directionInput) {
        console.log(directionInput.key);
        if (directionInput.key === 'w') {
            this.locationY -= 5;
        }
    }
}

export default Character;

I’ve tried placing the eventlistener in the mainGame file and call the the function from there, but I cant get to work.

Contributing to React Apex Chart

I am trying to fix an issue in the open source library Apex Charts. I followed the steps on the official GitHub site. After making a new demo project and using npm link apexcharts I was able to run the demo project using the Apex Charts library. However when I tried to use the React Apex Chart module with import ReactApexChart from "react-apexcharts" node could not find the requested module. I probably need an extra step to run the react version of this library but I do not know how. Any help would be welcome since this is my first time trying to fix an open source issue.

WordPress how to use wp_localize_script()

I have trouble localizing PHP variables for use in JS in WP.

I have a plugin I’m working on, which has several scripts that I enqueue with wp_enqueue_scripts() (suppose the handle I gave it is ‘my_script’), which works as intended.

However, on one page I would like to submit a value (a counter in a foreach loop, which might change) from PHP to JS and I am unclear how to properly do this.

Assume I have this in my_page.php which is a submenu page in my plugin:


$my_counter = get_my_count();

    wp_localize_script(
        'my_script',
        'my_js_object',
        array(
            'ajax_url' => $ajax_url,
            'my_counter' => $my_counter
        )
    );

and my JS in my_script.js:

console.log(my_js_object.my_counter);

From what I understand, my_script points to the JS-file I enqueued in functions.php. However, this isn’t working, and my console tells me ‘my_js_object’ is not defined.

What do I localize where to get this to work?

Sudoku Validator returning undefined

I have been working on this too long now, so for some reason my sudoku validator keeps returning undefined, it has to be the sudokuisvalid part, but i have no clue why it wont return a boolean fixed the problem with the getRow, and the 1 where the I is supposed to be.

im really hoping its something obvious and im just too tired, and im new to programming so ill paste my code and see what y’all think!

function getRow(puzzle, row) {
// WRITE YOUR CODE HERE
return puzzle[row]
}

function getColumn(puzzle, col) {
// WRITE YOUR CODE HERE
return puzzle.map(row=>row[col])
}

function getSection(puzzle, x, y) {
// WRITE YOUR CODE HERE
let section = []
for(i = 3 * x; i < 3 * x + 3; i++){
  for(j = 3 * y; j < 3*y+3 ; j++){
    section.push(puzzle[i][j])
  }
}
return section
}

function includes1To9(arr) {
// WRITE YOUR CODE HERE
  for (i = 0; i < arr.length; i++){
    for (j = 0; j < arr.length; j++){
      if (j != i){
        if (arr[i] === arr[j]){
          return false
        }
      }
    }
  }
  return true
}

function sudokuIsValid(puzzle) {
  let valid =[]
  for(let i=0; i<9; i++){
    valid.push(getRow(puzzle,i))
    valid.push(getColumn(puzzle, i))
  }
  for(let i=0; i<3; i++){
    for(let j=0; j<3; j++){
      valid.push(getSection(puzzle, i, j))
    }
  }
  for(let i= 0; i< valid.length; i++){
    if(includes1To9(valid[i] === false)){
      return false
    }
  }
  return true
}