Extra line break occuring with syntax highlighting (prism js)

I am making a syntax highling code editor in HTML, JS, and CSS.

How it Works:
There are two divs that overlap. The one on top is the one that you edit. The one below mimicks what you type, but is formatted (using prism js).

Problem:

Whenever there are consecutive line breaks (more than one line break at a time), the formatted code appears that many times below the typed text.

Example:

Typed Text:

<span></span>



<h1></h1>

Formatted:

<span></span>






<h1></h1>

Code

`#codeContainer {
            position: fixed;
            top: 10%;
            left: 0%;
            z-index: 1;
            width: 100%;
            height: 90%;
            outline: 0;
        }

        #code {
            position: absolute;
            left: 0%;
            top: 0%;
            width: 100%;
            height: 100%;
            background-color: transparent;
            font-size: 14px;
            line-height: 1.5;
            white-space: pre-wrap;
            overflow: auto;
        }

        #highlight {
            position: absolute;
            left: 0%;
            top: 0%;
            z-index: 0;
            width: 100%;
            height: 100%;
            background-color: white;
            font-size: 14px;
            color: white;
            line-height: 1.5;
            white-space: pre-wrap;
            overflow: auto;
            margin-top: -6px;
            padding-left: 5px;
        }

        pre code {
            position: absolute;
            left: 0%;
            top: 0%;
            width: 100%;
            height: 100%;
            padding-left: 5px;
        }

        #code,
        #highlight {
            font-size: 14px;
            line-height: 1.5;
            font-family: 'Courier New', Courier, monospace;
        }
<div id="codeContainer">
        <div id="highlight"></div>
        <pre id="code">
            <code contenteditable="true"></code>
        </pre>
    </div>
const codeElement = document.getElementById('code');
        const highlightElement = document.getElementById('highlight');

        function updateHighlight() {
            const code = codeElement.innerText;
            var highlightedCode = Prism.highlight(code, Prism.languages.html, 'html');

            highlightElement.innerHTML = highlightedCode.toString();
        }

        codeElement.addEventListener('input', updateHighlight);

I am not really sure how I could fix this, and I don’t really know what is causing the issue.
Any help is appreciated. Thanks!

What’s the correct way to render a component on data change in the database? React

I working on a MERN project for learning purposes (not YT follow-up). I have a user model with a rank of 0 as default and with different score fields. I have created an endpoint that when the score fields meet certain conditions, the user rank gets updated 1. So far so good here and it works. My next step is to show a ‘you ranked up’ pop-up when the user rank changes and I am not sure what the best practice is for that. It’s a math-practice challenge and I want the pop-up to show between the end of the game and final score component. Any help is appreciated.

Endpoint:

import User from "../models/userModel.js";
import jwt from "jsonwebtoken";
import asyncHandler from "express-async-handler";

export const rankUp = asyncHandler(async (req, res) => {
  // Extract token from headers
  const token = req.headers.authorization.split(" ")[1];

  // Find the user by token
  const decoded = jwt.verify(token, process.env.JWT_SECRET);
  // Find user by id
  const user = await User.findOne({ _id: decoded.id });

  if (!user) {
    return res.status(404).send("User not found");
  }

  let newRank;

  if (
    user.userStats.totalScore === 5000 &&
    user.userStats.totalAdditionScore >= 1000 &&
    user.userStats.totalAdditionScore >= 1000 &&
    user.userStats.totalSubtractionScore >= 1000 &&
    user.userStats.totalMultiplicationScore >= 1000 &&
    user.userStats.totalOrderedScore >= 1000
  ) {
    newRank = 1;
  } else {
    throw new Error('Conditions not met')
  }

  // Save the updated user
  const updatedUserRank = await User.findByIdAndUpdate(
    { _id: decoded.id },
    { $set: { userRank: newRank } },
    { new: true }
  );

  if (updatedUserRank) {
    res.json({updatedUserRank});
  } else {
    res.status(400);
    throw new Error("Something went wrong");
  }
});

The component that I want to show the pop-up:

import { Divider, List, TextField, Typography } from "@mui/material";
import React, { useEffect } from "react";
import Navbar from "../components/Navbar";
import Container from "@mui/material/Container";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import { useState } from "react";
import { useNavigate } from "react-router";
import GameInfo from "./GameInfo";
import { useSelector, useDispatch } from "react-redux";

import {
  earnLife,
  gainPoints,
  gainTime,
  isFinished,
  loseLife,
  loseTime,
  restart,
} from "../features/gameSlice";
import { updateScore } from "../statsHandler";

const correctAnswer = <Typography>Correct!</Typography>;
const wrongAnswer = <Typography>Wrong!</Typography>;
const enterAnswer = <Typography>Enter your answer!</Typography>;

const MainInput = ({ operation, calculation }) => {
  const [enteredValue, setEnteredValue] = useState("");
  const [correctValue, setCorrectValue] = useState(false);
  const [calculatedNums, setCalculatedNums] = useState({});
  const [isIncorrect, setIsIncorrect] = useState(false);
  const [generateNewNumbers, setGenerateNewNumbers] = useState(false);
  const [haveToEnterAnswer, setHaveToEnterAnswer] = useState(false);
  const [streak, setStreak] = useState(0);

  const seconds = useSelector((state) => state.game.seconds);
  const points = useSelector((state) => state.game.points);
  const lives = useSelector((state) => state.game.lives);
  const gameOver = useSelector((state) => state.game.isFinished);
  const gameStart = useSelector((state) => state.game.startGame);

  const user = JSON.parse(localStorage.getItem("user"));

  const token = user.token;

  let finalScore = points;

  const navigate = useNavigate();

  // FIX THE UNDEFINED ISSUE

  // FIX THE UNDEFINED ISSUE

  // FIX THE UNDEFINED ISSUE

  useEffect(() => {
    if (gameOver) {
      updateScore(finalScore, operation, token);
    }
  }, [gameOver]);

  useEffect(() => {
    if (correctValue && streak === 4 && lives < 4) {
      dispatch(earnLife());
      setStreak(0);
    }
  }, [streak]);

  useEffect(() => {
    setCalculatedNums(calculation());
    setGenerateNewNumbers(false);
    setCorrectValue(false);
    setEnteredValue("");
  }, [generateNewNumbers]);

  const dispatch = useDispatch();

  const timerValid = lives > 0 && seconds > 0 && gameStart;

  const newChallenge = () => {
    setIsIncorrect(false);
    setHaveToEnterAnswer(false);
    dispatch(restart());
  };

  const handleCount = () => {
    if (timerValid) {
      dispatch(loseTime());
    }
  };

  useEffect(() => {
    if (lives === 0 || seconds === 0) {
      dispatch(isFinished());
    }
  }, [lives, seconds]);

  useEffect(() => {
    let interval;
    if (timerValid) {
      interval = setInterval(() => {
        handleCount();
        if (lives === 0 || seconds === 0) {
          clearInterval(interval);
        }
      }, 1000);
    }
    return () => {
      clearInterval(interval);
    };
  }, [timerValid]);

  const submitHandler = () => {
    if (correctValue) {
      setGenerateNewNumbers(true);
      dispatch(gainPoints());
      dispatch(gainTime());
      setStreak(streak + 1);
      console.log(user);
    }

    if (+enteredValue === calculatedNums.result) {
      setCorrectValue(true);
    } else if (enteredValue.length === 0) {
      setHaveToEnterAnswer(true);
    } else {
      setIsIncorrect(true);
      dispatch(loseLife());
      setStreak(0);
    }
  };

  const inputValueHandler = (value) => {
    setIsIncorrect(false);
    setHaveToEnterAnswer(false);
    setEnteredValue(value);
  };

  const submitOrTryNewOne = () => {
    return correctValue ? "Try new one" : "Submit";
  };

  const goHome = () => {
    navigate("/");
    dispatch(restart());
  };

  return (
    <>
      <Navbar />

      {seconds && lives > 0 ? (
        <>
          <GameInfo />
          <Container component="main" maxWidth="xs">
            <Box
              sx={{
                marginTop: 8,
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
              }}
            >
              <Typography>
                Fill in the box to make the equation true.
              </Typography>

              <Typography fontSize={28}>
                {operation !== "/"
                  ? `${calculatedNums.number1} ${operation} ${calculatedNums.number2}`
                  : `${calculatedNums.number2} ${operation} ${calculatedNums.number1}`}{" "}
                =
              </Typography>

              <TextField
                inputProps={{ inputMode: "numeric", pattern: "[0-9]*" }}
                type="number"
                name="sum"
                id="outlined-basic"
                label=""
                variant="outlined"
                onChange={(event) => {
                  inputValueHandler(event.target.value);
                }}
                disabled={correctValue}
                value={enteredValue}
              ></TextField>
              {haveToEnterAnswer && enterAnswer}
              {correctValue && correctAnswer}
              {isIncorrect && wrongAnswer}

              <Button
                type="button"
                sx={{ marginTop: 1 }}
                onClick={() => submitHandler()}
                variant="outlined"
              >
                {isIncorrect ? "Try again!" : submitOrTryNewOne()}
              </Button>
            </Box>
          </Container>
        </>
      ) : (
        <>
          <List
            sx={{
              marginTop: 8,
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
            }}
          >
            <Typography fontSize={28}>GAME OVER</Typography>
            <Divider></Divider>
            <Typography sx={{ marginTop: 2 }} fontSize={28}>
              Final Score: {points}
            </Typography>
            <Divider></Divider>
            <Button
              sx={{ marginTop: 2 }}
              variant="contained"
              size="large"
              onClick={newChallenge}
            >
              New Challenge
            </Button>
            <Button
              sx={{ marginTop: 2 }}
              variant="contained"
              size="large"
              onClick={goHome}
            >
              Home Page
            </Button>
          </List>
        </>
      )}
    </>
  );
};

export default MainInput;

JsonWebTokenError: login working but CRUD not Working

I write a code for a sample project of an ecommerce web application. Everything is working fine like login, registration, admin dashboard. Reading from api is perfectly working. Every protected admin route is working absolutely fine with POSTMAN. But whenever I try to create, update or delete a product from the frontend it throws a error as below. Please help me solve

JsonWebTokenError: jwt must be provided
[0] at module.exports [as verify] (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesjsonwebtokenverify.js:60:17)
[0] at requireSignIn (file:///C:/Users/Bangladesh%20One/Desktop/ReactJs/eCommerceApp/middlewares/authMiddleware.js:8:24)
[0] at Layer.handle [as handle_request] (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterlayer.js:95:5)
[0] at next (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterroute.js:144:13)
[0] at Route.dispatch (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterroute.js:114:3)
[0] at Layer.handle [as handle_request] (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterlayer.js:95:5)
[0] at C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterindex.js:284:15
[0] at Function.process_params (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterindex.js:346:12)
[0] at next (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterindex.js:280:10)
[0] at Function.handle (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterindex.js:175:3)

I tried with POSTMAN if my admin routes are working fine and I got positive result with POSTMAN.
But whenever I try to create, update, delete a product with frontend it throws error. But login , register is working fine

Here is my middleware

`import JWT from "jsonwebtoken";
import userModel from "../models/userModel.js";
import asyncHandler from "express-async-handler"

