ReactJS: How to show links in column in a table

I have below code. I fetch the data from back end and show as a table. This works fine. Now my task is to show 1st column in table as a link. How can I do that?

const EditController = () => {

    const initState = [
        {name: "", ipaddr: "", port: 0, sshuser: "", sshport: 0, license: ""},
    ];
    
    const [state, setState] = useState(initState);
    const user = localStorage.getItem("user");
    const token = localStorage.getItem("jwt");
    
    const fetchControllers = async () => {
        try {
            const res = await axios.post('/exec/editcontroller', {user} , {headers: {
              'Content-Type': 'application/json',
              'Authorization': token,
            }}).then( function (res) {
                
                if(res.status === 200) {
                    setState(res.data);
                }else {
                    return 'failure';
                }
                
            });
        }catch(err) {
            return 'error';
        }
    }
    
    useEffect ( () => {
       console.log('Inside useEffect');
       fetchControllers();
    }, []);
        
    return (
        <div className="medium-text">
            <div className="center">
                <h2>Controllers</h2>
                <table id="tbl">
                
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>IP Address</th>
                            <th>Port</th>
                            <th>SSH User</th>
                            <th>SSH Port</th>
                            <th>License</th>
                        </tr>
                    </thead>                
                    
                    {state.map((item) => (
                        <tr key={item.id}>
                        {Object.values(item).map((val) => (
                            <td>{val}</td>
                        ))}
                        </tr>
                    ))}
                
                </table>    
            </div>
        </div>
    );
}

export default {EditController};

UI loading before set value of a variable in subsribe in angular

 `isReqReviewSelected: boolean = false;`

