Chartjs with std dev bars

I am trying to duplicate a chart created in a different software program (by someone else- unable to ask questions). In this line chart, there are a few lines in a time-series, with an average, +/- 1 std dev, and min/max points/bars (avg, std dev, and min/max over larger data set than displayed). The points/bars (for avg, std dev, min/max) are wide – 50% or more of the ‘tick’ spacing (ticks are between grid lines).

I can plot the data as a line, I can turn off the line and only show the point, but I can’t get the point to be wide. Setting the point style to line is the right look, just needs to be longer. pointBorderWidth changes the ‘height’ of the point, but nothing changes the length. See example. Is there a way to customize the point size more than in documentation? Currently on chartjs 3.7, but would update to newer version if there was a solution there.
enter image description here

Spring boot error : Loading module from “http://localhost:8080/index.js” was blocked because of a disallowed MIME type (“application/json”)

I followed a tutorial, I copied and pasted the code, but it’s not working!

The goal is to use react and spring-boot together to send web pages to the user (I think). So when they go to a api pathway, it should just load up the index.js.

It worked with just basic html, when I tried to follow the part for javascript and react it stopped working.

What happens:

when I go to localhost:8080/react (this mapping should load a mustache file, index.js) I just get a blank page, pressing f12 (open browser console) showed me this error:
Loading module from “http://localhost:8080/index.js” was blocked because of a disallowed MIME type (“application/json”).

when i click on the link in the image above i get a 404 not found error.

when I go to localhost:8080/ I get the html mustache file as expected.

console:
enter image description here

code:

The tutorial made me locally download node.js, then it made me download plugins (parcel and react-dom), and then gave me 4 small javascript files to make.

Here is the github link (.idea, .mvn, node and node_modules are no there because they are too big
) :

https://github.com/S1coding/halp

File directory:

enter image description here

How to make it preserve HTML tags if each line of text is wrapped with a div tag?

I hope someone can help me out. I have the following code wrapping each text line with a span tag. The problem is that currently, it completely ignores HTML tags. How to make it preserve HTML tags in the text?

$(".wrap-lines").each(function () {
  let $lineWrapper = this;
  
  function splitLines(container, opentag, closingtag) {
    let $lines = container.children,
      $top = 0,
      $tmp = "";
    container.innerHTML = container.textContent.replace(/S+/g, "<n>$&</n>");
    for (let i = 0; i < $lines.length; i++) {
      let $rect = $lines[i].getBoundingClientRect().top;
      if ($top < $rect) $tmp += closingtag + opentag;
      $top = $rect;
      $tmp += $lines[i].textContent + " ";
    }
    container.innerHTML = $tmp += closingtag;
  }

  splitLines( $(this)[0], '<div class="line">', "</div>" );

});
p {
  font-size: 24px;
}
p span {
  background-color: red;
  color: white;
}