//Protected Routes token base
export const requireSignIn = async (req, res, next) => {
  try {
    const decode = JWT.verify(
      req.headers.authorization,
      process.env.JWT_SECRET
    );
    req.user = decode;
    next();
  } catch (error) {
    console.log(error);
  }
};

//admin acceess
export const isAdmin = async (req, res, next) => {
  try {
    const user = await userModel.findById(req.user._id);
    if (user.role !== 1) {
      return res.status(401).send({
        success: false,
        message: "UnAuthorized Access",
      });
    } else {
      next();
    }
  } catch (error) {
    console.log(error);
    res.status(401).send({
      success: false,
      error,
      message: "Error in admin middelware",
    });
  }
};`

Get Data from API – And Display

enter image description here
How to map the data inside choice
I used data.data.content.forEach to display other data. For choice how to do
Thank you

let formData1= ”;
data.data.content.forEach((user,index) => {
formData1 +=`

            <label for="inputEmail4">Type</label>
            <select class="custom-select mr-sm-2" id="typeSelect-${index + 1}" name="type">
                <option selected>Choose...</option>
                <option value="Multiple Choice">Multiple Choice</option>
                <option value="Email">Email</option>
                <option value="Short Text">Short Text</option>
              </select>
        </div>
        </div>

         
        <div class="form-group row justify-content-center">
            <div class="col-lg-6">
            <label for="inputEmail4">Question</label>
            <input type="text" name="question" value="${user.question}" class="form-control" id="question" placeholder="">
        </div>
        </div>
        <div id="choice-div" class="form-group row justify-content-center">
            <div class="col-lg-6">
            <label for="inputEmail4">Choice</label>
            <input type="text" class="form-control" id="choice" name="choice" placeholder="" value="${user.choice}">
        </div>
        </div>

})

