Is there a way to reduce if else conditions while validating all the keys of a request payload?

I have a request payload with multiple keys (about 20 to 30) like name, email, phone number, address etc and some of these are optional.

To validate those I use multiple if/else conditions and in some cases I need to include validation based on a dependent key too.

For example: If I have a value in the address key, then values for the city, state and zip keys are mandatory. In this scenario I have a bunch of if/else conditions in my code. Is there a way to minimize the if conditions and improve my code?

I’m expecting to reduce the number of if/else conditions

ForbiddenError: invalid csrf token in express.js

I tried to apply my frontend pages to 2 different servers: Django and Express.js. In Django I used csrf tokens and so I want to use same frontend pages for 2 servers. So I tried to apply csrf tokens to my express server, and I got error when I tried to move to my admin page. In Django all works fine, but smth wrong in Express server. My Express version is 4.19.2. Also I don’t know how to use same html and script.js files for both Django server and Express

So here is my app.js with all settings:

    const express = require('express');
    const mongoose = require('mongoose');
    const session = require('express-session');
    const crypto = require('crypto');
    const path = require('path');
    const routes = require('./routes');
    const dotenv = require('dotenv');
    const csrf = require('csurf');
    const cookieParser = require('cookie-parser');
    const bodyParser = require('body-parser');

    dotenv.config();

    const app = express();
    const port = 3000;

    const secretKey = crypto.randomBytes(32).toString('hex');

    const mongoURI = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/mydatabase';
    mongoose.connect(mongoURI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });

    const db = mongoose.connection;

    db.on('error', console.error.bind(console, 'MongoDB connection error:'));
    db.once('open', async () => {
    console.log('Connected to MongoDB');
    });

    app.use(express.static(path.join(__dirname, '..','public')));

    app.use(session({
    secret: secretKey,
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false },
    }));

    app.use(cookieParser());

    const csrfProtection = csrf({ cookie: true });
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    app.use(csrfProtection);

    app.use((req, res, next) => {
    res.locals.csrfToken = req.csrfToken();
    res.locals.using_django = false;
    next();
    });

    app.use('/', routes);

    app.get('/public/styles.css', (req, res) => {
    res.sendFile(path.join(__dirname, '..','public', 'styles.css'));
    });

    app.get('/public/script.js', (req, res) => {
    res.sendFile(path.join(__dirname, '..','public', 'script.js'));
    });

    app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, '..', 'views', 'main.html'));
    });

    app.get('/modify-gifs', csrfProtection, (req, res) => {
    if (!req.session.isAuthenticated) {
    res.redirect('/'); 
    return;
    }

    res.sendFile(path.join(__dirname, '..', 'views', 'Modify-GIF.html'));
    });

    app.use((req, res, next) => {
    res.status(404).sendFile(path.join(__dirname, '..', 'views', '404.html'));
    });

    app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
    });

authentification route in routes.js:

    router.post('/check-auth', (req, res) => {
    const { login, password } = req.body;

    if (login === process.env.ADMIN_LOGIN && password === process.env.ADMIN_PASSWORD) {
    req.session.isAuthenticated = true;
    res.status(200).json({ isAuthenticated: true, message: 'Authentication successful' });
      } else {
    req.session.isAuthenticated = false;
    res.status(401).json({ isAuthenticated: false, message: 'Invalid login or password' });
      }
    });

script.js:

    let isAuthenticated = false;
    let csrfToken = '';
    document.addEventListener('DOMContentLoaded', function () {
    csrfToken = getCsrfToken();
    function getCsrfToken() {
        const tokenElement = document.querySelector('meta[name="csrf-token"]');
        if (tokenElement) {
            return tokenElement.getAttribute('content');
        } else {
            console.error('CSRF token not found');
            return '';
        }
    }

    
    });
    function authenticateAndShowTab() { //TODO: fix with sessions
    const login = prompt('Enter login:');
    const password = prompt('Enter password:');

    fetch('/check-auth', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRFToken': csrfToken,
    },
    body: JSON.stringify({ login, password }),
    })
    .then(response => {
            console.log('Response status:', response.status);
            return response.json();
        })
        .then(data => {
            console.log('Response data:', data);
            if (data.isAuthenticated) {
                isAuthenticated = true;
                sessionStorage.setItem('isAuthenticated', 'true');
                showTab('modGif');
            } else {
                isAuthenticated = false;
                alert('Invalid login or password. Please try again.');
            }
        })
    .catch(error => {
      console.error('Error checking authentication:', error);
    });
    }
    function showTab(tabName) {
    const savedAuthStatus = sessionStorage.getItem('isAuthenticated');
    isAuthenticated = savedAuthStatus === 'true';

    if (tabName === 'main') {
    window.location.href = '/'; 
    } else if (tabName === 'modGif') {
    if (!isAuthenticated){
      authenticateAndShowTab();
      return;
    }
    window.location.href = '/modify-gifs';
    }
    }