.line:hover {
  background-color: #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1>Wrapping text lines</h1>

<p class="wrap-lines">Lorem ipsum dolor sit, amet <a href="">consectetur</a> adipisicing elit. Animi dolorem quasi aut dolore <span>porro iusto</span> in facilis, molestias nostrum possimus ipsum laboriosam dolorum voluptatibus praesentium consequuntur! Culpa quas nisi hic.</p>

Pushing elements to array causes infinite loading in Postman

I have a user:

"user": {
        "_id": "655cee1bce26ab5b90584157",
        "role": "user",
        "name": "gogo2",
        "email": "[email protected]",
        "password": "$2a$12$ZjP6i2PqRzsuPt8V2pTM.uBC.qZA2C/EiAVFTCwdzTlLyfrrO08/6",
        "__v": 0,
        "favourites": [
            "Regex",
            "Data structures",
            {
                "resourceCollection": "Fudamentals",
                "resourceName": "Fudamentals"
            }
        ]
    }

and i want to added new resource to its favourites.
heres the API endpoint:

exports.addToFavoriteCollection = async (req, res) => {
  const token = await req.headers.authorization.replace('Bearer ', '');
  const { id } = jwt.decode(token);
  const UsersCollections = createModel('users');
  const { resourceCollection, resourceName } = req.body;
  try {
    const user = await UsersCollections.findById(id);
   user.favourites.push({ resourceCollection, resourceName });
    await user.save();
    //
    res.status(200).json({
      message: 'Added to favorites!',
      user
    });
  } catch (error) {
    console.log(error);
  }
};

here i am finding user by id and i try to add to its favorites for example object:


{ 
"resourceName": "Fudamentals", 
"resourceCollection": "Fudamentals" 
}

every line works, but this line:

user.favourites.push(resourceCollection, resourceName);

makes it loading forver in postman. The request is sent and loading and after some time it crashes. WHen i delete this line, everything works.

I thougt it is because of the model, so I added to the model:

      favourites: {
        type: Array,
        required: false
      }

but it didnt work..

Is it possible to enable third party sites to embed my webpage that is rendered on client-side?

I have an ASP.NET core razor page that is mostly rendered client-side using JavaScript. That means, as soon as the page loads, I call my render() function.

The function involves cloning the content of several <template> HTML tags as part of its logic. These tags are included in the page itself.

I would like to allow third party sites to embed this page into any of their own webpage that is hosted in any of their own website that I do not control.

My question: Is this possible?

draw a dynamic circle with two arrow with hightcharts between two pont : actual real date and some (x,y) point

i use hightcharts with angular ,

i need to draw a dynamic circle that has as start (x,y) point until the actual date axe.

enter image description here

My angular ts code :

`xAxis: {`
`type: 'datetime',`
`lineWidth: 0,`
`tickPositions: [...this.tickPositions],`
`labels: {`
`x: 0,`
`y: chartStyles.y,`

          formatter(): any {
            //@ts-ignore
            let dateLabel = Highcharts.dateFormat('%H:%M',new Date(this.value));
    
            //@ts-ignore
            return (
              '<span style="width:10px; height:24px; color:var(--chart-text-color); background-color: var(--rectangle-bg-color);  padding: 3px 4px;margin-top:90px; margin-bottom:10px; border-radius:4px;">' +
              dateLabel +
              '</span>'
            );
          },
          useHTML: true,
        },
    
        min: this.slotsStart(),
        max: this.slotsEnd(),
        gridLineColor: '#e6e6e6',
        gridLineWidth: 0.5,
        plotLines: [
          {
            name: 'Current Time',
            color: 'var(--default-text-color)',
            width: 2,
            value: this.getCurrentDate(),
            zIndex: 6,
            label: {
              text: `${this.getUTCRealtimeFormatedDate()}`,
              align: 'bottom',
              x: -22,
              y: 287,
              enabled: true,
              rotation: 0,
              formatter() {
                //@ts-ignore
                return '<span style="display: inline-block;color:var(--chart-text-color); background-color: var(--rectangle-bg-color);padding: 3px 4px;border-radius:4px;">' +Highcharts.dateFormat('%H:%M', new Date(this.options.value)) +'</span>'
                
              },
              useHTML: true,
            } as any,
          },
        ],
      },
    
      yAxis: {
        lineWidth: 0,
        gridLineDashStyle: 'longdash',
        gridLineColor: 'var(--chart-row-color)',
        max: 45,
        min: 0,
        title: {
          text: '',
        },
        labels: {
          x: -5,
          y: 8,
    
          formatter() {
            return (
              '<span style="width:20px; height:24px; color:var(--chart-text-color); background-color: var(--frame-color); padding: 3px 6px; margin-bottom:10px; border-radius:4px;">' +
              this.value +
              '</span>'
            );
          },
          useHTML: true,
        } as any,
      },
    
      series: this.series,

