React TypeError: Cannot read properties of null (reading ‘useMemo’) in Elements2 component in stripe gateway

I’m encountering a TypeError in my React application and I’m having trouble resolving it. The error message points to an issue within the Elements2 component, specifically mentioning a problem with reading properties of null, particularly ‘useMemo’. Here’s a snippet of the error:

enter image description here
enter image description here

The relevant code snippet where Elements2 is used is as follows:

 const CheckoutForm = () => {
  const [isProcessing, setIsProcessing] = useState(false);
  const submitHandler = async (e) => {};
  return (
    <div className="checkout-container">
      <form onSubmit={submitHandler}>
        <PaymentElement />
        <button type="submit" disabled={isProcessing}>
          {isProcessing ? "Processing..." : "pay"}
        </button>
      </form>
    </div>
  );
};

const Checkout = () => {
  const clientSecret =
    "client-secret";
  return (
    <Elements options={{ clientSecret }} stripe={stripePromise}>
      <CheckoutForm />
    </Elements>
  );
};

export default Checkout;

I’ve tried troubleshooting by checking the dependencies, but haven’t been able to pinpoint the root cause. Any insights on what might be causing this issue and how to resolve it would be greatly appreciated. Thank you in advance!

I initially searched for solutions using ChatGPT to troubleshoot the problem. After that, I thoroughly reviewed my code for any logical errors, ensuring that I didn’t miss anything obvious. I specifically checked for adherence to the rules of React Hooks, ensuring there were no violations. Additionally, I verified that there were no mismatched versions of dependencies and made sure that there was only one copy of React being used in the application.

React Google Maps Marker Icon Not Updating Dynamically

I’m working on a delivery app using React and @react-google-maps/api. I have a map component that shows the location of a delivery worker with a custom icon. However, I’ve run into an issue where the marker’s icon does not update dynamically when the delivery worker’s status changes (e.g., from “delivering” to “delivered”).

Here’s the simplified version of my map component:

import React from 'react';
import { GoogleMap, LoadScript, Marker } from '@react-google-maps/api';

const mapContainerStyle = {
  width: '800px',
  height: '600px',
};
const center = {
  lat: -34.397,
  lng: 150.644,
};
const deliveryWorkerIcon = "https://www.citypng.com/public/uploads/large/701751694974714k04h1qhze9qoibj5zsdeldgmudwiygsfhulvidozwie8c3x74fcxvb3skcj0yqfnr2xehmarxrjwct6xtqgpbryyi5giatccgmjb.png";

const MapComponent = () => {
  return (
    <LoadScript googleMapsApiKey="">
      <GoogleMap
        mapContainerStyle={mapContainerStyle}
        center={center}
        zoom={10}
      >
        <Marker
          position={center}
          icon={{
            url: deliveryWorkerIcon,
            scaledSize: new window.google.maps.Size(50, 50),
          }}
        />
      </GoogleMap>
    </LoadScript>
  );
};

export default MapComponent;

The marker is supposed to change when the delivery worker’s status updates, but the icon remains the same. I’ve tried to use useState to dynamically update the deliveryWorkerIcon URL based on the worker’s status, but the marker does not re-render with the new icon.

How can I ensure the marker icon updates dynamically in response to state or prop changes in my component?

Problem with correct executing of 2 JavaScript functions

I have a container (with a background image) and inside this container there is some text (chosen by reading value from a text input). To fit the text I’m using textFit script. User can also choose the font and there is the major problem.

I’m putting a snippet here so you can se the problem (instructions below):

const resultContainer = document.querySelector("#slide-container");
const chosenText = document.querySelector("#ChosenText");
const chosenFont = document.querySelector("#ChosenFont");
const textOnPicture = document.querySelector(".textOnPicture");

function refreshPicture() {
  textOnPicture.textContent = chosenText.value;
  textFit(resultContainer);
}

function reloadPicture(manualChoose) { //function is called by pressing "Reload" button
  changeFontFamily(manualChoose); //here is the thing, I want to change font family
  refreshPicture();
}