Also, here is Modify-Gif.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token }}">
    <title>Modify GIFs</title>
    <link rel="stylesheet" type="text/css" href="/public/styles.css">
    <script src="/public/script.js"></script>
    </head>
    <body>
    <div id="tabs">
    <button class="tab-button" data-tab="main" onclick="showTab('main')">Main</button>
    <button class="tab-button active-tab" data-tab="modGif" onclick="showTab('modGif')">Modify Gifs</button>
    </div>
  
    <form id="uploadForm" action="/upload" method="post" enctype="multipart/form-data" style="display: block;">
    {% csrf_token %}
    <h2>File Upload</h2>
    <input type="file" name="file">
    <input type="text" name="filename" id="filename" placeholder="Enter GIF name">
    <input type="text" name="attributes" id="attributesInput" placeholder="Enter attributes (comma-separated)">
    <input type="submit" value="Upload File">
    </form>
  

    <div id="ViewGIFForm" style="display: block;">
    <h2>View GIF</h2>
    <input type="text" id="gifIdInput" placeholder="GIF ID">
    <button onclick="openGif()">Open GIF</button>
    <button onclick="deleteGif()">Delete GIF</button>

    <video id="" controls class="styled-video" style="display: none;"></video>
    <img id="gifImage" style="display: none;">
    <div id="gifAttributes"></div>
    <div id="gifName"></div>
    </div>
    <script>

      displayGifList();
      function deleteGif() {
        const gifIdInputDel = document.getElementById('gifIdInput');
        const gifId = gifIdInputDel.value;

        if (!gifId) {
          alert('Please enter GIF ID to delete.');
          return;
        }

        fetch(`/gif/${gifId}`, {
          method: 'DELETE',
          headers: {
            'X-CSRFToken': csrfToken
          }
        })
          .then(response => {
            if (response.ok) {
              console.log('GIF deleted successfully.');
              alert('GIF deleted successfully.');
            } else if (response.status === 404) {
              console.error('GIF not found.');
              alert('GIF not found.');
            } else {
              console.error('Error deleting GIF:', response.status);
              alert('Error deleting GIF.');
            }
          })
          .catch(error => {
            console.error('Error deleting GIF:', error);
            alert('Error deleting GIF.');
          });
    }
    </script>
    </body>
    </html>

and main.html:

   <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token }}">
    <title>All GIF List</title>
    <link rel="stylesheet" type="text/css" href="/public/styles.css">
    <script src="/public/script.js"></script>
    </head>
    <body>
    <div id="tabs">
    <button class="tab-button active-tab" data-tab="main" onclick="showTab('main')">Main</button>
    <button class="tab-button" data-tab="modGif" onclick="showTab('modGif')">Modify Gifs</button>
    </div>


    <div id="ViewAndDownloadGIFForm" style="display: block;">
    <h2>View and Download GIF</h2>
    <input type="text" id="gifIdInput" placeholder="GIF ID">
    <input type="text" id="downloadFileNameInput" name="filename" placeholder="Enter file name (in Latin)">
    <button onclick="openGif()">Open GIF</button>
    <button onclick="downloadGif()">Download GIF</button>
        
    <video id="" controls class="styled-video" style="display: none;"></video>
    <img id="gifImage" style="display: none;">
    <div id="gifAttributes"></div>
    <div id="gifName"></div>
    </div>
    </body>
    </html>

P.S. Sorry for the possibly stupid question or bad wording. This is my first public question here

I tried to remove the authentication (by commenting out the code) but got the same error when I tried to send a GIF to the database.

