How to implement websocket client in Electron (Next.js/React)?

I have a working websocket server. I use a websocket as client in web browser/react before, but I’m unable to use Websocket inside electron app since WebSocket depends on browser’s compatibility and for some reason, this feature is unavailable in Electron.

I use nextron (nextjs/react + electron) boilerplate.

import React from 'react';
import Head from 'next/head';
import { ThemeProvider } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import { theme } from '../lib/theme';
import type { AppProps } from 'next/app';

export default function (props: AppProps) {
  const { Component, pageProps } = props;

  const ws = new WebSocket("ws://192.168.100.8:8081/")
  console.log("file: _app.tsx:11 ~ ws", ws)

  React.useEffect(() => {
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles) {
      jssStyles.parentElement.removeChild(jssStyles);
    }
  }, []);

  return (
    <React.Fragment>
      <Head>
        <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
      </Head>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <Component {...pageProps} />
      </ThemeProvider>
    </React.Fragment>
  );
}

enter image description here

Error in MaterialUI’s autocomplete menu “Encountered two children with unique keys”, where I could provide a key?

I am using material-ui’s autocomplete for search suggestion. I have implemented some dummy data from json – server.
Now into the autocomplete , I want to render a list of products that exists into my data, but I am facing a problem

when looking on the browser, it says “two children with the same key “productName_(it is one of same product names from my json)” key should be unique”.
But my products have productId field which I made of type<string> and left vacant, because I want to render uuid() as a product Id, but I don’t know where to put the key into autocomplete.

Also, I don’t want to render a mere list of suggested items, rather I want to render some cards with avatar on the left hand side of them. so where should I put .map() method to do so into MUI Autocomplete?

Here’s my code for autocomplete –

import { Autocomplete, TextField, Typography } from "@mui/material";
import { Fragment, useEffect, useState } from "react";
import uuid from "react-uuid";
import agent from "../../../api/agent";
import { Item } from "../../../models/Job";
import { setCloseMenu, setOpenMenu } from "../../menu/menuSlice";
import { useAppDispatch, useAppSelector } from "../../Redux/reduxStore";


interface Props {
    searchTerm? : string;
}

export default function JobSearch ( props : Props ) {
const [ item, setItem ] = useState<item[]>([]);
// using redux
const dispatch = useAppDispatch();
const { status } = useAppSelector ( state => state.menu );

useEffect(() => {
    agent.Product.getAutoCompleteProducts() // endpoint to get list of products
    .then((item) => {setItem(item); console.log(item)})
    .catch((error) => console.log(error))
}, []);


    return (
        <Fragment>
           <Autocomplete
             open = { status.name === "autoCompleteMenu" && status.open }
             onOpen = { () => {
                dispatch(setOpenMenu("autoCompleteMenu"));
            }}
             onClose = { () => dispatch(setCloseMenu("autoCompleteMenu"))}
             options = {item.map((item) => 
               item.name
             )}  // I want options into form of cards with key as uuid() here
             renderInput = {(params) => (
                <TextField { ...params} 
                 variant = {'outlined'} />  )} />
        </Fragment>
    )
}

type file for my Items is –

 export interface Items {
 itemId : string, //uuid() - should be here
 itemName : string,
 itemPrice : number,
 itemDesc : string

}

I want to know 2 things –

  1. How could I map my own custom layout beneath the autocomplete box, Like I want to map the items into the form of cards, long lengthed cards with avatar on left-side.
  2. I want to know where am I making a mistake in not supplying the key = {} prop to the autocomplete, please keep a note that I only waNt to supply uuid as a key prop.
    and uuid() should be inside my itemId = uuid().
    All suggestions are welcome.

JavaScript validation error. What’s the matter?

<script type="text/javascript">
    function checkF()
    {
        var f = document.user_info;
        
        if(f.userID.value.length < 2 || f.userID.value.length >16)
            {
            alter("아이디는 2~16자 이내로 입력해야 합니다.");
            f.userID.focus();
            return false;
            }
        else if(f.userPW.value.length < 6)
            {
            alter("비밀번호는 6자 이상으로 입력해야 합니다.");
            f.userPW.focus();
            return false;
            }
        else if(f.userMAIL.value == "")
            {
            alter("이메일을 입력해야 합니다.");
            f.userMAIL.focus();
            return false;
            }
        else return true;
    }