function changeFontFamily(manualChoose) {
  let fontFamily;
  if (!!manualChoose) {//when triggered by changing value of input
    fontFamily = chosenFont.value;
    textOnPicture.style.setProperty("--font-family", fontFamily); //in css this property is obviously assigned to font-family of textOnPicture
    textFit(resultContainer);
  } else {//when triggered by "Reload" button, then random picture, font and color are chosen
    fontFamily = fonts[Math.floor(Math.random() * fonts.length)].name;//random font from an array where I have all of my fonts
    textOnPicture.style.setProperty("--font-family", fontFamily);
    chosenFont.value = fontFamily;
  }
}

function resizePicture() {
  resultContainer.style.height = resultContainer.offsetWidth * (screen.height / screen.width) + "px";
}

window.onresize = (e) => {
  resizePicture();
  textFit(resultContainer);
};

(async () => {
  resizePicture();
})();
.textOnPicture {
    font-family: var(--font-family);
    text-align: center;
    position: absolute;
    padding: 0.2em;
}

#slide-container {
    width: 100%;
    background-color: red;
    background-size: cover;
    background-position: center;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    margin-top: 40px;
}
    <link href="https://fonts.googleapis.com/css2?family=Amita:wght@400;700&family=Averia+Serif+Libre:ital,wght@0,300;0,400;0,700;1,300;1,400;1,700&family=Madimi+One&family=Underdog&family=VT323&family=Victor+Mono:ital,wght@0,100..700;1,100..700&family=Ysabeau+SC:[email protected]&display=swap" rel="stylesheet">

<input type="text" id="ChosenText" autocomplete="off" placeholder="Type text here" oninput="refreshPicture()">

<select id="ChosenFont" onchange="changeFontFamily(true)">
  <option value="Amita">Amita</option>
  <option value="Averia Serif Libre">Averia Serif Libre</option>
  <option value="Victor Mono">Victor Mono</option>
</select>

<div id="slide-container">
        <span id="textOnPicture" class="textOnPicture textFitted"></span>