Also i tried to include some middleware from this question:

app.use(express.urlencoded({ extended: true }));

To use the same files for different servers, I tried to apply a condition, but it only works on Django (on Express it appears visually on the page):
Modify-Gif.html

    {% if using_django %}
    {% csrf_token %}
     {% else %}
    <input type="hidden" name="_csrf" value="{{ csrf_token }}">
    {% endif %}

Also i tried to replace this:
<meta name="csrf-token" content="{{ csrf_token }}">

to this:
<meta name="csrf-token" content="{{csrfToken}}">
but still i got same error

And if i keep this change i will get error in Django:
Forbidden (CSRF token from the ‘X-Csrftoken’ HTTP header has incorrect length.): /check-auth
[07/Aug/2024 17:19:18] “POST /check-auth HTTP/1.1” 403 2563

Also i tried to replace some code from answer to this question:

app.use(crsfProtection);

to

app.use(crsfProtection());

But then i got error:
return req[cookieKey]
^

TypeError: Cannot read properties of undefined (reading ‘cookies’)

BSONTypeError: Unsupported type BigInt, please use Decimal128

I’m trying to create a sort of timer command with Discord.js and MongoDB. I currently use mongoose as the wrapper. I am also using Agenda to automatically delete the timers from the database after the specified time period.
Once the bot is ready, the bot goes through the timers from the database and the agenda jobs are postponed/executed depending on the time.

// models.timer refers to the Model from mongoose itself.
const timers = await models.timer.find();
for (const timer of timers) {
  if (Date.now() > timer.endsAt) {
    // this is logged correctly
    console.log(Date.now(), timer.endsAt, timer.id);
    await agenda.now<RemoveTimer>(AgendaJobs.RemoveTimer, {
      timerId: timer.id,
      client: this.container.client,
    });
    // this doesn't log at all
    console.log("done");
  } else
    await agenda.schedule<RemoveTimer>(
      new Date(timer.endsAt),
      AgendaJobs.RemoveTimer,
      {
        timerId: timer.id,
        client: this.container.client,
      }
    );
}

I have the Agenda job which supposedly never runs

agenda.define<RemoveTimer>(
  AgendaJobs.RemoveTimer,
  async (job: Job<RemoveTimer>) => {
    // never gets logged, code doesn't continue
    console.log("job");
    const { timerId, client } = job.attrs.data;
    console.log("job", timerId);
    const timer = await models.timer.findByIdAndDelete(timerId);
    if (!timer) return;
    const message = `Timer for **${timer.name}** has ended! <@${timer.createdBy}>`;
    if (timer.dm) {
      const channel = client.channels.cache.get(timer.channelId);
      if (channel?.type !== ChannelType.GuildText) return;
      await channel.send(message).catch(() => {});
    } else {
      await client.users.send(timer.createdBy, message).catch(() => {});
    }
  }
);

The mongoose schema:

const schema = new Schema<ITimer>({
  name: {
    type: String,
    default: "Timer",
  },
  createdBy: String,
  channelId: String,
  endsAt: Number,
  dm: {
    type: Boolean,
    default: false,
  },
});
export const TimerModel = model<ITimer>("timer", schema);

After the last successful log from the first code (which logs the current unix time, the time in which the timer ends at, and the string version of the id of the timer provided by mongoose), the code supposedly stops running, and I get this error:

2024-08-07 19:58:26 - ERROR - Encountered error on event listener "ready" for event "ready" at path "H:GitStuffnightmare-utilsdistlistenersready.js" BSONTypeError: Unsupported type BigInt, please use Decimal128
2024-08-07 19:58:26 - ERROR -     at new BSONTypeError (H:GitStuffnightmare-utilsnode_modulesmongodbnode_modulesbsonliberror.js:41:28)
2024-08-07 19:58:26 - ERROR -     at serializeInto (H:GitStuffnightmare-utilsnode_modulesmongodbnode_modulesbsonlibparserserializer.js:788:35)
2024-08-07 19:58:26 - ERROR -     at serializeObject (H:GitStuffnightmare-utilsnode_modulesmongodbnode_modulesbsonlibparserserializer.js:282:20)
2024-08-07 19:58:26 - ERROR -     at serializeInto (H:GitStuffnightmare-utilsnode_modulesmongodbnode_modulesbsonlibparserserializer.js:813:25)
2024-08-07 19:58:26 - ERROR -     at serializeObject (H:GitStuffnightmare-utilsnode_modulesmongodbnode_modulesbsonlibparserserializer.js:282:20)
2024-08-07 19:58:26 - ERROR -     at serializeInto (H:GitStuffnightmare-utilsnode_modulesmongodbnode_modulesbsonlibparserserializer.js:813:25)
2024-08-07 19:58:26 - ERROR -     at serializeObject (H:GitStuffnightmare-utilsnode_modulesmongodbnode_modulesbsonlibparserserializer.js:282:20)
2024-08-07 19:58:26 - ERROR -     at serializeInto (H:GitStuffnightmare-utilsnode_modulesmongodbnode_modulesbsonlibparserserializer.js:813:25)
2024-08-07 19:58:26 - ERROR -     at serializeObject (H:GitStuffnightmare-utilsnode_modulesmongodbnode_modulesbsonlibparserserializer.js:282:20)
2024-08-07 19:58:26 - ERROR -     at serializeInto (H:GitStuffnightmare-utilsnode_modulesmongodbnode_modulesbsonlibparserserializer.js:607:25) {
2024-08-07 19:58:26 - ERROR -   originalLine: 45,
2024-08-07 19:58:26 - ERROR -   originalColumn: 30
2024-08-07 19:58:26 - ERROR - }

While using scss in vite react with bootstrap

while using sass in Vite react with bootstrap, the installation is properly done of bootstrap and sass and import is also working but only few styles are working, like width and height is working but Bg-color is not …

I tried vanilla CSS as well as sass and I don’t want to use tailwind or inline CSS

JavaScript ID will not duplicate and using class doesn’t work either

I need my code colour highlights to function more than once on a page. I am using a JavaScript string but with ID but this doesn’t duplicate it, it only works for the first ID then the second and third don’t work. I have tried using class but this doesn’t work either.

w3CodeColor(document.getElementById("mycode"));
w3CodeColor(document.getElementsByClassName("mycode"));

Both of these don’t work

This is what I have tried already:

w3CodeColor(document.getElementsById("mycode"));
w3CodeColor(document.getElementsByClassName("mycode"));

write a program in js to print student list with courses and score [closed]

program explanation:
first ask student name & course1 & score of course1 from user.
then ask if student have more courses?
if yes add another course with score
if not ask user if new student needed
if yes define new student with his cources and score and add to student list
if not print student list;
i write following code but it works only work for one student.

var studentList = [];

function addnewstudent() {
  var studentInfo = {
    name: '',
    courses: {}
  }
  var studentName = prompt("name");
  studentInfo.name = studentName;
  var newLesson = prompt("new course");
  var score = prompt("nomre");
  for (label in studentInfo) {
    if (typeof studentInfo[label] === 'object') {
      studentInfo[label][newLesson] = score;
    }
  }
  studentList.push(studentInfo);
  console.log(studentList);
}
addnewstudent();

serialize and deserialize dates

I want to serialize and deserialize dates using a custom format. For that, I’m trying to intercept the date during JSON.stringify() using a custom receiver

function serialize(data) {
   if (data === undefined) {
      return JSON.stringify('__undef__')
   }

   if (data instanceof Date) {
      return JSON.stringify({ _t: 'dt', v: data.getTime() })
   }

   return JSON.stringify(data, (_, value) => {
      if (value === undefined) {
         return '__undef__'
      }

      if (value instanceof Date) {
         return { _t: 'dt', v: value.getTime() }
      }

      return value
   })
}

console.log(serialize(new Date(2024, 7, 4))); // {"_t":"dt","v":1722729600000}
console.log(serialize([undefined, new Date(2024, 7, 4)])); // ["__undef__","2024-08-04T00:00:00.000Z"]

Seems like the receiver is not intercepting the date format before serialization.

What am I doing wrong?

Why are my shapes disappearing when I soft-drop in my Tetris implementation?

I’m working on implementing Tetris in JavaScript. I’m new to JavaScript, so the way I’m coding may not be the most practical or efficient seeing as I’m trying to minimize the amount of help I’m getting.