ngOnInit() { this.getIntProgReviewCommentsById(this.selectedAgendaId); console.log(Reviewe:'+this.isReqReviewSelected); //Always false - Ui render before value set }

`getAgendasById() {
    this.agendasService.getAgendasById(this.selectedAgendaId ?? 0)
   .pipe(takeUntil(this._destroying$))
   .subscribe({
    next: (res: any) => {
      this.agenda = res;
      this.eventId = res.eventId;
      this.isReqReviewSelected = this.agenda.reqReview ?? false;
      console.log('est' + res.reqReview); // Here the value got changed
    },
    error: (err) => {
      console.log(err);
     }
      }
      );
  }`

<ng-template pTemplate *ngIf=”isReqReviewSelected”> //Always false

I tried with return type of observable but not worked

loop through querySelectAll nodelist (Uncaught TypeError: Cannot read properties of undefined)

I know I can use querySelector(“#sub_menuid”); directly., but my plan is to have nested sub menu
and able to loop through them all later.

I’m trying to querySelectAll my ul submenu into an array and do some DOM operations with it later.
After doing

globalThis.allsubmenu_nodelist =  document.querySelectorAll("#"+ submenu.id + " > li > ul");

It does not return an array which is what I’m expecting, it return a nodelist instead.

        console.log("->"+ submenu_list[i].id +"<-");
        console.log("->"+ submenu_list[i].innerHTML +"<-");

I’m using Google chrome. Strangely when I inspect the page
I’m able to see the result in console log and yet the console prompt Uncaught TypeError
for every line I use submenu_list[i].id or .innerHTML

Uncaught TypeError: Cannot read properties of undefined (reading 'id')
Uncaught TypeError: Cannot read properties of undefined (reading 'iinnerHTML')

when I type the following at console: submenu_list[0].id or submenu_arr[0].id
it can give me the result. But why the console give Uncaught TypeError for every line I use submenu_list[i].id or .innerHTML. When I comment out the console.log(“->”+ submenu_list[i].id +”<-“);
it gave me Uncaught TypeError for the next line with submenu_list[i].id

When I pass submenu_arr[i] to toggleDropdownMenu call
the console.log writeout that the submenu is undefined inside toggleDropdownMenu call,
and can’t use classList
passUncaught TypeError: Cannot read properties of undefined (reading ‘classList’)

Did I convert it successfully in array? why it give me uncaught Type Error?
Can anyone help me with this?

Can anyone point me to an article or sample code where I can go through the node list to get the id & innerHTML without converting it to an array?

I may not know why javascript return querySelectAll in nodelist instead of an array, I think they should have made a simple method to convert it into array and made simpler for javascript users.

I use global for debugging purpose in browser console log

here is my HTML code:

            <ul id="mainmenu" class="nav_menu">
                <li class="nav_item"><a href="#" class="nav_link">Home</a></li>
                <li class="nav_item"><a href="javascript:void(0);" id="newsreview-toggle" class="nav_link submenu-toggle">News & Review</a>
                    <ul id="newsreview" class="sub_menu">
                        <li class="nav_item"><a href="#" class="nav_link">News</a></li>
                        <li class="nav_item"><a href="#" class="nav_link">Review</a></li>
                    </ul>
                </li>
                <li class="nav_item"><a href="javascript:void(0);" id="categories-toggle" class="nav_link submenu-toggle">Categories</a>
                    <ul id="categories" class="sub_menu">
                        <li class="nav_item"><a href="#" class="nav_link">Movies</a></li>
                        <li class="nav_item"><a href="#" class="nav_link">Sports</a></li>
                        <li class="nav_item"><a href="#" class="nav_link">Games</a></li>
                    </ul>
                </li>
            </ul>

here are my javascript code:

function toggleDropdownMenu (submenu){
    console.log("submenu: ->"+ submenu +"<-"); // How come this gives undefined at consol.log
    submenu.classList.toggle('nav--visible'); // console log gives: Uncaught TypeError: Cannot read properties of undefined (reading 'classList')

    if (submenu.classList.contains('nav--visible')) {
        console.log("Show Menu");
    } else {
        console.log("Hide Menu");
    }
}

cconst mainmenu = document.querySelector('#mainmenu');

function initMenu (submenu){
    // globalThis.allsubmenu = document.querySelectorAll("#"+ submenu.id + " > li > ul");
    globalThis.alltoggles = document.querySelectorAll("#"+ submenu.id + " > li > a.submenu-toggle"); //querySelectAll will return a nodelist
    globalThis.allsubmenu_nodelist = document.querySelectorAll("#"+ submenu.id + " > li > ul"); //querySelectAll will return a nodelist
    globalThis.submenu_list = [];
    //globalThis.allsubmenu = Array.from(allsubmenu_nodelist).map(elem => {console.log(elem)}); //this line doesn't convert it to array
    globalThis.allsubmenu = Array.from(allsubmenu_nodelist).map(elem => {submenu_list.push(elem)});
    // allsubmenu has array of 2 with undefined value inside, is this correct?

    globalThis.alltoggles_arr = [];
    globalThis.submenu_arr = [];
    for (var i=0; i<= submenu_list.length; i++){
        //console.log("->"+ submenu_list[i].id +"<-");
        //console.log("->"+ submenu_list[i].innerHTML +"<-");
        //submenu_arr[i] = document.querySelector("#"+ allsubmenu_nodelist[i].id);
        alltoggles_arr[i] = document.querySelector("#"+ alltoggles[i].id);
        submenu_arr[i] = document.querySelector("#"+ submenu_list[i].id);
        //console.log("-->"+ submenu_arr[i].id +"<--");
        //console.log("-->"+ submenu_arr[i].innerHTML +"<--");

        alltoggles_arr[i].addEventListener('click', function(e) {
            e.stopPropagation();
            toggleDropdownMenu(submenu_arr[i]);
        });

    }
    console.log(alltoggles_arr); //Did I convert it successfully in array? why it give me uncaught Type Error?
    console.log(submenu_arr); //The console log shows the result, but why  uncaught Type Error for 
}

initMenu(mainmenu);

Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist. from scripts/background.js

i am doing a chrome extension project with manifest v3.

I tried to follow different tutorial/similar questions asked in over the web but it didnt able to solve the error.

Currently, the background.js is able sendmessage to content.js as intented. But I still wish to solve the error. Any help will be greatly appreciated!

Error:

Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.

Context:

scripts/background.js

Stack Trace

scripts/background.js:0 (anonymous function)

My code:
manifest.json

{
  "manifest_version": 3,
  "name": "YT Extension",
  "description": "Youtube extension",
  "version": "1.0.0",
  "icons": {
    "16": "assert/icons/icon16.jpeg",
    "32": "assert/icons/icon32.jpeg",
    "48": "assert/icons/icon48.jpeg",
    "128": "assert/icons/icon128.jpeg"
  },
  "background": {
    "service_worker": "./scripts/background.js",
    "type": "module"
  },
  "content_scripts": [ {
    "matches":["<all_urls>"],
    "run_at": "document_end",
    "js": ["./scripts/contentScript.js"]
  } ],
  "action": {
    "default_popup": "popup.html"
  },
  "host_permissions": [
    "https://www.youtube.com/*"
  ],
  "permissions": [
    "storage",
    "tabs"
  ]
}

scripts/background.js

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === 'complete') {
    console.log("background.js running...")

    if (tab.url && tab.url.includes("youtube.com/watch")) {
      console.log("Sending message: VIDEO")
      chrome.tabs.sendMessage(tabId, {
        type: "VIDEO",
      });
    }

    else if (tab.url && tab.url.includes("youtube.com/")) {
      console.log("Sending message: MAIN")
      chrome.tabs.sendMessage(tabId, {
        type: "MAIN",
      });
    }

    else {
      console.log("Sending message: NOT SUPPORTED")
      chrome.tabs.sendMessage(tabId, {
        type: "NOT SUPPORTED",
      });
    }

  }
}
)