I want to display the choice individually in html

waitForSelector timing out even tho the element is on screen

I’m building a checkout bot and I’m haveing truble geting past one of those dumb “enter your phonenumber for text” pop ups that sites do, the element I’m telling the bot to click is appering on screen but the bot wont click it. This is my first project ever on javascript and I have no Idea what I’m doing, I’m kinda taking the learn as you go aproach to coding right now and I’m learning a lot but Im really stuck here and I cant find what I am doing wrong.

async function regectingnumber(page) {
    try {
        console.log("Rejecting number")
        //await waitForTimeout(2000)
        //await page.setDefaultNavigationTimeout(60000);
        console.log("waiting...")
        await page.waitForSelector('button[class= css-10e85z4 errp0sa0]', {timeout:60000})
         console.log("waiting...")
         await page.evaluate(() => document.getElementsByClassName('button css-10e85z4 errp0sa0')[0].click());
        console.log("Number entered!");
        //await page.click('button[class="css-yq30jm e5ippug0"]');
        //console.log("Number rejected!");
    } catch (err) {
        console.error(err);
    }
}

this is just a small part of the code the part that im specifcally getting a error on because it wont let me post the full thing without calling it spam

Split array of objects to multiple arrays

I have an array like this :

[ { id: '1', quantity: 5 }, { id: '1', quantity: 5 }, { id: '1', quantity: 5 }, { id: '1', quantity: 3 }, { id: '2', quantity: 5 }, { id: '2', quantity: 5 }, { id: '2', quantity: 2 }, { id: '3', quantity: 5 }, { id: '3', quantity: 4 } ]