That being said, when I try to move down my shape (soft-drop) before the shape appears in the grid, it’ll disappear halfway down the grid whether I let go or not. If the shape is already visible fully, it has no problem soft dropping. Only if I’m holding the down key it has issues.

Below is what I think it related to the issue. I cut out a lot of extra information, but I can’t tell if any function is messing with another. I’d appreciate any help and guidance! 🙂

I tried adjusting the conditions of when my pieces should lock, like after passing a certain y but that didn’t help. I added an invisible area above the grid where I tried spawning my pieces but that didn’t really work. I’m expecting that even if I preemptively soft-drop, the piece will just fly down the grid without disappearing. regardless of these changes, i still have disappearing shapes. I know this is a lot, but I appreciate any help!!

const ROW = 22;
const VISIBLE_ROW = 20;
const COL = COLUMN = 10;
const SQ = squareSize = 30;

// draw a square
function drawSquare(x, y, color) {
  ctx.fillStyle = color;
  ctx.fillRect(x * SQ, y * SQ, SQ, SQ);

  ctx.strokeStyle = 'WHITE';
  ctx.strokeRect(x * SQ, y * SQ, SQ, SQ);
}

// create the board
let board = [];
for (let r = 0; r < ROW; r++) {
  board[r] = [];
  for (let c = 0; c < COL; c++) {
    board[r][c] = VACANT;
  }
}

// draw the board
function drawBoard() {
  for (let r = 2; r < ROW; r++) {
    for (let c = 0; c < COL; c++) {
      drawSquare(c, r - 2, board[r][c]);
    }
  }
}

drawBoard();

// TETROMINO SHAPE EXAMPLE (of how I made them)
const Z = [
  [
    [1, 1, 0],
    [0, 1, 1],
    [0, 0, 0]
  ],

  [
    [0, 0, 1],
    [0, 1, 1],
    [0, 1, 0]
  ]
];


// piece constructor
function Piece(tetromino, color) {
  this.tetromino = tetromino;
  this.color = color;

  this.tetrominoN = 0; // start from the first pattern
  this.activeTetromino = this.tetromino[this.tetrominoN];

  // control the pieces
  this.x = 3;
  this.y = 1;
}

// draw piece to the board
Piece.prototype.draw = function() {
  for (let r = 0; r < this.activeTetromino.length; r++) {
    for (let c = 0; c < this.activeTetromino.length; c++) {
      // draw only occupied squares
      if (this.activeTetromino[r][c]) {
        let drawY = this.y + r;
        if (drawY >= 2) { // draw only visible rows
          drawSquare(this.x + c, drawY - 2, this.color);
        }
      }
    }
  }
}

// undraw piece from the board
Piece.prototype.unDraw = function() {
  for (let r = 0; r < this.activeTetromino.length; r++) {
    for (let c = 0; c < this.activeTetromino.length; c++) {
      // undraw only occupied squares
      if (this.activeTetromino[r][c]) {
        let drawY = this.y + r;
        if (drawY >= 2) { // draw only visible rows
          drawSquare(this.x + c, drawY - 2, VACANT);
        }
      }
    }
  }
}

// gravity dropping piece
Piece.prototype.gravityDrop = function() {
  if (!this.collision(0, 1, this.activeTetromino)) {
    this.unDraw();
    this.y++;
    this.draw();
  } else {
    this.handleLockDelay();
  }
}

// handle lock delay
Piece.prototype.handleLockDelay = function() {
  if (lockDelayTimer) {
    clearTimeout(lockDelayTimer);
  }

  lockDelayTimer = setTimeout(() => {
    // lock current piece and generate new piece
    this.lock();
    if (!gameOver) {
      p = randomPiece();
    }
  }, lockDelay);

  // increment move count and reset lock delay if under max moves
  if (moveCount < maxMoves) {
    moveCount++;
  } else {
    this.lock();
    if (!gameOver) {
      p = randomPiece();
    }
  }
}

// move piece down
Piece.prototype.softDrop = function() {
  if (this.y >= 1 && !this.collision(0, 1, this.activeTetromino)) {
    this.unDraw();
    this.y++;
    this.draw();
    score += 1; // add 1 point per row for soft drop
    updateScoreDisplay();
  } else {
    this.handleLockDelay();
  }
}