</script>
</head>
<body>
    Home > 회원 가입
    <hr>
    <form action="insertDB.jsp" name="user_info" method="post" onsubmit="return checkF()">
     <fieldset style="width:230px">
      <legend> 회원 가입 화면 </legend><p>
            
            아이디 : <br>
            <input type="text" size = "16" name="userID"><br><br>
            
            비밀번호 : <br>
            <input type="password" size = "16" name="userPW"><br><br>
            
            이메일 : <br>
            <input type="email" size = "30" name="userMAIL"><br><br>
            <hr>
            <input type="reset" value=" ◀ 다시작성 ">
            <input type="submit" value=" 가입하기 ▶ ">
            <hr><hr>
     </fieldset>
    </form>
</body>
</html>

An error was found in the validation step that prevented validation from being performed properly.
onsubmit=”return false” works fine. Perhaps it is a connection problem. Why can’t I connect?

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ include file = "dbConn.jsp" %>
<%
    String u_id = request.getParameter("userID");
    String u_pw = request.getParameter("userPW");
    String u_mail = request.getParameter("userMAIL");
    
    String sql="INSERT INTO members(id, passwd, email) VALUES";
    sql += "('" + u_id + "','" + u_pw + "','" + u_mail +"')";
    
    Statement sm = conn.createStatement();
    
    int count = sm.executeUpdate(sql);
    if(count ==1){
        response.sendRedirect("signupSuccess.jsp");
    }else{
        out.println("회원가입 실패!");
        response.sendRedirect("signup.jsp");
    }
    sm.close();
    conn.close();
%>

This is the contents of insertDB. I’m attaching it in case there might be a cause here.

If there is no problem with the code, is the external factor the problem? I am wondering what steps to take to solve this.

Why are my JavaScript questions not populating for my quiz?

I’m trying to create a little quiz on JavaScript (new to coding and just learning how to tie JS into HTML and CSS) and cannot seem to get the questions to show up.

I’ve tried to make sure that I’ve included the link for JavaScript in the html file, make sure that I added a link for jQuery for the $ in the head (seem to be getting an error from JS line 98 for the ($) according to the console) and at this point not really sure where to go.

// setting up an array and sending the questions, number, options, and answers
var questions = [
  //Question #1
  {
    id: 1,
    question: "What is JavaScript?",
    a: "A scripting language used to make the website interactive",
    b: "A cup of Joe",
    c: "An assembly language used to make the website interactive",
    d: "Not any of these answers",
    answer: "a"
  },
  //Question #2
  {
    id: 2,
    question: "JavaScript is an _____language?",
    a: "Object-Oriented",
    b: "Procedural",
    c: "Object-Based",
    d: "All of the Above",
    answer: "a"
  },
  //Question #3
  {
    id: 3,
    question: "Which of the following is not a JavaScript data type?",
    a: "Undefined",
    b: "Number",
    c: "Null",
    d: "All of the Above",
    answer: "d"
  },
  //Question #4
  {
    id: 4,
    question: "Which of the following can be used to call a JavaScript Code Snippet?",
    a: "Function/Method",
    b: "RMI",
    c: "Preprocessor",
    d: "Triggering Event",
    answer: "a"
  },
  //Question #5
  {
    id: 5,
    question: "Which symbol is used to separate JavaScript statements?",
    a: "Colon (:)",
    b: "Underscore (_)",
    c: "Semicolon (;)",
    d: "Comma (,)",
    answer: "c"
  }
];


const question = document.getElementById("question");
const answers = Array.from(document.getElementsByClassName("answers"));
const questionCounterText = document.getElementById('counter');
const scoreText = document.getElementById("score");

console.log(questions);
let questionCounter;
let score;
const MAX_Questions = 5;

let acceptingAnswers;

startGame = () => {
  questionCounter = 0;
  score = 0;
  acceptingAnswers = true;
  availableQuestions = getRandomQuestions(questions, MAX_QUESTIONS);
  consolelog(availableQuestions);
  getNewQuestion();
};