I want the result to be like this:
[ {products: [{id: 1, quantity: 5}, {id: 2, quantity: 5}, {id: 3, quantity: 5}]}, {products: [{id: 1, quantity: 5}, {id: 2, quantity: 5}, {id: 3, quantity: 4}]}, {products: [{id: 1, quantity: 5}, {id: 2, quantity: 2}]}, {products: [{id: 1, quantity: 3}]} ]

There should not be any duplicate IDs inside each products.

Thank you in advance.

flutter web build JS function with external JS library

I am going to build the JS function which calls external JS library.

// import external library
import 'https://cdn.jsdelivr.net/npm/[email protected]/dist/pica.min.js';

function resize(param) {
    var src = param["src"];
    var toWidth = param["toWidth"];    
    //var callback = param["callback"];
    
    // call function in external library
    return resizeBuffer({
        src: src,
        toWidth: toWidth,

    });
}

Is this correct?

Why Does “Throw new Error” logs the error in console instead of sending it as HTTP Response

I have been trying to develop an authentication system using Typescript, ts-node, nodemon, Express & Mongoose. I am not very experienced with Typescript but doing throwing the errors in Javascript Node Server by “Throw new Error()” seemed to send that message as a response to the frontend where I could read it in “err.message”. Doing so in Typescript doesn’t work, rather it logs the error in the console and crashes the server. Please Drop your suggestions.
Error Handler and console window

Throwing new error.

How to make hover work correct for mobile?

I have lots and lots of code written already for the website that I’m launching soon, but I forget one really important thing. The hover effect doesn’t work correct on mobile. I know that it kind of works when you click it, but that’s not what I want. I want an touchstart and touchend effect for mobile. Is there an easy Javascript code that can fix all the hover effects? Because it’s not just about one class hover effect, but there are many. Like the button effect and the flipcards that will flip when you hover them.

There is too much code to post here, but here is a link to my dummy site.

Is there anyone who can help me solve my problem please? I know this is kind of a basic question, but I see so much different things on the internet that I don’t know what to do. I can’t write a Javascript code for every hover effect that’s on the side. I also don’t know how to fix it with the media query (hover: hover) or (hover:none) because I want an touchstart and touchend effect.

Hope someone has the time to help me, it would mean a lot to me. Thank you in advance.

Uncaught Error: useRecaptcha() is called without provider. while import Checkbox inside script setup tag in Vue3

I want to use ReCAPTCHA for my portfolio website to prevent intended email contact spamming to EmailJS, but when I followed the documentations, it show an error Uncaught Error: useRecaptcha() is called without provider.

I tried both of with @unhead/vue and without @unhead/vue

using @unhead/vue

main.js

import { createApp } from 'vue'
import { createHead } from '@unhead/vue'
import { VueRecaptchaPlugin } from 'vue-recaptcha'
import './style.css'
import App from './App.vue'


const app = createApp(App)
const head = createHead()
app.use(head)
app.use(VueRecaptchaPlugin, {
  v2SiteKey: import.meta.env.VITE_RECAPTCHA_SITE_KEY,
})
app.mount('#app')

App.vue

<script setup>

import Navbar from './components/Navbar.vue'
import Projects from './components/Projects.vue'
import About from './components/About.vue'
import Contact from './components/Contact.vue';

import { useRecaptchaProvider } from 'vue-recaptcha'
useRecaptchaProvider()

</script>

<template>
  <Navbar/>
  <div id="about">
    <About/>
  </div>
  <div id="work-experience">
    Work Experience
  </div>
  <div id="projects">
    <Projects/>
  </div>
  <div id="contact">
    <Contact/>
  </div>
</template>

...

Contact.vue

<script setup>

import { Checkbox } from 'vue-recaptcha';

</script>

<template>
  <div class="container">
    <div class="contact">
      <h2>Reach me</h2>
      <div class="social">

      </div>
    </div>
    <form ref="form" @submit.prevent="sendEmail">
      <div class="form">
        <input type="text" name="from_name" placeholder="Name">
        <input type="email" name="from_email" placeholder="Email">
        <input type="text" name="company_name" placeholder="Company">
        <textarea name="message" placeholder="Message"></textarea>
        <Checkbox/>
        <button type="submit">Send</button>
      </div>
    </form>
  </div>
</template>

Warning

[Vue warn]: injection "Symbol(vue-recaptcha-context)" not found. 
  at <Checkbox> 
  at <Contact> 
  at <App>
[Vue warn]: [vue-recaptcha]: You may forget to `use` vue-recaptcha plugin 
  at <Checkbox> 
  at <Contact> 
  at <App>
[Vue warn]: Unhandled error during execution of setup function 
  at <Checkbox> 
  at <Contact> 
  at <App>

Error

Uncaught Error: useRecaptcha() is called without provider.
    at useRecaptchaContext (context.mjs?v=40414563:8:11)
    at useAssertV2SiteKey (context.mjs?v=40414563:17:15)
    at useChallengeV2 (challenge-v2.mjs?v=40414563:12:19)
    at useComponentV2 (component-v2.mjs?v=40414563:5:83)
    at setup (Checkbox.vue:46:18)
    at callWithErrorHandling (runtime-core.esm-bundler.js:173:22)
    at setupStatefulComponent (runtime-core.esm-bundler.js:7265:29)
    at setupComponent (runtime-core.esm-bundler.js:7220:11)
    at mountComponent (runtime-core.esm-bundler.js:5542:13)
    at processComponent (runtime-core.esm-bundler.js:5517:17)

not using @unhead/vue is same as using but not create head and change import as vue-recaptcha/head Also, I get the same warning and error as using @unhead/vue

onClick matche the right word and move on if not set allert to wrong word

i want if the user clicks the right word to move on to the next word and if it is wrong th set the allert to wrong word.
now even when it is the right answer the allert is rendernig!!

i tryied several ways and doesnot work

i ssems like i’m using somthing wron in the boxclicked and actually i dont know if there is somthing else

here is my code