// collision detection
Piece.prototype.collision = function(x, y, piece) {
  for (let r = 0; r < piece.length; r++) {
    for (let c = 0; c < piece.length; c++) {
      if (!piece[r][c]) {
        continue;
      }
      let newX = this.x + c + x;
      let newY = this.y + r + y;
      if (newX < 0 || newX >= COL || newY >= ROW) {
        return true;
      }
      if (newY < 0) {
        return false;
      }
      if (board[newY][newX] != VACANT) {
        return true;
      }
    }
  }
  return false;
}

// lock piece and generate a new one
Piece.prototype.lock = function() {
  let lines = 0;
  for (let r = 0; r < this.activeTetromino.length; r++) {
    for (let c = 0; c < this.activeTetromino.length; c++) {
      if (!this.activeTetromino[r][c]) {
        continue;
      }
      if (this.y + r < 2) {
        // game over
        alert('Game Over');
        gameOver = true;
        break;
      }
      board[this.y + r][this.x + c] = this.color;
    }
  }
  // remove full rows & update score
  for (let r = 0; r < ROW; r++) {
    let isRowFull = true;
    for (let c = 0; c < COL; c++) {
      isRowFull = isRowFull && (board[r][c] != VACANT);
    }
    if (isRowFull) {
      for (let y = r; y > 1; y--) {
        for (let c = 0; c < COL; c++) {
          board[y][c] = board[y - 1][c];
        }
      }
      for (let c = 0; c < COL; c++) {
        board[0][c] = VACANT;
      }
      lines++;
    }
  }
  if (lines > 0) {
    // update score based on number of lines cleared
    const action = lines === 1 ? 'single' : lines === 2 ? 'double' : lines === 3 ? 'triple' : 'tetris';
    score += calculateScore(action, level);

    linesCleared += lines;
    if (linesCleared >= linesPerLevel) {
      level++;
      linesCleared -= linesPerLevel;
    }
    updateScoreDisplay();
  }
  drawBoard();
}

// Drop the piece every 1sec
let dropStart = Date.now();
let gameOver = false;

function drop() {
  let now = Date.now();
  let delta = now - dropStart;
  if (delta > getGravitySpeed(level)) {
    p.gravityDrop();
    dropStart = Date.now();
  }
  if (!gameOver) {
    requestAnimationFrame(drop);
  }
}

drop();
<span id="score"></span><br />
<span id="level"></span><br />
<span id="lines"></span><br />

<canvas id="gameCanvas" width="800" height="800"></canvas>

Form Submit in jsp and servlet doesn’t work when Bootstrap’s js file is added

Without js the login form works but if I add the js(Bootstrap CDN) login doesn’t work.

this is the js script tag:

<script type="text/javascript" src="https://mdbcdn.b-cdn.net/wp-content/themes/mdbootstrap4/docs-app/js/dist/mdb5/standard/core.min.js"></script>

If I remove this some of the styling disappears. What to do

I tried the latest js cdn still doesn’t work. I think I have to choose between bootstrap or servlet.

Warning: React has detected a change in the order of Hooks called by NavButton. This will lead to bugs and errors if not fixed

I have following component in next js:

const NavButton = ({icon, 'icon-active': iconActive, title, link, badge, refreshable = false}) => {
    const {pathname, reload} = useRouter();
    const isActive = link === pathname;
    const Icon = isActive ? iconActive : icon;
    const handleRefreshIfRequired = e => {
        if (!refreshable) return;
        if (isActive) {
            e.preventDefault();
            reload();
        }
    };
    return <Link href={link}
                 onClick={handleRefreshIfRequired}
                 className={clsx('home-page-button', {'home-page-button-active': isActive})}>
        <div className="button-icon">
            <Icon/>
        </div>
        <div className="button-title">
            {title}
            {badge && <strong
                className={'bg-danger card text-white px-1 border-none ms-1 font-bold animate-fade inline-block'}>{abbrNumber({number: badge})}</strong>}
        </div>
    </Link>;
};

Now when I use the component, it says:

Warning: React has detected a change in the order of Hooks called by NavButton. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks

   Previous render            Next render
   ------------------------------------------------------