</div>
<script> /*It's textFit from Github, not my own code. I changed here only few settings*/ (function(root, factory) {
  "use strict";

  // UMD shim
  if (typeof define === "function" && define.amd) {
    // AMD
    define([], factory);
  } else if (typeof exports === "object") {
    // Node/CommonJS
    module.exports = factory();
  } else {
    // Browser
    root.textFit = factory();
  }

}(typeof global === "object" ? global : this, function () {
  "use strict";

  var defaultSettings = {
    alignVert: false, // if true, textFit will align vertically using css tables
    alignHoriz: true, // if true, textFit will set text-align: center
    multiLine: true, // if true, textFit will not set white-space: no-wrap
    detectMultiLine: true, // disable to turn off automatic multi-line sensing
    minFontSize: 6,
    maxFontSize: 10000,
    reProcess: true, // if true, textFit will re-process already-fit nodes. Set to 'false' for better performance
    widthOnly: false, // if true, textFit will fit text to element width, regardless of text height
    alignVertWithFlexbox: true, // if true, textFit will use flexbox for vertical alignment
  };

  return function textFit(els, options) {

    if (!options) options = {};

    // Extend options.
    var settings = {};
    for(var key in defaultSettings){
      if(options.hasOwnProperty(key)){
        settings[key] = options[key];
      } else {
        settings[key] = defaultSettings[key];
      }
    }

    // Convert jQuery objects into arrays
    if (typeof els.toArray === "function") {
      els = els.toArray();
    }

    // Support passing a single el
    var elType = Object.prototype.toString.call(els);
    if (elType !== '[object Array]' && elType !== '[object NodeList]' &&
            elType !== '[object HTMLCollection]'){
      els = [els];
    }

    // Process each el we've passed.
    for(var i = 0; i < els.length; i++){
      processItem(els[i], settings);
    }
  };

  /**
   * The meat. Given an el, make the text inside it fit its parent.
   * @param  {DOMElement} el       Child el.
   * @param  {Object} settings     Options for fit.
   */
  function processItem(el, settings){
    if (!isElement(el) || (!settings.reProcess && el.getAttribute('textFitted'))) {
      return false;
    }

    // Set textFitted attribute so we know this was processed.
    if(!settings.reProcess){
      el.setAttribute('textFitted', 1);
    }

    var innerSpan, originalHeight, originalHTML, originalWidth;
    var low, mid, high;

    // Get element data.
    originalHTML = el.innerHTML;
    originalWidth = innerWidth(el);
    originalHeight = innerHeight(el);

    // Don't process if we can't find box dimensions
    if (!originalWidth || (!settings.widthOnly && !originalHeight)) {
      if(!settings.widthOnly)
        throw new Error('Set a static height and width on the target element ' + el.outerHTML +
          ' before using textFit!');
      else
        throw new Error('Set a static width on the target element ' + el.outerHTML +
          ' before using textFit!');
    }

    // Add textFitted span inside this container.
    if (originalHTML.indexOf('textFitted') === -1) {
      innerSpan = document.createElement('span');
      innerSpan.className = 'textFitted';
      // Inline block ensure it takes on the size of its contents, even if they are enclosed
      // in other tags like <p>
      innerSpan.style['display'] = 'inline-block';
      innerSpan.innerHTML = originalHTML;
      el.innerHTML = '';
      el.appendChild(innerSpan);
    } else {
      // Reprocessing.
      innerSpan = el.querySelector('span.textFitted');
      // Remove vertical align if we're reprocessing.
      if (hasClass(innerSpan, 'textFitAlignVert')){
        innerSpan.className = innerSpan.className.replace('textFitAlignVert', '');
        innerSpan.style['height'] = '';
        el.className.replace('textFitAlignVertFlex', '');
      }
    }

    // Prepare & set alignment
    if (settings.alignHoriz) {
      el.style['text-align'] = 'center';
      innerSpan.style['text-align'] = 'center';
    }

    // Check if this string is multiple lines
    // Not guaranteed to always work if you use wonky line-heights
    var multiLine = settings.multiLine;
    if (settings.detectMultiLine && !multiLine &&
        innerSpan.getBoundingClientRect().height >= parseInt(window.getComputedStyle(innerSpan)['font-size'], 10) * 2){
      multiLine = true;
    }

    // If we're not treating this as a multiline string, don't let it wrap.
    if (!multiLine) {
      el.style['white-space'] = 'nowrap';
    }

    low = settings.minFontSize;
    high = settings.maxFontSize;

    // Binary search for highest best fit
    var size = low;
    while (low <= high) {
      mid = (high + low) >> 1;
      innerSpan.style.fontSize = mid + 'px';
      var innerSpanBoundingClientRect = innerSpan.getBoundingClientRect();
      if (
        innerSpanBoundingClientRect.width <= originalWidth 
        && (settings.widthOnly || innerSpanBoundingClientRect.height <= originalHeight)
      ) {
        size = mid;
        low = mid + 1;
      } else {
        high = mid - 1;
      }
      // await injection point
    }
    // found, updating font if differs:
    if( innerSpan.style.fontSize != size + 'px' ) innerSpan.style.fontSize = size + 'px';

    // Our height is finalized. If we are aligning vertically, set that up.
    if (settings.alignVert) {
      addStyleSheet();
      var height = innerSpan.scrollHeight;
      if (window.getComputedStyle(el)['position'] === "static"){
        el.style['position'] = 'relative';
      }
      if (!hasClass(innerSpan, "textFitAlignVert")){
        innerSpan.className = innerSpan.className + " textFitAlignVert";
      }
      innerSpan.style['height'] = height + "px";
      if (settings.alignVertWithFlexbox && !hasClass(el, "textFitAlignVertFlex")) {
        el.className = el.className + " textFitAlignVertFlex";
      }
    }
  }

  // Calculate height without padding.
  function innerHeight(el){
    var style = window.getComputedStyle(el, null);
    return el.getBoundingClientRect().height -
      parseInt(style.getPropertyValue('padding-top'), 10) -
      parseInt(style.getPropertyValue('padding-bottom'), 10);
  }

  // Calculate width without padding.
  function innerWidth(el){
    var style = window.getComputedStyle(el, null);
    return el.getBoundingClientRect().width -
      parseInt(style.getPropertyValue('padding-left'), 10) -
      parseInt(style.getPropertyValue('padding-right'), 10);
  }

  //Returns true if it is a DOM element
  function isElement(o){
    return (
      typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
      o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName==="string"
    );
  }

  function hasClass(element, cls) {
    return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
  }

  // Better than a stylesheet dependency
  function addStyleSheet() {
    if (document.getElementById("textFitStyleSheet")) return;
    var style = [
      ".textFitAlignVert{",
        "position: absolute;",
        "top: 0; right: 0; bottom: 0; left: 0;",
        "margin: auto;",
        "display: flex;",
        "justify-content: center;",
        "flex-direction: column;",
      "}",
      ".textFitAlignVertFlex{",
        "display: flex;",
      "}",
      ".textFitAlignVertFlex .textFitAlignVert{",
        "position: static;",
      "}",].join("");

    var css = document.createElement("style");
    css.type = "text/css";
    css.id = "textFitStyleSheet";
    css.innerHTML = style;
    document.body.appendChild(css);
  }
}));</script>