const ParFour = () => {
  const [boxPosition, setBoxPosition] = useState({ x: 0, y: 0 });
  const containerSize = { width: 400, height: 400 };
  const boxSize = { width: 50, height: 50 };
  const [gameOver, setGameOver] = useState(false);
  const [currentWordIndex, setCurrentWordIndex] = useState(0);
  const [boxesClicked, setBoxesClicked] = useState(0);
  const totalBoxes = 3;

 const handleBoxClick = (event) => {
  if (!gameOver) {
    const box = event.target;
    const currentMeaning = words[currentWordIndex].currectBedeutungIndex;
    const clickedWord = box.getAttribute('data-word');
    if (box.style.display !== 'none') {
      if (clickedWord === currentMeaning) {
        box.style.display = 'none';
        setBoxesClicked((prevBoxesClicked) => prevBoxesClicked + 1);
        setCurrentWordIndex((prevIndex) => prevIndex + 1);
      } else {
        alert('Wrong word!');
      }
    }
    if (boxesClicked + 1 === totalBoxes) {
      setGameOver(true);
    }
  }
};



  const currentWord = words[currentWordIndex];  
  const currentMeaning = currentWord.bedeutung[0];

  return (
    <div className='part-four-container'>
      <div>
          <p className='bedeutung-container' key={0}>{currentMeaning}</p>
      </div>

      {!gameOver && (
        <div>
          <div
            className='hallo'
            data-word="hallo"
            style={{
              top: `${boxPosition.y}px`,
              left: `${boxPosition.x}px`,
            }}
            onClick={handleBoxClick}
            //onClick={(event) => handleBoxClick(event, 'hallo')}
           // onClick={(event) => handleBoxClick(event)}
            //onClick={hadleRightClick}
           //onClick={handleBoxClickAndRightClick}
          >
            hallo
          </div>

          <div
            className='danke'
            data-word="danke"
            style={{
              top: `${boxPosition.y * Math.floor(Math.random() * 5)}px`,
              left: `${boxPosition.x * Math.floor(Math.random() * 5)}px`,
            }}
            onClick={handleBoxClick}
           // onClick={(event) => handleBoxClick(event, 'danke')}
          // onClick={(event) => handleBoxClick(event)}
           //onClick={hadleRightClick}
          // onClick={handleBoxClickAndRightClick}
          >
            danke
          </div>

          <div
            className='gutenMorgen'
            data-word="gutenMorgen"
            style={{
              top: `${boxPosition.y * Math.floor(Math.random() * 5)}px`,
              left: `${boxPosition.x * Math.floor(Math.random() * 5)}px`,
            }}
            onClick={handleBoxClick}
          // onClick={(event) => handleBoxClick(event, 'gutenMorgen')}
       //   onClick={(event) => handleBoxClick(event)}
          //onClick={hadleRightClick}
         // onClick={handleBoxClickAndRightClick}
      > Guten Morgen</div>
      

</div>)}

        {gameOver && (
      <div >
        <p className='game-over'>Spiel ist aus</p>
      <button className='gam-over-button' onClick={handleRefreshClick}>nochmal abspielen</button>
       
      </div>
      )}

    </div>
  );
};

export default ParFour;

and here is my array

const words = [
    {
        word: 'Hallo',
        bedeutung: ['مرحبا','اهلا'],
        currectBedeutungIndex: 0,
    },
    {
        word: 'Guten Morgen',
        bedeutung: ['صباح الخير','مرحبا'],
        currectBedeutungIndex: 0,
    },

]

When debugging React v18 source code, I installed @babel/preset-flow as prompted, but I still get an error

Recently, I wanted to debug the source code of React v18 locally. The main operations I performed are as follows:
1.Downloaded the source code of React from GitHub and generated a build file locally;

build
     ....
     oss-experimental
     oss-stable
     ...
  1. Entered the /build/oss-stable/react and /build/oss-stable/react-dom directories of oss-stable and created links using yarn link;

  2. Created a project named react-debug using react-create-app, installed dependencies, executed yarn link react and react-dom, and started the project, but encountered an error message;

Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Support for the experimental syntax 'flow' isn't currently enabled (11:8):

   9 |
  10 | // Keep in sync with https://github.com/facebook/flow/blob/main/lib/react.js
> 11 | export type StatelessFunctionalComponent<P> =
     |        ^
  12 |   React$StatelessFunctionalComponent<P>;
  13 | export type ComponentType<-P> = React$ComponentType<P>;
  14 | export type AbstractComponent<