scripts/contentScript.js

chrome.runtime.onMessage.addListener((obj, sender, response) => {
    const { type } = obj;
    console.log("content.js running...")

    if (type === "VIDEO") {
        console.log("Received message: VIDEO")
    }
    else if (type === "MAIN") {
        console.log("Select video")
    }
    else if (type === "NOT SUPPORTED") {
        console.log("Website not supported")
    }
}
);

Why the child state is not updated?

Here is Parent.js source code:

import React,{useState} from "react";
import Child from "./Child";
export default function Parent(){
   const[count,setCount]=useState(0);
   return <Child count={count} setCount={setCount}/>
}

the Child.js source code:

import React,{useReducer} from "react";
let reducer = (state, action) => {
  let result = { ...state };
  return result;
}
export default function Child({count,setCount}){
  console.log("hi");
  const[text,setText]=useReducer(reducer,count);
  return <>{text}<button onClick={()=>{setCount(count+1)}}>Go</button></>
}

My problem is why the variable “text” in Child.js is not updated. at the same time, the variable “count” in Child.js can be updated.

Redux Store cartItems is not accepting data when the addToCartHandler is called in Nextjs

I am in the process of creating an ecommerce website where I stumble on this problem when I try to run the addToCartHandler through a button. I have everything as I am supposed to but for some unknown reason, the cartItems I try to push data to returns undefined with the following error message TypeError: Cannot read properties of undefined (reading 'push'), which typically indicates that somewhere in your code, an attempt is made to access the push method which is state.cartItems array that is undefined.

Please help me find a possible solution with the related code below:

store/index.js

import { configureStore } from "@reduxjs/toolkit";
import { combineReducers } from "redux";
import thunk from "redux-thunk";
import storage from "redux-persist/lib/storage";
import { persistReducer } from "redux-persist";
import cart from "./cartSlice";

const reducers = combineReducers({ cart });
const config = {
  key: "root",
  storage,
};
const reducer = persistReducer(config, reducers);

const store = configureStore({
  reducer: reducer,
  devTools: process.env.NODE_ENV !== "production",
  middleware: [thunk],
});

export default store;

store/index.js

import { createSlice } from "@reduxjs/toolkit";
const initialState = {
  cartItems: [],
};
export const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addToCart(state, action) {
      console.log("Adding to cart:", action.payload);
      state.cartItems.push(action.payload);
    },
    updateCart(state, action) {
      state.cartItems = action.payload;
    },
    emptyCart(state, action) {
      state.cartItems = [];
    },
  },
});

export const { addToCart, updateCart, emptyCart } = cartSlice.actions;

export default cartSlice.reducer;

pages/_app.js

import "@/styles/globals.scss";
import { Provider } from "react-redux";
import { SessionProvider } from "next-auth/react";
import { PersistGate } from "redux-persist/integration/react";
import { persistStore } from "redux-persist";
import Head from "next/head";
import store from "@/store";

let persistor = persistStore(store);

export default function App({
  Component,
  pageProps: { session, ...pageProps },
}) {
  return (
    <>
      <Head>
        <title>Nails Republic</title>
        <meta
          name="description"
          content="The one stop online shop for all of your manicure and pedicure needs."
        />
        <link rel="icon" href="/nails_republic_icon.png" />
      </Head>
      <SessionProvider session={session}>
        <Provider store={store}>
          <PersistGate loading={null} persistor={persistor}>
            <Component {...pageProps} />
          </PersistGate>
        </Provider>
      </SessionProvider>
    </>
  );
}

productPage