The problem is when I change font family (by pressing the button and choosing it randomly or manually by changing value) font size doesn’t change and sometimes text is outside of the container. But when I call textFit function again; it fixes.
A step by step instruction to see a problem:

  1. Type some text to the input, for the “best” result text element should fill the container as much as it is possible.
  2. Change font family to “Victor Mono”. It is the biggest one so you should see the text is too big and it’s outside of the container.
  3. Change size of your browser window or type one more letter in the input. Now size of the text should be correct.

So I have 2 functions: changeFontFamily and textFit. And they should execute in the exactly same order I wrote them but it looks like they aren’t. I don’t know what’s going on here really because I don’t know how to check it so it is only my hypotesis. Font family changes but font size not, here is the problem. And due to every font family basically has its own size the text is sometimes too small or too big after change of font family and it looks terrible. Of course I would like to my text always have correct size.

Prevent code that merges two arrays by matching on different columns from adding rows for the unmatched

I found from here code that merges two arrays by matching on different columns where arrays are of unequal length

merge two arrays by matching on different columns where arrays are of unequal length unequal length

If you are matching the longer array to the shorter array
It adds rows for all the unmatched from the longer array

How do you edit the code to prevent the addition of the unmatched rows?

I have tried to do this but could not figure it out

enter image description here

I have created a Google sheet with more data that shows more accurately what I mean than what the original question provided

Thank you

https://docs.google.com/spreadsheets/d/1e6OZa532KW2Wp-fDwqyZ4__RpKLjZSENtTacBfwbl50/edit?usp=sharing

const
    mergeBy = (tables, keepFirstKey = false) => {
        const
            SPACER = '',
            empty = [],
            head = [],
            rows = {};
            
        tables.forEach(([table, key], j) => {
            const
                index = table[0].indexOf(key),
                withKey = (row, i) => {
                    const key = row[index];
                    if (i) (rows[key] = rows[key] || [...empty]).push(...row);
                    else head.push(...row);
                },
                withoutKey = ({ [index]: key, ...row }, i) => {
                    if (i) (rows[key] = rows[key] || [...empty]).push(...Object.values(row));
                    else head.push(...Object.values(row));
                },
                takeKey = !j && keepFirstKey;
                
            table.forEach(takeKey ? withKey : withoutKey);
            empty.push(...Array(table[0].length - !takeKey).fill(SPACER));
        });

        return [head, ...Object.values(rows)].map(a => {
            while (a.length < empty.length) a.push(SPACER);
            return a;
        });
    }

I want to correct the JSON of an invalid JSON syntax given as an input by the user. I don’t want to use json repair library but code that repairs it

So, if a user throws a invalid JSON.For example
…i want a code that repair the JSON and returns a VALID json to me …correcting its FORMAT
NOTE:- I don’t want to use any JSON repair Library
at first i am trying to handle the outer braces that whether they are balanced or not.

`const strInvalid = {
  "personality": [
    {
      "key": "extraversion",
      "rating": 15.0,
      "comment": "No relevant data"
    },
    {
      "key": "active",
      "rating": 15.0,
      "comment": "No relevant data"
    },
    {
      "key": "disciplined",
      "rating": 15.0,
      "comment": "No relevant data"
    }
  ] // Corrected: Added closing brace here
};

const string = `{
    "personality": [
        {"key": "extraversion", "rating": 15.1, "comment": "No relevant data" },
         {"key " : "active", "rating": 15.0, "comment": "No relevant data" }
    ]
}`;

const strNormalized = string.replace(/s+/g, '');

function addMissingBraces(str) {
    let openingBraceCount = 0;
    let closingBraceCount = 0;
   
    const strLen = str.length;

    for (let i = 0; i < strLen; i++) {
        if (str[i] === "{") {
            openingBraceCount++;
        } else if (str[i] === "}") {
            closingBraceCount++;
        }
    }

    if (closingBraceCount > openingBraceCount) {
        str = "{".repeat(closingBraceCount - openingBraceCount) + str;
    } else if (openingBraceCount > closingBraceCount) {
        str = str + "}".repeat(openingBraceCount - closingBraceCount);
    }

    return str;
}

function isValidJSON(str) {
    try {
        JSON.parse(str);
        return true;
    } catch (error) {
        return false;
    }
}

if (isValidJSON(strNormalized)) {
    console.log("Valid JSON");
} else {
    console.log("Not valid, correcting JSON...");
    const correctedJSON = addMissingBraces(strNormalized);
    console.log("Corrected JSON: ", correctedJSON);
}
`