const getRandomQuestions = (arr, n) => {
  let len = arr.length;
  if (n > len) {
    throw new RangeError(
      "getRandomQuestions: more elements taken than are available"
    );
  }

  const shuffled = [...arr].sort(() => 0.5 - Math.random());

  return (selected = shuffled.slice(0, n));
};

const getNewQuestion = () => {
  if (availableQuestions.length === 0) {
    alert("End of the game");
    alert("You scored " + score + " points!")
    return;
  }

  questionCounter++;
  questionCounterText.innerText = `${questionCounter}/${MAX_QUESTIONS}`;

  currentQuestion = availableQuestions[0];
  console.log("current question --> ", currentQuestion.question);
  question.innerText = currentQuestion.question;

  answers.forEach((answer) => {
    if (!acceptingAnswers) {
      //console.log("not accepting");
      return;
    }
    acceptingAnswers = false;
    const clickedAnswer = e.target;
    const answeredLetter = clickedAnswer.dataset["answer"]

    let classToApply = "incorrect";

    if (answeredLetter === currentQuestion.answer) {
      score++;
      scoreText.innerText = score;
      classToApply = "incorrect";
      console.log("incorrect")
    }

    clickedAnswer.parentElement.classList.add(classToApply);

    setTimeout(() => {
      clickedAnswer.parent.Element.classList.add(classToApply);
      getNewQuestion();
      acceptingAnswers = true;
    }, 1000);
  });
  availableQuestions.shift();
};



startGame();

var highScore = [];
body,
h1 {
  font-weight: 400;
  background-color: darkgray;
}

#introduction {
  display: flex;
  justify-content: space-between;
}

.prefix {
  text-align: center;
  font-size: 20px;
}

#counter,
#score {
  text-align: center;
}

.question-holder {
  height: 75px;
  align-items: center;
  text-align: center;
}

.answer-card {
  display: flex;
  flex-direction: initial;
  margin-bottom: 3px;
  font-size: 20px;
}

.answer-prefix {
  background-color: ghostwhite;
  color: black;
  padding: 4px 2px;
  margin: 0;
}

.answer-text {
  padding: 6px;
  width: 100%;
  margin: 0;
}

.answer-container:hover {
  cursor: pointer;
  box-shadow: 0 2px 3.4px 0 rgb(87, 158, 184);
}

.correct {
  background-color: rgb(45, 167, 45);
}