Add @babel/preset-flow (https://github.com/babel/babel/tree/main/packages/babel-preset-flow) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add @babel/plugin-syntax-flow (https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-flow) to the 'plugins' section to enable parsing.
...

4.Installed @babel/preset-flow and @babel/plugin-transform-flow-strip-types according to the prompt, but still encountered the error shown in the figure;

5.Configured babel.

 "babel": {
    "plugins":["@babel/plugin-transform-flow-strip-types",
    ["@babel/plugin-proposal-decorators",{ "legacy": true }]],
    "presets": ["@babel/preset-flow"]
  }

Note: To ensure that the configuration in babel has taken effect, I tested the @babel/plugin-proposal-decorators plugin separately, and it worked, but @babel/preset-flow and @babel/plugin-transform-flow-strip-types did not work. Please help me with this problem.

NextJS server components are running in the client side too

I am tring to use MUI v5.11.16 with nextjs v13.3.0 and setup my nextjs project as the official documentation suggests here and I am able to use MUI components without writing "use client" at the top of my files.

The issue is that I tried to check if a component is server component or not. I putted a console.log("type of window: ", typeof window) to see if typeof window is undefined it is server component, or if that is an object it is a client component.

import * as React from "react";
import Container from "@mui/material/Container";
import Typography from "@mui/material/Typography";
import Box from "@mui/material/Box";
import { Button } from "@mui/material";

export default function Home() {
  console.log("this typeof window: ", typeof window)
  
  return (
    <Container maxWidth="lg">
      <Typography>
      </Typography>
      <Box
        sx={{
          my: 4,
          display: "flex",
          flexDirection: "column",
          justifyContent: "center",
          alignItems: "center",
        }}
      >
        <Typography variant="h4" component="h1" gutterBottom>
          Material UI - Next.js example in TypeScript
        </Typography>
        <Button
          variant="outlined"
          onClick={() => {
            console.log("clicked!");
          }}
        >
          TESTing Button
        </Button>
      </Box>
    </Container>
  );
}

I realized that the console.log is executing on both server side and client side, it logs the typeof window: undefined in the server log and prints the typeof window: object in browsers console. Why it is running on both sides?

I tried putting use client at the top of the file, again that was logged in the server too. what is really happening here ?

Got error: “Uncaught Error: Service firestore is not available” while working with firebase

I’m working on a website, and have decided to use firebase as a host/database server. I use npm to manage my firebase sdk, and have run into an error while trying to import firestore into my site. Yes, my firestore database is readable and writable on the dev console, so it definitely exists.

As an attempt to fix the issue, I decided to make a firebase.js where I import from firebase and then export my database to use on other pages and scripts. Here is firebase.js:

import { initializeApp } from "./node_modules/firebase/firebase-app.js"
import { getFirestore, collection, addDoc } from './node_modules/firebase/firebase-firestore.js';

const firebaseConfig = {
    //config
};  
export const app = initializeApp(firebaseConfig)
export const db = getFirestore(app)
export { collection, addDoc}

The above gives me the error:

provider.ts:130 Uncaught Error: Service firestore is not available

The reason I am using /node_modules/firebase instead of just firebase/ is because it gives me the error:

Uncaught TypeError: Failed to resolve module specifier "firebase/firebase-app.js". Relative references must start with either "/", "./", or "../".

If I use a static page, like https://www.gstatic.com/firebasejs/9.19.1/firebase-firestore.js as my import location, it will say

provider.ts:130 Uncaught Error: Service firestore is not available

I’ve seen 2 other posts relating to this and tried the suggestions there, but none of it was any help. Other import statements work as my package.json has “type”: “module” and for my dependencies I had {“firebase”: “^9.19.1”}. Any help is appreciated.

this is undefined inside prototype function

I have below two functions in two seperate files:

//homeFunction.js

import secondaryFunc from "./secondaryFunction.js";

const secFunc = new secondaryFunc(3);

secFunc.sayHello(5);

The another file is secondaryFunction.js:

function secondaryFunc(val){
    this.val = val;
}

secondaryFunc.prototype.sayHello = (val1)=>{
    console.log(this);
    console.log("Hello");
}

export default secondaryFunc;

Here, when I execute homeFunction, this is undefined inside sayHello function, which I don’t understand because I have already created a reference to the secondaryFunc, which has sayHello as a property, so this should not be undefined inside sayHello. Please help me to understand this anomaly.

Thanks!