Why is my React Query query function being called when it should be disabled?

I want to conditionally set the parameters and fetching function called in a React Query function (useSpeciesCodes.js) in order to fetch from one of two API endpoints (fetching functions are getSpeciesCodesByRegion or getSpeciesCodesByAddress), based off of URL query and search parameters. When the parameters and function definition are returned from another hook (useGetSpeciesCodesFunction.js), only then should the query function run.

/**
 * useSpeciesCodes.js
 */
import { useQuery } from "@tanstack/react-query";
import { useParams, useSearchParams } from "react-router-dom";
import { useGetSpeciesCodesFunction } from "./useGetSpeciesCodesFunction";

export function useSpeciesCodes() {
  const { layer } = useParams();
  const [searchParams] = useSearchParams();
  const lat = searchParams.get("lat");
  const lng = searchParams.get("lng");

  const { params, speciesCodesFunction } = useGetSpeciesCodesFunction(layer, lat, lng);

  const {
    status,
    data: speciesCodes,
    error,
  } = useQuery({
    queryKey: ["speciesCodes", params],
    queryFn: () => speciesCodesFunction(params),
    enabled: !!(params && speciesCodesFunction)
  });

  return { status, error, speciesCodes };
}
/**
 * useGetSpeciesCodesFunction.js
 */

import { useEffect, useState } from "react";
import { getSpeciesCodesByAddress, getSpeciesCodesByRegion } from "../services/apiEBird";
import { getAddressbyCoordinates } from "../services/apiRadar";
import { useParams, useSearchParams } from "react-router-dom";

export function useGetSpeciesCodesFunction() {
    const { layer } = useParams();
    const [searchParams] = useSearchParams();
    const lat = searchParams.get("lat");
    const lng = searchParams.get("lng");
    const [params, setParams] = useState(null);
    const [speciesCodesFunction, setSpeciesCodesFunction] = useState(null)

    useEffect(
        () => {
            async function handleLocation(layer, lat, lng) {
                // If layer is state or country, convert option value to ISO standardized code to get region code for eBird API
                if (layer === 'state') {
                    const { stateCode, countryCode } = await getAddressbyCoordinates(layer, lat, lng);
                    setParams(`${countryCode}-${stateCode}`)
                    setSpeciesCodesFunction(getSpeciesCodesByRegion);
                } else if (layer === 'country') {
                    const { countryCode } = await getAddressbyCoordinates(layer, lat, lng);
                    setParams(countryCode);
                    setSpeciesCodesFunction(getSpeciesCodesByRegion);
                } else {
                    const radius = 25;
                    setParams({ lat, lng, radius });
                    setSpeciesCodesFunction(getSpeciesCodesByAddress);
                }
            }
            handleLocation(layer, lat, lng);
        }
        , [layer, lat, lng]
    )
    console.log(params, speciesCodesFunction)
    return { params, speciesCodesFunction }

}

The output shows that a fetch function getSpeciesCodesByRegion is being called before the useGetSpeciesCodesFunction.js hook returns non-null values, when it should not be called because of the condition in the ‘enabled’ option. An additional issue/reason I am confused is why the function being returned from useGetSpeciesCodesFunction.js is a Promise and not a function definition, but it is being handled as a function definition by React Query.

1. useGetSpeciesCodesFunction.js:44 null null
2. apiRadar.js:8 getAddressbyCoordinates
3. apiEBird.js:11 getSpeciesCodesByRegion null
4. useGetSpeciesCodesFunction.js:44 US-WA Promise {<pending>}
5. useGetSpeciesCodesFunction.js:44 US-WA Promise {<fulfilled>: Array(0)}