.incorrect {
  background-color: rgb(201, 65, 85);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
  <h1 class="page-title">Fun JavaScript Quiz</h1>
</header>

<div class="container my-5">
  <div id="introduction">
    <div class="counter">
      <p class="prefix">Question:</p>
      <h1 id="counter">1/10</h1>
    </div>
  </div>
  <div class="score">
    <p class="prefix">Your Score</p>
    <h1 id="score" class="score">0</h1>
  </div>
</div>
<div class="question-holder row">
  <div class="col-12">
    <h1 id="question">What's the right answer to this question?</h1>
  </div>
</div>

<div id="answer-container">
  <div class="col-12">
    <div class="answer-card card">
      <p class="answer-prefix">A</p>
      <p class="answer-text answers" data-answer="a"> Answer A</p>
    </div>
  </div>
</div>

<div class="col-12">
  <div class="answer-card card">
    <p class="answer-prefix">B</p>
    <p class="answer-text answers" data-answer="b"> Answer B</p>
  </div>
</div>
</div>

<div class="col-12">
  <div class="answer-card card">
    <p class="answer-prefix">C</p>
    <p class="answer-text answers" data-answer="c"> Answer C</p>
  </div>
</div>
</div>

<div class="col-12">
  <div class="answer-card card">
    <p class="answer-prefix">D</p>
    <p class="answer-text answers" data-answer="d"> Answer D</p>
  </div>
</div>
</div>
</div>
</div>

How do I use the sx prop in material UI to implement styling only when the component is selected?

As shown in the code below,I have configured useState such that when a ListItem is clicked on, selected is true. When I want to do is implement specific styling when the item is selected. I would like to do this in the sx prop and not used a styled component as that would be unnecesarry for such simple styling. What I want to have is that when a ListItem is selected, the ListItemText turns blue and the ListItem turn a lighter shade of blue.

import { useState } from 'react'
import { Box, Drawer, CssBaseline, AppBar, Toolbar, Avatar, List } from '@mui/material';
import Typography from '@mui/material/Typography';
import ListItem from '@mui/material/ListItem';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import HomeOutlinedIcon from "@mui/icons-material/HomeOutlined"
import PeopleOutlinedIcon from "@mui/icons-material/PeopleOutlined"
import PersonOutlinedIcon from "@mui/icons-material/PersonOutlined"
import CalendarTodayOutlinedIcon from '@mui/icons-material/CalendarTodayOutlined';
import HelpOutlinedIcon from "@mui/icons-material/HelpOutlined"
import PieChartOutlineOutlinedIcon from "@mui/icons-material/PieChartOutlineOutlined"
import TimelineOutlinedIcon from "@mui/icons-material/TimelineOutlined"
import FolderSharedOutlinedIcon from '@mui/icons-material/FolderSharedOutlined';
import { Link as RouterLink } from 'react-router-dom'
import { useTheme } from '@mui/material'
import { ColorModeContext, tokens } from "./../theme"
import { useContext } from 'react';
import Logo from "./../assets/code2.jpg"

const SideBar = () => {
    const theme = useTheme();
    const colorMode = useContext(ColorModeContext);
    const colors = tokens(theme.palette.mode);
    const [selected, setSelected] = useState("Dashboard")

    const handleListItemClick = (text) => {
        setSelected(text)
    }

    const Item = ({ icon, text, to, selected }) => {
        console.log(selected === text);
        return (
            <ListItem key={text}
                selected={selected === text}
                disablePadding
                onClick={() => handleListItemClick(text)}
                sx={{
                    "&$selected": {
                        "& .MuiListItem.Mui-selected": {
                            backgroundColor: "blue",
                        }
                    },
                    "&$selected:hover": {
                        backgroundColor: "white",
                        '& .MuiListItem-root': {
                            color: "white"
                        }
                    }
                }}>
                <ListItemButton component={RouterLink} to={to}>
                    <ListItemIcon>
                        {icon}
                    </ListItemIcon>
                    <ListItemText selected={selected === text} primary={text}
                        sx={{
                            "&$selected": {
                                "& .MuiListItemText.Mui-selected": {
                                    color: "blue",
                                }
                            }}}                    />
                </ListItemButton>
            </ListItem>)
    }

    return (
        <Drawer sx={{
            width: 240,
            flexShrink: 0,
            '& .MuiDrawer-paper': {
                p: 2,
                width: 240,
                boxSizing: 'border-box',
                backgroundColor: `${colors.primary[500]}`,
            }
        }} variant="permanent" anchor="left">
            <Box textAlign="center" m="0 0 15px 0">
                <Typography variant="h3" color={colors.grey[100]} fontWeight="bold" sx={{ m: "10px 0 0 0" }}> ADMINIS</Typography>
            </Box>
            <Box mb="10px">
                <Box display="flex" justifyContent="center" alignItems="center">
                    <Avatar alt="logo" src={Logo} sx={{ width: 100, height: 100, cursor: "pointer"}} />
                </Box>
            </Box>
            <Box textAlign="center">
                <Typography variant="h2" color={colors.grey[100]} fontWeight="bold" sx={{ m: "10px 0 0 0" }}> Huvon Goodridge</Typography>
                <Typography variant="h5" color={colors.greenAccent[500]}>VP Fancy Admin</Typography>
            </Box>
            <List>
                <Item selected={selected} icon={<HomeOutlinedIcon />} text={"Dashboard"} to={'dashboard'} />
            </List>
            <Typography variant="h6" color={colors.grey[300]} sx={{ m: "15px 0px 0px 5px" }}>
                Data
            </Typography>
            <List>
                <Item selected={selected} icon={<PeopleOutlinedIcon />} text={"Team"} to={'team'} />
                <Item selected={selected} icon={<FolderSharedOutlinedIcon />} text={"Projects"} to={"projects"} />
            </List>
            <Typography variant="h6" color={colors.grey[300]} sx={{ m: "15px 0px 0px 5px" }}>
                Pages
            </Typography>
            <List>
                <Item selected={selected} icon={<PersonOutlinedIcon />} text={"Profile"} to={'profile'} />
                <Item selected={selected} icon={<CalendarTodayOutlinedIcon />} text={"Calendar"} to={'calendar'} />
                <Item selected={selected} icon={<HelpOutlinedIcon />} text={"FAQ"} to={'faq'} />
            </List>
            <Typography variant="h6" color={colors.grey[300]} sx={{ m: "15px 0px 0px 5px" }}>
                Charts
            </Typography>
            <List>
                <Item selected={selected} icon={<PieChartOutlineOutlinedIcon />} text={"Pie Chart"} to={'piechart'} />
                <Item selected={selected} icon={<TimelineOutlinedIcon />} text={"Timeline"} to={'timeline'} />
            </List>
        </Drawer>)
}

export default SideBar;

I have tried multiple ways to select the classes of the components that I want but to no avail. I expected this to change the backgroundColor but it did not and furthermore, it failed to change the text color. I have looked at the documentation on material ui website for this but it did not help.

hamburger-react with disclosure panel (How to animate hamburger onclick navigation links)

When User Clicks Hamurger imported from hamburger-react – Hamburger animates to X – Opens Disclosure Panel
When User Clicks X it animates to Hamburger and closes the disclosure panel –
Though if User instead clicks a navigation link, Hamburger remains an X and Disclosure panel closes.

I assume I need to implement some JavaScript syntax to connect the disclosure panels state to the hamburgers state.
Trying to figure out how to connect the 2 aria states to each other,

I’m expecting when Disclosure.Panel is closed, after click of a navigation link, X is reset to hamburger.
Unopened state as intended
Open State as Intended
When it’s broken after clicking a navigation link
My code

How to create tag only once

I have a function, that creates a cells in table automatically. It takes information from array and puts it to the cell. But I don’t know how to create a header cell for this table with a function. Is there a way to create a whole table with one function?
My HTML is next:

<div id="table"> 
   <details>
       <summary class="summary">
           day 1
       </summary>
            <table>
                <tr>
                    <th>name</th>
                    <th>count1 </th>
                    <th>count2</th>
                    <th>count3</th>
                </tr>
                <tr id="createTable"></tr>
            </table>
   </details>
</div>

And function is next:

function addTable(array) { 
    var check_value = array;     
    for(var count in check_value){
        var node = document.createElement('tr');   
        node.innerHTML = '<td class ="tdtable">'+check_value[count][0]+'</td>'+
                         '<td class ="tdtable">'+check_value[count][1]+'</td>'+
                         '<td class ="tdtable">'+check_value[count][2]+'</td>'+
                         '<td class ="tdtable">'+check_value[count][3]+'</td>';
        document.getElementById('createTable').appendChild(node);  
    }
}

Jest can’t find module with esm

I have tried several days ,but still error,
this is my problem :

Cannot find module '../src/repository/UserRoleRepository.js' from 'test/user_roles_positive.test.js'

      at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:425:11)
          at async Promise.all (index 3)