1. useContext                 useContext
2. undefined                  useContext
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

ReactDOMClient is not defined

I am trying to get started with ReactJS and I have watched a beginners Pluralsight course. I seem to be falling at the first hurdle followin what the tutor is doing. Here is my HTML (index.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple React app no JSS</title>
    <script src="index.js" ></script>
    <script type="module">
        import React from
        "https://esm.sh/[email protected]/?dev"

        import ReactDOMClient from
        "https://esm.sh/[email protected]/client/?dev"
    </script>
</head>
<body>
    <div id="root"></div>
</body>
</html>

Here is my Javascript (index.js):

window.onload = () => {
    const rootElement=document.getElementById("root");
    const root = ReactDOMClient.createRoot(rootElement);
    const ints = [1,2,3]
    const childrenElements = [];
    childrenElements.push(
        React.createElement("li", { key:ints[0] }, ints[0])
    );
    childrenElements.push(
        React.createElement("li", { key:ints[1] }, ints[1])
    );
    childrenElements.push(
        React.createElement("li", { key:ints[2] }, ints[2])
    );
    root.render(childrenElements);
}

Nothing is displayed, which is not the case for the tutor. If I inspect console after pressing F12, then I see this:

enter image description here

If I manually browse (using a web browser) to https://esm.sh/[email protected]/?dev or https://esm.sh/[email protected]/client/?dev then I see content so I beliece they are valid.

`shiny`: adding a `tag` for scrolling and continuously scrolling to the bottom?

Following this I have implemented a container for continuously capturing R console output including scrolling capabilities.

The corresponding bit in ui.R looks like so:

shiny::tabPanel(
  title = "Console 
  shiny::verbatimTextOutput(
    outputId    = "consolemessages",
    placeholder = TRUE),
  shiny::tags$head(
    shiny::tags$style(
      "#consolemessages{overflow-y: scroll; max-height: 800px;}"
    )
  )
)

In server.R I am using the following function to capture the Rconsole content:

capture_console_output <- function(
  fnctn,
  output_id,
  output_header = NULL)
{
  withCallingHandlers(
    {
      if (!is.null(output_header))
      {
        shinyjs::html(
          id   = output_id,
          html = output_header,
          add  = TRUE
        )
      }
      output <- fnctn
    },
    message = function(m) {
      shinyjs::html(id = output_id, html = m$message, add = TRUE)
    }
  )

  return(output)
}

I am aiming at a scroll state that automatically scrolls to the end of this container whenever something is added. How would that be achievable?

Initializing new BorshCoder instance throws error (JS)

I am trying to decode a Solana transaction using anchor’s BorshCoder. I have a seperate file with the IDL of which the content was copied 1 on 1 from here: https://github.com/raydium-io/raydium-idl/blob/master/raydium_amm/idl.json

When creating a new BorshCoder class like this:

const { BorshCoder } = require('@coral-xyz/anchor');
const IDL = require("./idl.json");

const borshCoder = new BorshCoder(IDL);

This error is thrown

throw new error_js_1.IdlError(`Type not found: ${field.name}`);
IdlError: Type not found: undefined

Is the IDL file incorrect? All IDL files I have tried so far didn’t work one way or the other. So if this is the case could you provide me with a IDL json file that should work?

SSR React : Unexpected token ‘<' in call to renderToString()

I’m working on SSR with react but I’m encountering the following error. Syntax error: Unexpected token

const express = require("express");
const app = express();
const path = require("path");
const mongoose = require("mongoose");

const App =  require('../../../frontend/src/App');
const renderToString  = require('react-dom/server');

  const frontendPath = path.join(__dirname, '../../../frontend/src');
  app.use(express.static(frontendPath));
  
  app.get('*', (req, res) => {
    fs.readFile(path.resolve(frontendPath, 'index.html'), 'utf-8', (err, data) => {
      if (err) {
        console.error('Error reading index.html:', err);
        return res.status(500).send('An error occurred');
      }
  
      const renderedApp = ReactDOMServer.renderToString(<App />);
  
      return res.send(
        data.replace('<div id="root"></div>', `<div id="root">${renderedApp}</div>`)
      );
    });
  });

Is it something related to babel, please help.