This problem is driving me crazy. I have tried wrapping the useGetSpeciesCodesFunction async function in multiple async-await layers considering it is an asynchronous issue and moving the async function outside hooks or into other hooks. I have tried a workaround for a bug where the enabled option is reported to be not working (https://github.com/TanStack/query/issues/1196), but the query function is called anyway. I want useGetSpeciesCodesFunction to return parameters and a function definition, based on the URL and search params. I want useSpeciesCodes to call the function is is passed with the parameters it is passed and return data from the fetching API. I can only imagine that this is some sort of misunderstanding of how promises, hooks, or React Query works???

Thank you so much for your help in advance.

Puppeteer not working after deployed in render but work on my local machine

I am trying to deploy my api for fetch compatibility details for my website.The api is running perfectly in my local machine i tested several time by postman but when deployed it gives 500 internal error every time

const puppeteer = require('puppeteer');

async function scrapeCompatibility(req, res) {
    try {
    
        const { sign1,sign2 } = req.body;
        const browser = await puppeteer.launch();
        const page = await browser.newPage();

        const url = `https://www.horoscope.com/us/games/compatibility/game-love-compatibility.aspx?ZodiacSignSelector_alphastring=${sign1}&PartnerZodiacSignSelector_alphastring=${sign2}`;
        await page.goto(url);

        // Selector for horoscope content might change on the website. Update as needed.
        const compatibilityScore = await page.evaluate(() => document.querySelector('.game-compatibility-score').innerText);
        const compatibilityText = await page.evaluate(() => document.querySelector('.module-skin p').innerText);
        await browser.close();
        console.log(compatibilityScore);
        console.log(compatibilityText);
        return res.status(200).json({
            success: true,
            data: {compatibilityScore,compatibilityText }
       })
    }
    catch (e)
    {
        return res.status(500).json({
            success: false,
            message:"Something went wrong"
        })
    }
    

}

module.exports = { scrapeCompatibility };

Console error with sweetalert2 plugin from adminlte and primefaces

I have a problem when I press the primefaces button to delete a client:

enter image description here

Here is my javascript code with the button calling the function.
Javascript:

if (window.location.pathname.endsWith('/cliente.xhtml')) {

function confirmarEliminar() {
    Swal.fire({
        title: "<strong>HTML <u>example</u></strong>",
        icon: "info",
        html: `
You can use <b>bold text</b>,
<a href="#">links</a>,
and other HTML tags `,showCloseButton: true,
        showCancelButton: true,
        focusConfirm: false,
        confirmButtonText: `
<i class="fa fa-thumbs-up"></i> Great! `,confirmButtonAriaLabel: "Thumbs up, great!",
        cancelButtonText: `
<i class="fa fa-thumbs-down"></i>  `,cancelButtonAriaLabel: "Thumbs down"
    });
}};

And the button.

<p:commandButton icon="ui-icon-close" onclick="confirmarEliminar()"></p:commandButton>

I would also like to know how to execute a function to the controller when the user presses OK.

Upload img using ckeditor and firebase storage in React

Helloo, I have a problem with my react project
Im trying to use upload image feature in ckeditor with firebase storage but I cannot do that with code I got from AI chatbot :<.

I had looking for some doc and found https://dev.to/suraj975/ckeditor-image-upload-with-firebase-and-react-1pe8 but I still not understand at all.
Here is my code:

import React, { useState, useEffect } from 'react';
import { CKEditor } from '@ckeditor/ckeditor5-react';
import Editor from 'ckeditor5-custom-build/build/ckeditor';
import { firebase } from '../../services/firebase';

class MyUploadAdapter {
    constructor(loader) {
        this.loader = loader;
    }

    // Starts the upload process
    upload() {
        return this.loader.file.then((file) =>
            new Promise((resolve, reject) => {
                const storage = firebase.storage().ref();
                const uploadTask = storage.child('geogbraimg/' + file.name).put(file);

                uploadTask.on(
                    firebase.storage.TaskEvent.STATE_CHANGED,
                    (snapshot) => {
                        // Show upload progress if needed
                        const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                        console.log(`Upload is ${progress}% done`);
                    },
                    (error) => {
                        // Handle errors (e.g., unauthorized, canceled, unknown)
                        switch (error.code) {
                            case "storage/unauthorized":
                                reject("User doesn't have permission to access the object");
                                break;
                            case "storage/canceled":
                                reject("User canceled the upload");
                                break;
                            case "storage/unknown":
                                reject("Unknown error occurred, inspect error.serverResponse");
                                break;
                            default:
                                reject("Error during upload");
                        }
                    },
                    () => {
                        // Upload completed successfully, get the download URL
                        uploadTask.snapshot.ref
                            .getDownloadURL()
                            .then((downloadURL) => {
                                resolve({ default: downloadURL });
                            });
                    }
                );
            })
        );
    }
}

const Ckeditor = ({ title, dataOnChange }) => {
    const [editorData, setEditorData] = useState('');
    const [showToolbar, setShowToolbar] = useState(false);

    const handleEditorChange = (event, editor) => {
        const data = editor.getData();
        // Update databucket prop with the new data
        dataOnChange(data);
        setEditorData(data);
    };

    let toolbar = {
        toolbar: ['heading',
            '|',
            'ckbox',
            '|',
            'bold',
            'italic',
            'link',
            'bulletedList',
            'numberedList',
            '|',
            'outdent',
            'indent',
            '|',
            'fontFamily',
            'fontSize',
            '|',
            'mathType',
            'chemType',
            '|',
            'imageUpload',
            'blockQuote',
            'insertTable',
            'undo',
            'redo'],
        extraPlugins: [MyUploadAdapter]
    }

    return (
        <div>
            <h4>{title}</h4>
            <CKEditor
                editor={Editor}
                data={editorData}
                onChange={handleEditorChange}
                config={toolbar}

            />
            <br></br>
        </div>
    );
};

export default Ckeditor;

Thank for your help <3

How to use React Router with a backend?

I’m a beginner, so very inexperienced when it comes to full stack so tell me if my entire approach is just wrong. I’m currently building a simple chatting web app that has 2 components. A log in page and the main page where you have one chat window where the actual activity happens.

The problem is that for my login page I use mongodb and when I login I basically just send the form data(POST) and see whether or not the inputted username and passwords from the from exist on the database, if it does i want the user to get into their account with some sort of identifier so the app renders the right things depending on the user, this component works on its own just fine. But I’m not sure how to do that with the React router because when I integrate react router, and I do the login nothing happens. I assume thats because React Router intercepts any call to the server by the client. Does React router have some way around this or am I just using the wrong tools or doing it the wrong way?

I would like to try and ask first before I try some brute force methods that might work but ultimately wont give me any idea of how things should be done.

Error while running npx create-react-app my-app on VS Code

Have installed Node.js and have VS Code too. While running npx create-react-app my-app in terminal there is the error coming:

npm ERR! code ENOENT
npm ERR! syscall lstat
npm ERR! path C:UsersAMANAppDataRoamingnpm
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, lstat 'C:UsersAMANAppDataRoamingnpm'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in: C:UsersAMANAppDataLocalnpm-cache_logs2024-04-06T15_41_19_323Z-debug-0.log

I don’t know what to do. I tried npm cache clean --force but after that this came npm WARN using --force Recommended protections disabled. Also tried package-lock.json but no use.

(TYPESCRIPT CHROME EXTENSION) Object.defineProperty(exports, “__esModule”,..); gets added unintentionally in compiled JS from TS

How can I get rid of this unnecessary line which cause errors Uncaught ReferenceError: exports is not defined.

I am creating Typescript Chrome Extension and I’ve been trying to fix this problem for long time now.

Compiled JavaScript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
console.log("running");
async function cacheUserCreationDate(userRobloxCreationDate) {
}
let backgroundAPIList = new Map();
backgroundAPIList.set("CacheUserCreationDate", cacheUserCreationDate);
console.log("setting up!");
chrome.runtime.onMessage.addListener((communicationRequest) => {
    console.log("got!");
    console.log(communicationRequest.parameters);
});

TypeScript

import { UserCreationDate } from "../background-types/types";

async function cacheUserCreationDate(userCreationDate : UserxCreationDate) : Promise<void> {
    
}

let backgroundAPIList = new Map<string, (...parameters: any[]) => Promise<unknown>>()
backgroundAPIList.set("CacheUserCreationDate", cacheUserCreationDate)

chrome.runtime.onMessage.addListener((communicationRequest: CommunicationRequest) => {
    console.log(communicationRequest.parameters)
})

tsconfig.ts


{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"rootDir": "./",
"outDir": "dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"strictNullChecks": true,
"alwaysStrict": true,
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}

Building Process

"scripts": {
    "dev": "",
    "test": "",
    "clean": "IF EXIST dist rmdir /s /q dist",
    "compile": "npx tsc",
    "copy-assets": "robocopy . dist /S /E /XF tsconfig.json /XD src /XD dist",
    "build": "npm run clean && npm run compile  && npm run copy-assets"
  }

Can you change locale of default form validation messages?

Is there a way to change locale of default form validation messages so that no matter the browser’s language they are always displayed in English.

I don’t want to set custom messages via setCustomValidity, I want to use browser’s messages but I want them always in English.

Code sample showing intended use:

      [...e.currentTarget.elements].reduce((acc, el) => {
        if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement)
          if (el.validationMessage)
            return { ...acc, [el.name]: el.validationMessage };

        return acc;
      }, {})