this is the import section :

import {jest} from '@jest/globals';
import UserRoleRepository from '../src/repository/UserRoleRepository.js';
import UserRoleService from '../src/service/UserRoleService.js';
import validation from '../src/validation/index.js';

const repository = new UserRoleRepository();
const service = new UserRoleService(repository, validation);
jest.mock('../src/repository/UserRoleRepository.js');

this my config.json :

{
  "name": "user_role_service",
  "type": "module",
  "version": "1.0.0",
  "description": "service for handling all about logic user role",
  "main": "server.js",
  "scripts": {
    "test": "NODE_OPTIONS='--experimental-vm-modules' jest",
    "dev": "nodemon ./src/server.js"
  },
  "jest": {
    "transform": {
      "^.+\.[t|j]sx?$": "babel-jest"
    }
  },
  "author": "me",
  "license": "ISC",
  "devDependencies": {
    "@babel/plugin-transform-runtime": "^7.19.1",
    "@babel/preset-env": "^7.19.4",
    "babel-jest": "^29.2.0",
    "dotenv": "^16.0.3",
    "eslint": "^8.29.0",
    "eslint-config-google": "^0.14.0",
    "jest": "^29.2.0",
    "nodemon": "^2.0.20",
    "prisma": "^4.4.0"
  },
  "dependencies": {
    "@hapi/hapi": "^20.2.2",
    "@hapi/nes": "^13.0.0",
    "@prisma/client": "^4.4.0",
    "joi": "^17.6.2",
    "uuid": "^9.0.0"
  }
}