draw betwwen the actual date ( real time , change every second ) and other fixed ime point (Xtimestemps,Yvalue) a circle with two arrow ( the arrow length change horizontally independent of those two point (fixed point , changed point)

Following tutorial on audio visualisers in javascript using audio context, audio works but visualiser isn’t

Been following this tutorial by Franks Laboratory https://www.youtube.com/watch?v=VXWvfrmpapI&t=2143s, I’ve done it a few times and successfully got the visualiser to work once. Don’t have the knowledge to figure it out myself could someone try help with what’s wrong… Using visual studio code on Mac, with the latest version of chrome to load the visualiser. Beats me why there’s no bars showing with the audio as all the code is the same as his, the one time I got it to work it was because I tweaked it but I can’t remember how :,).

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Javascript Sounds</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="container">
        <canvas id="canvas1"></canvas>
        <audio src="Hall.mp3" id="audio1" controls></audio>
    </div>    
    <script src="script.js"></script> 
</body>
</html>

Java:

const container = document.getElementById('container');
const canvas = document.getElementById('canvas1');
canvas.width = window.innerWidth;
canvas.height = canvas.innerHeight;
const ctx = canvas.getContext('2d');
let audioSource;
let analyser;

container.addEventListener('click', function(){
    let audio1 = new Audio();
    audio1.src = 'Hall.mp3';
    const audioContext = new AudioContext();
    audio1.play();
    audioSource = audioContext.createMediaElementSource(audio1);
    const analyser = audioContext.createAnalyser();
    audioSource.connect(analyser);
    analyser.connect(audioContext.destination);
    analyser.fftSize = 2048;
    const bufferLength = analyser.frequencyBinCount;
    const dataArray = new Uint8Array(bufferLength);

    const barWidth = canvas.width/bufferLength;
    let barHeight;
    let x;

    function animate(){
        x = 0;
        ctx.clearRect(0, 0, canvas.wdth, canvas.height);
        analyser.getByteFrequencyData(dataArray);
        for (let i = 0; i < bufferLength; i++){
            barHeight = dataArray[i];
            ctx.fillStyle = 'white';
            ctx.fillRect(x, canvas.height - barHeight, barWidth, barHeight);
            x += barWidth;
        }
        requestAnimationFrame(animate);
    };
    animate();
    
});

How can i loop this JS function?

I am relatively new to JS and i need help on this function
I want to loop the following function so that the counter starts from 0 everytime it counted to 4. I’ve looked through the internet but could’nt find anything and would be very happy if someone can help me with this:

onload = init;

function init() {
    var onclick = clickUpdates();
    var btn = document.getElementById("NOButton");
    btn.addEventListener("click", onclick, false);
}
function clickUpdates() {
    var count = 0;
    var next = function() {
        switch(count) {
            case 0:
            // function click 1 here
            card1.style.transitionDuration = '1.2s';
            card1.style.transform = 'translate(-1000px, -200px)';
            card1.style.zIndex = '4';
            function moveCard() {
                var card1 = document.querySelector('.card1');
                var card2 = document.querySelector('.card2');
                var card3 = document.querySelector('.card3');
                setTimeout(function() {
                  setTimeout(function() {
                  card1.style.transitionDuration = '1.2s';
                  card1.style.transform = 'translate(0px, -100px)';
                }, 100);
                  card2.style.transitionDuration = '1.2s';
                  card2.style.transform = 'translate(0px, 50px)';
                  card2.style.zIndex = '3';
                  card3.style.transitionDuration = '1.2s';
                  card3.style.transform = 'translate(0px, 50px)';
                  card3.style.zIndex = '2';
                  card1.style.zIndex = '1';
                }, 10);
              }
              moveCard()
            break;
            case 1:
            // function click 2 here
            function moveCard2() {
                var card1 = document.querySelector('.card1');
                var card2 = document.querySelector('.card2');
                var card3 = document.querySelector('.card3');
                card2.style.transform = 'translate(-1000px, -200px)';
                card2.style.zIndex = '1';
                setTimeout(function() {
                    setTimeout(function() {
                        card2.style.transitionDuration = '1.2s';
                        card2.style.transform = 'translate(0px, -50px)';  
                    }, 100);        
                  card3.style.transitionDuration = '1.2s';
                  card3.style.transform = 'translate(0px, 100px)';
                  card3.style.zIndex = '3';
                  card1.style.transitionDuration = '1.2s';
                  card1.style.transform = 'translate(0px, -50px)';
                  card1.style.zIndex = '2';
                  card2.style.zIndex = '2';
                }, 10);
              }
              moveCard2()
            break;
            case 2:
            // function click 3 here
            function moveCard3() {
                var card1 = document.querySelector('.card1');
                var card2 = document.querySelector('.card2');
                var card3 = document.querySelector('.card3');
                card3.style.transform = 'translate(-1000px, -200px)';
                card3.style.zIndex = '1';
                setTimeout(function() {
                    setTimeout(function() {
                        card3.style.transitionDuration = '1.2s';
                        card3.style.transform = 'translate(0px, 0px)';
                    }, 100);   
                  card1.style.transitionDuration = '1.2s';
                  card1.style.transform = 'translate(0px, 0px)';
                  card1.style.zIndex = '3';
                  card2.style.transitionDuration = '1.2s';
                  card2.style.transform = 'translate(0px, 0px)';
                  card2.style.zIndex = '2';
                  card3.style.zIndex = '1';
                }, 10);
              }
              moveCard3()
            break;
            case 3:
            // function click 4 here
            card1.style.transform = 'translate(-1000px, -200px)';
            moveCard()
            break;
            case 4:
            // function click 5 here
            moveCard2()
            break;
            case 5:
            // function click 6 here
            moveCard3()
            break;
            case 6:
            // function click 7 here
            card1.style.transform = 'translate(-1000px, -200px)';
            moveCard()
            break;
            default:
            // function click 1 here
            moveCard2()
            break;
            
            
        }
        count = count<7?count+1:7;
    }
    
    return next;
}

I am trying to loop this formula but i dont know how.

Retrieve model data from a controller using Next.js and Sequelize

I’m working on a project where my Vue.js is my frontend and my Next.js is my backend. Everything seems to go well, but I don’t know how to get my model data back to my controller…

More info :

  • I used Sequelize to create my models, migrations and seeders.
  • My db is on PostgreSQL

Here is my controller (recetteController.js) where I call findAllRecette() :

// import { Recette } from '../../models/recette';
const { Recette } = require('../../models/recette');
// const Recette = require('../../models/recette');

console.log(Recette);

export default async function handler(req, res) {
    try {
        const recettes = await Recette.getAllRecette(); 
        res.status(200).json(recettes);
    } catch (error) {
        res.status(500).json({ error: 'Erreur lors de la récupération des recettes' });
    }
}

Here is my model (recette) where is my function getAllRecette() :

'use strict';
const { Model } = require('sequelize');

module.exports = (sequelize, DataTypes) => {
  class Recette extends Model {
    static associate(models) {
      Recette.belongsTo(models.Difficulte, { foreignKey: 'id_difficulte', as: 'difficulte' });
      Recette.belongsTo(models.Categorie, { foreignKey: 'id_categorie', as: 'categorie' });
    }
  
    // Récupère toutes les recettes
    static async getAllRecette() {
      console.log("CONGRATS");
      const recettes = await this.findAll();
      return recettes;
    }
  }

  Recette.init({
    nom: DataTypes.STRING,
    description: DataTypes.STRING,
    portion: DataTypes.INTEGER,
    temps: DataTypes.INTEGER,
    id_difficulte: DataTypes.INTEGER,
    id_categorie: DataTypes.INTEGER,
    image: DataTypes.TEXT
  }, {
    sequelize,
    modelName: 'Recette',
  });

  return Recette;
};

I have never done this before except for Laravel and maybe I am doing this wrong … (MVC)

The problem is that the console.log(Recette) gives me a ‘undefined’ or ‘[Function (anonymous)]’ depending on how I import Recette

I have also tried to call findAll() directly in my controller but that did not change the fact that my controller doesn’t found my model.

please i spent too much time fixing this ! Thank you !

Priority precedence of operations in the JavaScript code

I would like to improve my app in JavaScript by implementing a new modern features : the priority precedence of the operations. What I meant by that is as follows. The app, the calculator will be able to show the parentheses buttons : ( and ) so that it should be able to operate with them.
For example Input = (2+3) * (20-10) should logically output 50.
How can I handle the parentheses as the priority precedence in my app please?

My operate function

export default function operate(numberOne, numberTwo, operation) {
  const one = Big(numberOne);
  const two = Big(numberTwo);
  if (operation === '+') {
    return one.plus(two).toString();
  }
  if (operation === '-') {
    return one.minus(two).toString();
  }
  if (operation === 'x') {
    return one.times(two).toString();
  }
  ......
  }

My calculate operation look like the following:

import operate from './operate';

function isNumber(item) {
  return !!item.match(/[0-9]+/);
}

/**
 * Given a button name and a calculator data object, return an updated
 * calculator data object.
 *
 * Calculator data object contains:
 *   total:s      the running total
 *   next:String       the next number to be operated on with the total
 *   operation:String  +, -, etc.
 */
export default function calculate(obj, buttonName) {
  if (buttonName === 'AC') {
    return {
      total: null,
      next: null,
      operation: null,
    };
  }

  if (isNumber(buttonName)) {
    if (buttonName === '0' && obj.next === '0') {
      return {};
    }
    // If there is an operation, update next
    if (obj.operation) {
      if (obj.next) {
        return { ...obj, next: obj.next + buttonName };
      }
      return { ...obj, next: buttonName };
    }
    // If there is no operation, update next and clear the value
    if (obj.next) {
      return {
        next: obj.next + buttonName,
        total: null,
      };
    }
    return {
      next: buttonName,
      total: null,
    };
  }

  if (buttonName === '.') {
    if (obj.next) {
      if (obj.next.includes('.')) {
        return { ...obj };
      }
      return { ...obj, next: `${obj.next}.` };
    }
    if (obj.operation) {
      return { next: '0.' };
    }
    if (obj.total) {
      if (obj.total.includes('.')) {
        return {};
      }
      return { total: `${obj.total}.` };
    }
    return { total: '0.' };
  }

  if (buttonName === '=') {
    if (obj.next && obj.operation) {
      return {
        total: operate(obj.total, obj.next, obj.operation),
        next: null,
        operation: null,
      };
    }
    // '=' with no operation, nothing to do
    return {};
  }

  if (buttonName === '+/-') {
    if (obj.next) {
      return { ...obj, next: (-1 * parseFloat(obj.next)).toString() };
    }
    if (obj.total) {
      return { ...obj, total: (-1 * parseFloat(obj.total)).toString() };
    }
    return {};
  }

  // Button must be an operation

  // When the user presses an operation button without having entered
  // a number first, do nothing.
  if (!obj.next && !obj.total) {
    return {};
  }

  // User pressed an operation after pressing '='

  if (!obj.next && obj.total && !obj.operation) {
    return { ...obj, operation: buttonName };
  }

  // User pressed an operation button and there is an existing operation
  if (obj.operation) {
    if (obj.total && !obj.next) {
      return { ...obj, operation: buttonName };
    }

    return {
      total: operate(obj.total, obj.next, obj.operation),
      next: null,
      operation: buttonName,
    };
  }

  // no operation yet, but the user typed one

  // The user hasn't typed a number yet, just save the operation
  if (!obj.next) {
    return { operation: buttonName };
  }

  // save the operation and shift 'next' into 'total'
  return {
    total: obj.next,
    next: null,
    operation: buttonName,
  };
}

This calculate is used in the calculator component by the handleEvent function

const handleEvent = (e) => {
    setState({ ...state, ...calculate(state, e.target.name) });
  };

And the UI use the handleEvent to show the button:

 <button type="button" className="grayButton" name="(" onClick={handleEvent}>(</button>
 <button type="button" className="grayButton" name=")" onClick={handleEvent}>)</button>

How do I locate and block a Javascript function?

A website that I’m using has an annoying pop-up that randomly appears on the screen every x minutes. Inside the Chrome developer tool bar using the ‘break on subtree modifications’ option, I can see that it’s calling insertBefore and removeChild functions inside of jquery-2.0.3.min.js. Specifically the following.

        before: function() {
            return this.domManip(arguments, function(e) {
                this.parentNode && this.parentNode.insertBefore(e, this)
            })
        },
        after: function() {
            return this.domManip(arguments, function(e) {
                this.parentNode && this.parentNode.insertBefore(e, this.nextSibling)
            })
        },
        remove: function(e, t) {
            var n, r = e ? x.filter(e, this) : this, i = 0;
            for (; null != (n = r[i]); i++)
                t || 1 !== n.nodeType || x.cleanData(mt(n)),
                n.parentNode && (t && x.contains(n.ownerDocument, n) && dt(mt(n, "script")),
                n.parentNode.removeChild(n));
            return this
        },

On the website itself it generates a div with a random css id, hangs around for a minute then disappears.

It doesn’t look like any particular event is causing this to fire.

Do you have any tips on how I can find out more about what’s happening and how I can block it? I believe I should be able to block this using something like greasemonkey.

Any insight would be much appreciated, plus this has been a valuable learning experience so far.

Thanks for taking the time to read this.

problem in using websocket with typescript

i’m new to typescript and i wanna create a websocket client using typescript and websocket library. you can see my code below. the problem is when i’m passing an arrow function in this this.client.on("connect", this.handleConnection); line of code the code works fine without errors, but when i pass thisthis.handleConnection method i get the below error . what can i do about this?

import { Logger } from "./logger";


enum WebsocketStatus{
    CONNECTING = 'connecting',
    STOPPED = 'stopped',
    CONNECTED= 'connected',
    IDLE = 'idle'
}
interface WebsocketInterface{
    getStatus(): WebsocketStatus
    connect(): void
    disconnect(): void
    sendMessage(message: string): void
}

export class WebsocketClient implements WebsocketInterface{
    private status: WebsocketStatus;
    private url: string;
    private logger?: Logger;
    private client: webSocket.client;
    private connection?: webSocket.connection;
    constructor(url: string, logger?: Logger){
        if(logger)
            this.logger = logger;
        this.url = url;
        this.status = WebsocketStatus.IDLE;
        this.client = new webSocket.client();
        this.client.on("connectFailed", this.handleConnectionFailed);
        this.client.on("connect", this.handleConnection);
    }
    getStatus(): WebsocketStatus {
        return this.status;
    }
    connect(): void {
        this.client.connect(this.url);
    }
    disconnect(): void {
        this.connection?.close()
    }
    private handleConnectionFailed(error: Error){
        this.logger?.logError(error.message);
    }
    private handleConnection(connection: webSocket.connection){
        this.connection = connection;
        this.logger?.logInfo(`successfully connected to address ${this.url}`);
        this.connection.on("error", this.handleConnectionError);
        this.connection.on("close", this.handleConnectionClose);
        this.connection.on("message", this.handleConnectionMessage);
    }
    private handleConnectionError(error:Error){
        this.logger?.logError(error.toString());
        this.status = WebsocketStatus.STOPPED;
        this.connection?.close();
    }
    private handleConnectionClose(){
        this.logger?.logInfo("connection closed");
        this.status = WebsocketStatus.STOPPED;
        this.connection?.close();
    }
    private handleConnectionMessage(message: webSocket.Message){
        this.logger?.logInfo(message.toString());

    }
    sendMessage(message: string): void {
        this.connection?.send(message);
    }
}

TypeError [ERR_INVALID_ARG_TYPE]: The “listener” argument must be of type function. Received undefined
at checkListener (node:events:265:3)
at _addListener (node:events:545:3)
at WebSocketConnection.addListener (node:events:604:10)
at WebSocketClient.handleConnection (/home/mohammad/projects/alphaTrader/digestion/wsConnector.ts:57:25)
at WebSocketClient.emit (node:events:512:28)
at WebSocketClient.emit (node:domain:489:12)
at WebSocketClient.succeedHandshake (/home/mohammad/projects/alphaTrader/digestion/node_modules/websocket/lib/WebSocketClient.js:348:10)
at WebSocketClient.validateHandshake (/home/mohammad/projects/alphaTrader/digestion/node_modules/websocket/lib/WebSocketClient.js:332:10)
at ClientRequest.handleRequestUpgrade (/home/mohammad/projects/alphaTrader/digestion/node_modules/websocket/lib/WebSocketClient.js:261:14)
at ClientRequest.emit (node:events:512:28) {
code: ‘ERR_INVALID_ARG_TYPE’
}

I’m unable to come up with a logic for a big multistep form in React

const PackageBuilder = () => {

  const {
    page,
    setPage,
    nights,
    subPage,
    setSubPage,
    travellerDetails,
    disableNext,
    disableBack,
  } = useFormContext();


  


  const handleBack = () => {
    if(page>2 || subPage === 1){
    setPage(prev => prev - 1);
    } else{
      setSubPage(prev => prev - 1)
    }
  }
  const handleNext = () => {


    if (page<2 || subPage === nights + 1) {
      setPage(prev => prev + 1);
    }else{
      setSubPage(prev => prev + 1);
    }
  }

  const handleSubmit = e => {
    e.preventDefault()
  
  }


  const display = {
    1: <TravellerDetails />,
    2: <ItineraryDetails />, // You can replace this with your actual components
    3: <DepartureRates />, // You can replace this with your actual components
    4: <PricingDetails />
  };
  return (
    <div>
      <div>
        <WizardBar />
      </div>

      <form onSubmit={handleSubmit}>
        <div>
          {display[page]}
        </div>

        <div>
          {page > 1 ?
            <button onClick={handleBack} disabled={disableBack}>Back</button>
            : <button>Back</button>

          }

          <button onClick={handleNext} disabled={disableNext}>Next</button>
        </div>
      </form>
    </div>
  )
}

So this is the Structure of the Form. Traveller Details has around 7 inputs, then Itinerary Details has arounded 4 sub-steps (When we reach the itinerary page, the next button will not reach the DeparturesRates Component untill all the 4 pages of Itinerary Details are iterated over) then Departure Rates has very dynamic data (input fields can vary from 20 – 30 fields depending on the user how many he adds) and then the PricingDetails will show the final Submit page.
So what my current logic does is when I change values in TravellerDetails Component , it rerenders everytime on onChange, which in my opinion feels like very inefficient for so many inputs (I can be wrong as i’ve been using react for few months only). I was thinking if there was a approach of saving the component’s data in the locally in the component and then when next is clicked, the data is passed to the state in the Context, so that when the back button is clicked, the data is still there.
So how could I do that in the above structure.
Thank You

I tried creating refs in the PackageBuilder Component but I think that will be very inefficient as there are 4 children components and one child has 3 children. That will be a lot of data being stored in the parent component.

Basic Discord.js bot not going online

I am trying to creat a discord js bot and followed a tutorial (i cant seem to find it again) I also found some other posts on Stack Overflow but i tried them and they also didn’t work (its probably a stupid error because i am a beginner):

import { Client, GatewayIntentBits } from 'discord.js';
const client = new Client({ 
    intents: [
        GatewayIntentBits.Guilds
    ] 
});

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.login('I have the wright token inserted');

It doesn’t console log it or show the green online dot on Discord.
Please Help.