Unable to focus on second textinput or rthe submit button

I am unable to focus on second textinput in this, first one works fine. Also the submit button isn’t pressable. The second input and submit button starts working fine after i input something in first input component.

I am using reanimated for animating the bottom container.

 const {width, height} = useWindowDimensions();
 const isKeyboardOpen = useKeyboardStatus();
 const offsetY = useSharedValue(0);
 const Available_Height = height - 55;
 const Banner_Height = Available_Height * 0.4;
 const AnimateTo = Banner_Height - 55 + 16;
 const animatedStyles = useAnimatedStyle(() => {
   return {
     transform: [{translateY: offsetY.value}],
   };
 });

 useEffect(() => {
   if (isKeyboardOpen) {
     offsetY.value = withTiming(-AnimateTo, {
       duration: 250,
     });
   } else {
     offsetY.value = withTiming(0, {duration: 250});
   }
 }, [isKeyboardOpen]);

 return (
   <Wrapper navHeading={'Login'} canGoBack={false}>
     <ViewComponent
       backgroundColor={SemanticColors.MAIN_FOREGROUND}
       style={{flex: 1}}>
       <ViewComponent backgroundColor={SemanticColors.MAIN_FOREGROUND}>
         <AuthSVG width={width} height={Banner_Height} />
       </ViewComponent>
       <ReanimatedBox
         backgroundColor={SemanticColors.MAIN_BACKGROUND}
         style={[
           {
             borderTopRightRadius: 14,
             borderTopLeftRadius: 14,
             padding: 16,
             height: Available_Height - Banner_Height,
             justifyContent: 'space-between',
           },
           animatedStyles,
         ]}>
         <ViewComponent>
           <InputField
             placeholder="Email"
             onFocus={() => {
               console.log('focused 1');
             }}
           />
           <InputField
             placeholder="Password"
             onFocus={() => {
               console.log('focused 2');
             }}
           />
         </ViewComponent>
         <ViewComponent marginBottom={Spacings.S}>
           <CustomButton
             onPress={() => {}}
             title={'Next'}
             btnType={BtnTypes.PRIMARY}
           />
         </ViewComponent>
       </ReanimatedBox>
     </ViewComponent>
   </Wrapper>
 );
};
export default Login;

And animated box is made using this code:

import {
  BackgroundColorProps,
  BorderProps,
  LayoutProps,
  PositionProps,
  ShadowProps,
  SpacingProps,
  SpacingShorthandProps,
  backgroundColor,
  createRestyleComponent,
  spacing,
  spacingShorthand,
  layout,
  border,
  shadow,
} from '@shopify/restyle';
import {Theme} from '@themes/Themes';
import {ViewProps} from 'react-native';
import Animated, {AnimatedProps} from 'react-native-reanimated';

export type ReanimatedBoxProps = BackgroundColorProps<Theme> &
  SpacingProps<Theme> &
  LayoutProps<Theme> &
  BorderProps<Theme> &
  SpacingShorthandProps<Theme> &
  PositionProps<Theme> &
  ShadowProps<Theme> &
  AnimatedProps<ViewProps>;

const ReanimatedBox = createRestyleComponent<ReanimatedBoxProps, Theme>(
  [backgroundColor, spacing, spacingShorthand, layout, border, shadow],
  Animated.View,
);

export default ReanimatedBox;