this is my babel.config.json :

{
    "presets": ["@babel/preset-env"],
    "plugins": [
        [
          "@babel/plugin-transform-runtime",
          {
            "regenerator": true
          }
        ]
      ]
}

i tried to change the test script in to several code but still error,hope u guys could help me thanks

Return to the desired place in the list

When the button is clicked, my list is replaced with a one-item list. When I click on the “return to list” button, I want to return to the same list and to the same place in the list to which I scrolled.

useEffect(() => {
    if (props.specialOfferRestaurant) {
        localStorage.setItem('scrollPosition', String(window.scrollY))
        localStorage.setItem('restaurants', JSON.stringify(allRestaurants));
        window.scrollTo(0, 0)
        setAllRestaurants([props.specialOfferRestaurant])
    } else if (!props.specialOfferRestaurant && localStorage.length > 0) {
        setAllRestaurants(JSON.parse(localStorage.getItem('restaurants')))
        window.scrollTo(0, Number(localStorage.getItem('scrollPosition')))
        localStorage.clear();
    }
}, [props.specialOfferRestaurant])

In this code, everything works except for the line that returns the scroll to the right place. The same line that returns the scroll to 0 also works. I can’t figure out what’s wrong.

How do I convert a list of tokens into React elements?

Similar to Constructing an Abstract Syntax Tree with a list of Tokens but specific for React. To have a simple markdown renderer (no blocks, just a string with simple formatting elements (not even code).

Given the complex example:

Foo *italic **bold-italic** italic* **bold** Blah

I have a parser that generates the following tokens in this order

{ type: text, content: "Foo " }
{ type: em_open }
{ type: text, content: "italic " }
{ type: strong_open}
{ type: text, content: "bold-italic" }
{ type: strong_close}
{ type: text, content: " italic" }
{ type: em_close }
{ type: text, content: " " }
{ type: strong_open}
{ type: text, content: "bold" }
{ type: strong_close}
{ type: text, content: " Blah" }

It’s easy to take the above and translate it to a string containing markup, but what I want to do is to take the above an generate elements using React.createElement

So to simplify the example to

**foo**

would have

{ type: strong_open }
{ type: text, content: "foo" }
{ type: strong_close }

I would have a call

return createElement(Text, { fontWeight: "bold" }, [ "foo" ]);

And a slightly complex one would be

***foo***

to have

{ type: em_open }
{ type: strong_open }
{ type: text, content: "foo" }
{ type: strong_close }
{ type: em_close }

which would return

return createElement(Text, { fontStyle: "italic" }, [ 
  createElement(Text, { fontWeight: "bold" }, [ "foo" ])
]);

Just wondering what patterns / techniques I can use to do this.

Writing a library that can be used by multiple programming languages

Since writing the same library in multiple languages is unpractical what would be the best way to write it once and make it available in different languages?

The library will be used on web and will not contain platform-specific code (will be able to run correctly on the client or the server). Also, it should not require from developers to use third party tools to load it. For example, in Javascript, it should be importable as an ES Module with import statement.

I already made some progress in Javascript, but realized that it would be better if the library can be used by more programing languages, hence I am considering writing the library in another language and, as I read somewhere, compile it to an interface for different languages. Is this even possible?

How would I make a discord bot that logs shifts?

this is my first post here so I apologize if this is messy. Anyways lets get to the point. I am trying to make a discord bot in JS that can log shifts. I want to make it where if you type in /startshift or something similar to it, then the bot will send something like Your shift has started at [The time you used the command]. Then when you are over with your shift you can go back and type /endshift and it will say something along the lines of You have just ended your shift. You were on duty for [The amount of time you were on duty] and then store that time preferably on MongoDB but really anything works. Although I don’t have an idea of how to go about doing this. I am fairly new to discord bot development. I am sure that you would say that if you are starting off you shouldn’t start with something this complicated but I am fairly adamant about creating this.

I’ve searched threw google for something similar that I could follow along with, unfortunately I didn’t find anything. I even tried to whip something up with my limited JS knowledge, which obviously didn’t work either.

To sum it up, I just need to know where to start and what to search up on google to learn what I need to in order to accomplish this. Thank you for viewing this, have an amazing night/day!

Zod: Reusing field multiple times

I have a large schema that represents a cluster with many data tiers:

hot
warm
cold
frozen

Each of this properties contains an array of nodes, the content of hot,war,cold,frozen is the same type. I can’t figure out how can I reuse this node type to avoid repeating.

const nodesOut = z.object({
  zone: z.string(),
  hot: z.array(
    z.object({
      jvm: z.object({
        mem: z.object({
          heap_used_in_bytes: z.number(),
          heap_used_percent: z.number(),
        }),
      }),
      fs: z.object({
        total: z.object({
          total_in_bytes: z.number(),
          free_in_bytes: z.number(),
          available_in_bytes: z.number(),
        }),
      }),
      indices: z.object({
        mappings: z.object({
          total_count: z.number(),
          total_estimated_overhead_in_bytes: z.number(),
        }),
      }).optional(),
      attributes: z.object({
        data: z.string().optional(),
        availability_zone: z.string(),
        server_name: z.string(),
      }),
    })
  ).optional(),
  warm: z.array(
    z.object({
      jvm: z.object({
        mem: z.object({
          heap_used_in_bytes: z.number(),
          heap_used_percent: z.number(),
        }),
      }),
      fs: z.object({
        total: z.object({
          total_in_bytes: z.number(),
          free_in_bytes: z.number(),
          available_in_bytes: z.number(),
        }),
      }),
      indices: z.object({
        mappings: z.object({
          total_count: z.number(),
          total_estimated_overhead_in_bytes: z.number(),
        }),
      }).optional(),
      attributes: z.object({
        data: z.string().optional(),
        availability_zone: z.string(),
        server_name: z.string(),
      }),
    })
  ).optional(),
  cold: z.array(
    z.object({
      jvm: z.object({
        mem: z.object({
          heap_used_in_bytes: z.number(),
          heap_used_percent: z.number(),
        }),
      }),
      fs: z.object({
        total: z.object({
          total_in_bytes: z.number(),
          free_in_bytes: z.number(),
          available_in_bytes: z.number(),
        }),
      }),
      indices: z.object({
        mappings: z.object({
          total_count: z.number(),
          total_estimated_overhead_in_bytes: z.number(),
        }).optional(),
      }),
      attributes: z.object({
        data: z.string().optional(),
        availability_zone: z.string(),
        server_name: z.string(),
      }),
    })
  ).optional(),
  frozen: z.array(
    z.object({
      jvm: z.object({
        mem: z.object({
          heap_used_in_bytes: z.number(),
          heap_used_percent: z.number(),
        }),
      }),
      fs: z.object({
        total: z.object({
          total_in_bytes: z.number(),
          free_in_bytes: z.number(),
          available_in_bytes: z.number(),
        }),
      }),
      indices: z.object({
        mappings: z.object({
          total_count: z.number(),
          total_estimated_overhead_in_bytes: z.number(),
        }),
      }).optional(),
      attributes: z.object({
        data: z.string().optional(),
        availability_zone: z.string(),
        server_name: z.string(),
      }),
    })
  ).optional(),
});

I read about recursive schemas but this is not actually recursive. What’s the best way to go?

Thanks

https://github.com/colinhacks/zod#recursive-types

React-scroll stopped working after turning a nodejs project into a yarn project

I have a project that I originally built with node.js, however I switched it over to yarn. Everything works, except for the react-scroll. I have uninstalled and reinstalled it and verified that it is still in package.json. Anyone else ran into this issue before or have any troubleshooting tips?
Here is a cut of my code for a button I want to link to a section of the site:

import { Link } from 'react-scroll';

<Link
activeClass='active'
to="portfolio"
smooth
duration={500}
className='group flex items-center rounded-lg cursor-pointer bg-indigo-600 w-fit text-white font-bold px-5 py-3 space-x-2'
>
 <div>Portfolio</div>
 <span className='group-hover:rotate-90 duration-300'>
  <MdOutlineArrowRightAlt />
 </span>
</Link>

And here is the code for the piece I want to link to:

<div id="portfolio">
 <div>
  <p>stuff in here and words </p>
 </div>
</div>```