import Rating from "@mui/material/Rating";
import React, { useState, useEffect } from "react";
import { useRouter } from "next/router";
import Link from "next/link";
import { TbPlus, TbMinus } from "react-icons/tb";
import { BsHandbagFill, BsHeart } from "react-icons/bs";
import { useDispatch, useSelector } from "react-redux";
import { signIn, useSession } from "next-auth/react";
import axios from "axios";
import styles from "./styles.module.scss";
import { addToCart, updateCart } from "@/store/cartSlice";

export default function Infos({ product, setActiveImg }) {
  const router = useRouter();
  const dispatch = useDispatch();
  const { data: session } = useSession();
  const [size, setSize] = useState(router.query.size);
  const [qty, setQty] = useState(1);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const { cart } = useSelector((state) => ({ ...state }));
  console.log("Cart state:", cart);

  useEffect(() => {
    setSize("");
    setQty(1);
  }, [router.query.style]);
  useEffect(() => {
    if (qty > product.quantity) {
      setQty(product.quantity);
    }
  }, [router.query.size]);
  const addToCartHandler = async () => {
    if (!router.query.size) {
      setError("Please Select a size");
      return;
    }
    const { data } = await axios.get(
      `/api/product/${product._id}?style=${product.style}&size=${router.query.size}`
    );
    if (qty > data.quantity) {
      setError(
        "The selected quantity is more than in stock. Try and lower the Qty"
      );
    } else if (data.quantity < 1) {
      setError("This Product is out of stock.");
      return;
    } else {
      let _uid = `${data._id}_${product.style}_${router.query.size}`;
      dispatch(
        addToCart({
        ...data,
        qty,
        size: data.size,
        _uid,
      );
    }
  };
  return (
    <div className={styles.infos}>
      <div className={styles.infos__container}>
        <h1 className={styles.infos__name}>{product.name}</h1>
        <h2 className={styles.infos__sku}>{product.sku}</h2>
        <div className={styles.infos__rating}>
          <Rating
            name="half-rating-read"
            defaultValue={product.rating}
            precision={0.5}
            readOnly
            style={{ color: "#5a141d" }}
          />
          ({product.numReviews}
          {product.numReviews == 1 ? " review" : " reviews"})
        </div>
        <div className={styles.infos__price}>
          {!size ? <h2>{product.priceRange}</h2> : <h1>{product.price}₦</h1>}
          {product.discount > 0 ? (
            <h3>
              {size && <span>{product.priceBefore}₦</span>}{" "}
              <span>(-{product.discount}%)</span>
            </h3>
          ) : (
            ""
          )}
        </div>
        <span className={styles.infos__shipping}>
          {product.shipping
            ? `+${product.shipping}$ Shipping fee`
            : "Free Shipping"}
        </span>
        <span>
          {size
            ? product.quantity
            : product.sizes.reduce((start, next) => start + next.qty, 0)}{" "}
          pcs left.
        </span>
        <div className={styles.infos__sizes}>
          <h4>Select a Size : </h4>
          <div className={styles.infos__sizes_wrap}>
            {product.sizes.map((size, i) => (
              <Link
                href={`/product/${product.slug}?style=${router.query.style}&size=${i}`}
              >
                <div
                  className={`${styles.infos__sizes_size} ${
                    i == router.query.size && styles.active_size
                  }`}
                  onClick={() => setSize(size.size)}
                >
                  {size.size}
                </div>
              </Link>
            ))}
          </div>
        </div>
        <div className={styles.infos__colors}>
          {product.colors &&
            product.colors.map((color, i) => (
              <span
                className={i == router.query.style ? styles.active_color : ""}
                onMouseOver={() =>
                  setActiveImg(product.subProducts[i].images[0].url)
                }
                onMouseLeave={() => setActiveImg("")}
              >
                <Link href={`/product/${product.slug}?style=${i}`}>
                  <img src={color.image} alt="" />
                </Link>
              </span>
            ))}
        </div>
        <div className={styles.infos__qty}>
          <button onClick={() => qty > 1 && setQty((prev) => prev - 1)}>
            <TbMinus />
          </button>
          <span>{qty}</span>
          <button
            onClick={() => qty < product.quantity && setQty((prev) => prev + 1)}
          >
            <TbPlus />
          </button>
        </div>
        <div className={styles.infos__actions}>
          <button
            disabled={product.quantity < 1}
            style={{ cursor: `${product.quantity < 1 ? "not-allowed" : ""}` }}
            onClick={() => addToCartHandler()}
          >
            <BsHandbagFill />
            <b>ADD TO CART</b>
          </button>
        </div>
        {error && <span className={styles.error}>{error}</span>}
        {success && <span className={styles.success}>{success}</span>}
      </div>
    </div>
  );
}

What is the benefit of using an IIFE to create a module? [closed]

I am a JS beginner looking at this lesson on freeCodeCamp:

https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/use-an-iife-to-create-a-module

Here is the code in the example they provide:

let motionModule = (function () {
  return {
    glideMixin: function(obj) {
      obj.glide = function() {
        console.log("Gliding on the water");
      };
    },
    flyMixin: function(obj) {
      obj.fly = function() {
        console.log("Flying, wooosh!");
      };
    }
  }
})();

I do not see what the benefit of using an IIFE is here. If we just directly assign the object to motionModule (instead of executing an IIFE that does one thing – return that same object) not only is it easier to read but it saves us a step (we don’t need to execute the IIFE).

So what is the benefit here? I had a bit of a chat with ChatGPT and it was saying a couple of things, some of which I list below:

  1. In the IIFE approach the methods names won’t interfere with outside method/function names. Is that not the same with the “non-IIFE” approach (i.e just assigning the object to motionModule directly)? In both approaches, the methods are kept to the context of that object, so if you create functions with the same name outside of that object it wouldn’t matter – there wouldn’t be any conflict.

  2. It also says that in the IIFE approach the methods are not added to the global scope – are they not? When you return the object in the IIFE (which contains those functions – they are properties of the object), it gets assigned to the global variable motionModule, which means the object (and its properties – the methods) are added to the global scope.

  3. ChatGPT also stressed that the methods are private in the IIFE approach, and can’t be accessed from outside the module. I don’t quite understand what this is getting at. Whether you use the IIFE approach or the “direct” approach, the only way to access those methods is through the motionModule object, right? Or is there a way (aside from using the motionModule variable) to access those methods in the “direct” (non-IIFE) approach that I am not aware of?

I know some people don’t like having several questions in one post so my main question is stated in the title: What is the benefit of using an IIFE to create a module?

The code example that lead to this question is found in the example (and link) above and secondary questions I found myself asking while researching the main question can be found in points 1. 2. and 3. However, since I have outlined the main question above I hope this post does not get flagged for not being focused. Please feel free to answer the secondary questions but I think my main question should be clear.

Thanks in advance!

How to syntax highlight nested text with Prism in this language?

I have a CodeSandbox here, which shows this:

import React from "react";
import ReactDOM from "react-dom";
import { PrismLight as Code } from "react-syntax-highlighter";

// Code.registerLanguage('xml', xml)

note.displayName = "note";

/** @type {import('../core.js').Syntax} */
function note(Prism) {
  // https://www.json.org/json-en.html
  Prism.languages.note = {
    comment: {
      pattern: /# .*n?/,
      greedy: true,
    },
    bracketed_term: {
      pattern: /{{([a-z][a-z0-9/.@*]*(?:-+[a-z0-9/.@*]+)*-*)}}/,
      greedy: true,
      alias: "string",
      inside: {
        term: {
          pattern: /([a-z][a-z0-9/.@*]*(?:-+[a-z0-9/.@*]+)*-*)/,
          greedy: true,
          alias: "tag",
        },
      },
    },
    nested_term: {
      pattern: /([a-z][a-z0-9/.@*]*(?:-+[a-z0-9/.@*]+)*-*)[ (]/,
      greedy: true,
      alias: "tag",
    },
    term: {
      pattern: /([a-z./*@][a-z0-9/.@*]*(?:-+[a-z0-9/.@*]+)*-*)/,
      greedy: true,
      alias: "keyword",
    },
    string: {
      pattern: /(<[^<>]+>)/,
      greedy: true,
      alias: "string",
    },
    bracket: {
      pattern: /[{}]/,
      greedy: true,
      alias: "string",
    },
    code: {
      pattern: /#ww+/,
      greedy: true,
      alias: "number",
    },
    number: {
      pattern: /-?bd+(?:.d+)?b/i,
      greedy: true,
    },
    punctuation: /[{}[],]/,
    boolean: /b(?:false|true)b/,
  };
}

Code.registerLanguage("note", note);

const light = {
  'code[class*="language-"]': {
    color: "#333",
    fontWeight: "bold",
    background: "none",
    fontFamily: "Noto Sans Mono",
    textAlign: "left",
    whiteSpace: "pre",
    wordSpacing: "normal",
    wordBreak: "normal",
    wordWrap: "normal",
    lineHeight: "1.7",
    MozTabSize: "2",
    OTabSize: "2",
    tabSize: "2",
    WebkitHyphens: "none",
    MozHyphens: "none",
    msHyphens: "none",
    hyphens: "none",
  },
  'pre[class*="language-"]': {
    color: "#333",
    fontWeight: "bold",
    fontFamily: "Noto Sans Mono",
    textAlign: "left",
    whiteSpace: "pre",
    wordSpacing: "normal",
    wordBreak: "normal",
    wordWrap: "normal",
    lineHeight: "1.7",
    MozTabSize: "2",
    OTabSize: "2",
    tabSize: "2",
    WebkitHyphens: "none",
    MozHyphens: "none",
    msHyphens: "none",
    hyphens: "none",
    overflow: "auto",
  },
  ':not(pre) > code[class*="language-"]': {
    background: "#282a36",
    whiteSpace: "normal",
  },
  comment: {
    color: "#ccc",
    fontWeight: "normal",
  },
  prolog: {
    color: "#6272a4",
  },
  doctype: {
    color: "#6272a4",
  },
  cdata: {
    color: "#6272a4",
  },
  punctuation: {
    color: "#aaa",
    fontWeight: "bold",
  },
  ".namespace": {
    Opacity: ".7",
  },
  property: {
    color: "#333",
  },
  tag: {
    color: "#333",
  },
  constant: {
    color: "#9248fc",
  },
  symbol: {
    color: "#9248fc",
  },
  deleted: {
    color: "#9248fc",
  },
  boolean: {
    color: "#3b82f6",
  },
  number: {
    color: "#34D399",
  },
  selector: {
    color: "#9248fc",
  },
  "attr-name": {
    color: "#aaa",
  },
  string: {
    color: "#9248fc",
  },
  char: {
    color: "#9248fc",
  },
  builtin: {
    color: "#9248fc",
  },
  inserted: {
    color: "#9248fc",
  },
  operator: {
    color: "#bbb",
  },
  entity: {
    color: "#333",
    fontWeight: "bold",
    cursor: "help",
  },
  url: {
    color: "#333",
    fontWeight: "bold",
  },
  ".language-css .token.string": {
    color: "#333",
    fontWeight: "bold",
  },
  ".style .token.string": {
    color: "#333",
    fontWeight: "bold",
  },
  variable: {
    color: "#aaa",
  },
  atrule: {
    color: "#aaa",
    fontWeight: "bold",
  },
  "attr-value": {
    color: "#9248fc",
    fontWeight: "bold",
  },
  function: {
    color: "#111",
    fontWeight: "bold",
  },
  "class-name": {
    color: "#111",
    fontWeight: "bold",
  },
  keyword: {
    color: "#999",
  },
  regex: {
    color: "#34D399",
  },
  important: {
    color: "#34D399",
    fontWeight: "bold",
  },
  bold: {
    fontWeight: "bold",
  },
  italic: {
    fontStyle: "italic",
  },
};

const note3 = `deck @termsurf/base
  mark <0.0.1>
  head <A NoteText Package Manager>
  term link-text
  term computation
  term philosophy
  term information
  term platform
  term white-label
  term compiler
  face <Lance Pollard>, site <[email protected]>
  task ./task
  read ./note
  lock apache-2
  example <The moon's period is {bold(<28 days>)}
  link @termsurf/bolt, mark <0.x.x>
  link @termsurf/nest, mark <0.x.x>
  link @termsurf/crow, mark <0.x.x>`;

ReactDOM.render(
  <Code
    customStyle={{
      height: "100%",
      padding: 16,
      margin: 0,
    }}
    language="note"
    style={light}
  >
    {note3}
  </Code>,
  document.getElementById("base")
);

If you’ll see the preview, notice the “example” line:

enter image description here

How do I make it so the text is highlighted properly, so it handles “terms” nested inside strings, nested inside terms, etc., recursively? More like this:

enter image description here

How can I change the definition of the syntax highlighter above to allow nested strings within terms? Terms are as defined in the highlighter, and they can be nested with parens, like term-a(term-b, term-c(term-d, etc)). But you can have strings within terms, and terms within strings.

Finding maximum average subarray of given length

I am trying to solve a Leetcode problem with JavaScript

#643 Maximum Average Subarray

My solution works for all the test cases but the time complexity is too high. How can I optimize this?

See Problem

var findMaxAverage = function(nums, k) {
    let maxsum = undefined;
    let sum = 0;
    for(let j=0; j<=nums.length-k;j++){
        for(let i = j; i<j+k; i++){
            sum+=nums[i]
        }
        if(maxsum <= sum || maxsum == undefined){
            maxsum = sum;
        }
        sum=0;
    }
    return maxsum/k;

Also I want to understand how to calculate the time complexity im guessing its O( (n-k+1) * k) please help me with this as well.

Thank you

Time complexity too high, need optimization

I am trying to solve a Leetcode problem with JavaScript

#643 Maximum Average Subarray

My solution works for all the test cases but the time complexity is too high. How can I optimize this?

See Problem

var findMaxAverage = function(nums, k) {
    let maxsum = undefined;
    let sum = 0;
    for(let j=0; j<=nums.length-k;j++){
        for(let i = j; i<j+k; i++){
            sum+=nums[i]
        }
        if(maxsum <= sum || maxsum == undefined){
            maxsum = sum;
        }
        sum=0;
    }
    return maxsum/k;

Also I want to understand how to calculate the time complexity im guessing its O( (n-k+1) * k) please help me with this as well.

Thank you

p-table virtualScroll is scrolling a table when spacebar is pressed

I did my best to find a solution but I had no luck this time.
I am using PrimeNG p-table component (that has editable fields) and I have a virtualScroll active if there are more than 100 elements.

When there are less than 100 elements, everything works as a charm but when there is 100 and more (when virtualScroll is enabled), on every spacebar press, a table is a bit scrolled down and I am not able to enter empty characted in my input field.

I tried to do a preventDefault and that will prevent scroll, but still – I am not able to add empty char on spacebar click.

Do you have some nice idea how to solve this? I really appriciate it.

Issue with z-index and framer motion layoutId

I’m using motion.span with layoutId set to underline to nicely animate bottom bar of my tabs. The problem is that is works nice when click from left tab to the right

From left to right

But its not visible when navifating from right tab to left because its hidden behind other tabs
from right to left

What should I change?

Full code

    <Tabs
              value={activeTab}
              onValueChange={setActiveTab}
              className='mt-[100px] min-h-[300px] w-full'
            >
              <TabsList className='flex items-start '>
                <TabsTrigger
                  value='latex'
                  className='flex items-center gap-1.5'
                >
                  <Keyboard className='h-5 w-5' />
                  <span>LaTeX</span>
                  {activeTab === 'latex' && (
                    <motion.span
                      layoutId='underline'
                      className='absolute left-0 top-full -mt-[4px] block h-[3px] w-full'
                      transition={{ duration: 200 }}
                      style={{
                        background:
                          'linear-gradient(113deg, hsl(260deg 100% 64%) 0%, hsl(190deg 100% 55%) 100%)',
                        boxShadow: '0px 0px 8px 0px hsl(262deg 100% 70% / 70%)',
                      }}
                    />
                  )}
                </TabsTrigger>
                <TabsTrigger
                  value='image'
                  className='flex items-center gap-1.5'
                >
                  <ImageIcon className='h-5 w-5' />
                  <span>Zdjęcie</span>
                  {activeTab === 'image' && (
                    <motion.span
                      layoutId='underline'
                      className='absolute left-0 top-full -mt-[4px] block h-[3px] w-full'
                      transition={{ duration: 200 }}
                      style={{
                        background:
                          'linear-gradient(113deg, hsl(260deg 100% 64%) 0%, hsl(190deg 100% 55%) 100%)',
                        boxShadow: '0px 0px 8px 0px hsl(262deg 100% 70% / 70%)',
                      }}
                    />
                  )}
                </TabsTrigger>
                <TabsTrigger
                  value='video'
                  className='flex items-center gap-1.5'
                >
                  <PlaySquare className='h-5 w-5' />
                  <span>Wideo</span>
                  {activeTab === 'video' && (
                    <motion.span
                      layoutId='underline'
                      transition={{ duration: 200 }}
                      className='absolute left-0 top-full z-[100] -mt-[4px] block h-[3px] w-full'
                      style={{
                        background:
                          'linear-gradient(113deg, hsl(260deg 100% 64%) 0%, hsl(190deg 100% 55%) 100%)',
                        boxShadow: '0px 0px 8px 0px hsl(262deg 100% 70% / 70%)',
                      }}
                    />
                  )}
                </TabsTrigger>
                {/* <div
                ref={cursorRef}
                className='absolute bottom-[0px] h-[4.5px] w-[100px] transition-all duration-300'
                style={{
                  background:
                    'linear-gradient(113deg, hsl(260deg 100% 64%) 0%, hsl(190deg 100% 55%) 100%)',
                  left: '0px',
                  width: '0px',
                  boxShadow: '0px 0px 8px 0px hsl(262deg 100% 70% / 70%)',
                }}
              ></div> */}
              </TabsList>
              <div
                className='min-h-[300px] rounded-[5px] border-y border-y-[#3b3d3f] bg-[#20222c] p-5'
                style={{
                  boxShadow:
                    '0 2px 3px rgb(10 10 10 / 10%), 0 0 0 1px rgb(10 10 10 / 10%)',
                }}
              >
                <TabsContent value='latex'>
                  {/* {data && (
                  <GridSelect
                    data={data}
                    defaultSelected={data.filter(
                      (x) => x.title === 'Arytmetyka'
                    )}
                  />
                )} */}
                </TabsContent>
                <TabsContent value='image'>Zdjęcie</TabsContent>
                <TabsContent value='video'>Wideo</TabsContent>
              </div>
            </Tabs>

React, 404 not found on password request update

I am trying to learn nodejs and react with mongodb. I have setup what I know is (sketchy) but a so far working login, signup, and password reset system. Currently with the password reset system one the user recieves the email and tries to update there password. I get a 404 not found. I have tried multiple different combinations of ways I can think of, looked at other stack over flow questions, visted a youtube tutorial and asked chatgpt who had a stroke.

reset password function from auth controller

    try {
   const token2 = crypto.createHash('sha256').update(req.params.token2).digest('hex');
   const user = await User.findOne({passwordResetToken: token2, passwordResetTokenExpires: { $gt: Date.now() } });

  if(!user) {
    return next(errorHandler(401, 'Token wrong or invalid!'));
   
  }

  const newPassword = req.body.password;
  const hashedPassword = await bcryptjs.hash(newPassword, 10);
  user.password = hashedPassword;
  user.passwordResetToken = undefined;
  user.passwordResetTokenExpires = undefined;

  user.save();


  const logintokeen = signToken(User._id);

  res.status(200).json({
    status: 'success',
    token: logintokeen
  })
} catch (error) {
  next(error);
 }
}``

``router.post('/signup', signup);
     router.post('/signin', signin);
     router.post('/google', google);
     router.get('/signout', signout);
     router.post('/forgotPassword', forgotPassword);
     router.patch('/resetPassword/:token2', resetPassword);
     router.post('/newpassword/:token2', resetPassword);
     export default router;``
Newpassword page 
``export default function Newpassword() {
  const [formData, setFormData] = useState({});
  const [password, setPassword] = useState('');
  const navigate = useNavigate();
  const { token2 } = useParams();
  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const hashedPassword = bcryptjs.hashSync(password, 10);
      const res = await fetch(`/resetPassword/:token2`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ hashedPassword }),
      });
      if (!res.ok) {
        throw new Error(`Error: ${res.status}`);
      }
      const data = await res.json();
      if (data.success === false) {
        console.log('failed');
        return;
      }
      navigate('/');
    } catch (error) {
      console.log(error);
    }
  };

  const handleChange = (e) => {
    setPassword(e.target.value);
  };

  return (
<div>
      <h2>Enter Your new Password</h2>
      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="password">New password</label>
          <input
            type="password"
            id="password"
            placeholder="Enter your new password"
            className='bg-slate-100 p-3 rounded-lg'
            onChange={handleChange}
          />
        </div>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};``
App js 
``

export default function App() {
  return (
    <BrowserRouter>
      {/* header */}
      <Header />
      <Routes>
        <Route path='/' element={<Home />} />
        <Route path='/about' element={<About />} />
        <Route path='/sign-in' element={<SignIn />} />
        <Route path='/sign-up' element={<SignUp />} />
        <Route element={<PrivateRoute />}>
          <Route path='/profile' element={<Profile />} />
          <Route path='/forgotpassword2' element={<Forgotpassword2 />} />
          <Route path='/newpassword/:token2' element={<Newpassword />} />
          <Route path='/resetpassword/:token2' element={<Newpassword />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );``