React escapes already escaped string

I have an app that uses Express + mongoose as its backend, and React as its frontend. On the backend, the validation of user input is done by express-validator the following way:

body('text')
      .trim()
      .escape()
      .not()
      .isEmpty()
      .withMessage('Comment should contain something, right?'),

The mongoose model schema:

const commentSchema = new Schema<IComment>({
  author: String,
  post: {
    type: SchemaTypes.ObjectId,
    ref: 'Post',
  },
  text: {
    type: String,
  },
  date: Date,
});

The text and author properties are what I have trouble with. I made sure the data comes to the backend unescaped, and from the backend it comes escaped (and only once, by express-validator). However, when I try to render in React a string coming from the backend like that's the (it contains ' character), it’s rendered in the browser as that&#x27;s the. When I inspected the element, I found that the ampersand has been replaced with &amp, and the string ended up being displayed exactly the way it came from the backend. It appears that the ampersand was doubly escaped. Is there a way to prevent this without installing any external libraries and using dangerouslySetInnerHTML? I just don’t want this ampersand to be escaped. My assumption is that it’s done by React.
The component has the following structure:

   <Wrapper>
      <Author>{author}</Author>
      <Text>{text}</Text>
      <Date>{date}</Date>
    </Wrapper>

Same happens if I insert all the values in a plain <div>.


EDIT: If I hardcode something like &lt;html&gt; right into the JSX tag, everything works fine. If I hardcode {"&lt;html&gt;"}, this is treated as a string and is escaped. The data coming from the backend is, well, string, but already escaped.

I can’t set i18n.locale in the javascript part of an inertiajs app

I want to use vue-i18n (version 9.1) in an interiajs app (laravel9 + vue3).
Since I need to do several things when switching languages, I need to outsource setting the i18n locale in the javascript part.
Unfortunately, this does not work:

I have already tried using $i18n.locale or this.$i18n.locale, without success (Error-message: this.$i18n / $i18n is not defined).
I am missing a hint how to set $i18n.locale in the javascript.

Here is my code:
app.js setup of i18n

require('./bootstrap');

import { createApp, h } from 'vue';
import { createI18n } from 'vue-i18n'
import { createInertiaApp } from '@inertiajs/inertia-vue3';
import { InertiaProgress } from '@inertiajs/progress';

const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => require(`./Pages/${name}.vue`),
    setup({ el, app, props, plugin }) {
        const i18n = createI18n({
            locale: "de",
            // locale: props.initialPage.props.locale, // user locale by props
            fallbackLocale: "en", // set fallback locale
            messages: loadLocaleMessages(),
        });

        return createApp({ render: () => h(app, props) })
            .use(plugin)
            .use(i18n)
            .mixin({ methods: { route } })
            .mount(el);
    },
});

Authenticated.vue switch locale

<script setup>
import {ref, onMounted} from 'vue';
import BreezeDropdown from '@/Components/Dropdown.vue';
import BreezeNavLink from '@/Components/NavLink.vue';
import BreezeResponsiveNavLink from '@/Components/ResponsiveNavLink.vue';
import ProjectVersion from '@/Components/ProjectVersion.vue';
import {Link} from '@inertiajs/inertia-vue3';
import { usePage } from '@inertiajs/inertia-vue3';
import { computed } from 'vue';

function switchLanguage(key){
    console.log('switchLanguage to ' + key);
    this.$i18n.locale = key; // not working
}
</script>

<template>
<div v-if="$i18n.locale == 'en'">
  <a @click.prevent="switchLanguage('de')" href="#">
     Deutsch
  </a>
</div>
<div v-if="$i18n.locale == 'de'">
  <a @click.prevent="switchLanguage('en')" href="#">
     English
  </a>
</div>
</template>

I am happy about every hint.

Many UseState() in component – how should be done? [duplicate]

I have component where I have to enter form of about 60 fields. My endpoint requires body of 60 fields to be sent so I have to create 60 variables and send them in a body.

const [wpsNumber,setWpsNumber] = useState('')
  const [revisionNumber,setRevisionNumber] = useState('')
  const [validDate,setValidDate] = useState(new Date())
  const [stand,setStand] = useState([])

........up to all 60...............

Of course creating component like this is not very good option because it will be insane in onChange handlers also. Imagine 60 functions like:

onChangeWpsNumber=(event)=>{
    setWpsNumber(event.target.value)
}

The fields of course are not the same type and also some of the onChange functions will have its own feature that has to be done before setting.

Is there any clever way of doing this? One that pops in my mind is somehow to combine the easy fields that are only like the onChangeWpsNumber with some useReducer and for complex to create separate onChange handler functions.

I also read Using too many useState hooks in react. How do I refactor this? but I am not familiar how exactly reducer will look like in my case.

How to count the number of links whose values do not contain “Input Process case”

The web page I work with contains links with the value “Input Process case”, and without the value “Input Process case”. How do I count the number of links that do not contain the “Input Process case” value

enter image description here

This is code snippet of links with “Input Process case” value

<tr valign="top">
td valign="middle" class="text ibr">
&nbsp;
<a tabindex="0" title="Input Process case TT20220606-0416 - Site is down_MainTT - Jangal_U ,SLA- 1" onkeypress="if(hasKeyCode(event,'KEYCODE_ENTER')) { sendEvent('openassignment','mx145','5');}" class="text pkr" href="javascript:sendEvent('openassignment','mx145','5')">Input Process case TT20220606-0416 - Site is down_MainTT - Jangal_U ,SLA- 1
</a>
</td>
<td class="text ibr">TTINFONEW</td>
<td class="text ibr"></td>
<td class="text ibr">2022-06-06 21:54</td>
<td class="text ri">
<a tabindex="0" title="Route" onkeypress="if(hasKeyCode(event,'KEYCODE_ENTER')) { sendEvent('routeassignment','mx145','5');}" class="text ri" href="javascript:sendEvent('routeassignment','mx145','5')">
<img src="../webclient/skins/tivoli09/images/nav_icon_route.gif" border="0" alt="Route">
</a>
</td>
</tr>

This is code snippet of links WITHOUT “Input Process case” value

<tr valign="top">
<td valign="middle" class="text ibr">
&nbsp;
<a tabindex="0" title="TT20220607-3549 - Site Abis control link broken - Kangurt is down,SLA- 2" onkeypress="if(hasKeyCode(event,'KEYCODE_ENTER')) { sendEvent('openassignment','mx145','4');}" class="text pkr" href="javascript:sendEvent('openassignment','mx145','4')">TT20220607-3549 - Site Abis control link broken - Kangurt is down,SLA- 2</a></td>
<td class="text ibr">TTINFONEW</td>
<td class="text ibr"></td>
<td class="text ibr">2022-06-07 15:56</td>
<td class="text ri">
<a tabindex="0" title="Route" onkeypress="if(hasKeyCode(event,'KEYCODE_ENTER')) { sendEvent('routeassignment','mx145','4');}" class="text ri" href="javascript:sendEvent('routeassignment','mx145','4')">
<img src="../webclient/skins/tivoli09/images/nav_icon_route.gif" border="0" alt="Route">
</a>
</td>
</tr>

JQuery won’t set right value onclick of button

So what I’m trying to achieve is to set the value of a hidden input so that I can send that value to a PHP file where this value will be used to execute a delete query.

The only problem that I’m facing is that it will only select the data-id from the first element, which is not what I want.

Here is the JQuery code, if any other files are required for more info I’ll post those aswell.

$('document').ready(function(){
    // Makes menu visibility toggable
    $('#hamburger_btn').on("click", function() {
        $('#sidemenu').toggleClass("show");
    })

    // Closes menu via separate button
    $('#close_btn').on("click", function() {
        $('#sidemenu').removeClass("show");
    })

    // Opens dialogbox
    $('.openDialog').on("click", function() {
        $('#dialog').addClass("showBox");
        $('#overlay').addClass("showOv");

        // Sets the input value in dialog
        $('#post_id').val($('.openDialog').data("id")); // Here lies the problem
    })

    // Closes dialogbox
    $('#closeDialog').on("click", function() {
        $('#dialog').removeClass("showBox");
        $('#overlay').removeClass("showOv");

        // Sets value to empty and remove attribute value
        $('#post_id').val('').removeAttr("value");
    })
});

If this question has already been answered elsewhere please let me know aswell, because I couldnt find it.

Why am I getting null in the console in JavaScript? [duplicate]

I want the div to be output in the console but I am getting ‘null’ in the console.
This is my 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">
    <script src="two_js.js"></script>
    <title>:)</title>
</head>
<body>
    <div id="main" class="container">
        This is my HTML Body.
    </div>
</body>
</html>

This is my JavaScript ->

let main = document.getElementById('main');
console.log(main);

What should I do?

Given a list of transfers between two banks, determine the minimum initial account balance of each bank required for the given transfers to be carried

I had a problem that I tried to solve. Some of the test cases were successful, while others were not.

Requirements:

You are given a list of N transfers (numbered from 0 to N−1) between two banks: bank A and bank B. The K-th transfer is described by two values:

  • R[K] (either “A” or “B”) representing the recipient (the bank the transfer is sent to);
  • V[K] denoting the value sent via the transfer.

All transfers are completed in the order they appear on the list. The banks do not want to go into debt (in other words, their account balance may
not drop below 0). What minimum initial account balance in each bank is necessary in order to complete the transfers?

Write a function:

function solution(R, V);

that, given a string R and an array of integers V, both of length N, returns an array of two integers. The integers should represent the minimum initial account balances for banks A and B in the following order: [bank A, bank B].

The result array should be returned as an array of integers.

Write an efficient algorithm for the following assumptions:

  • string R and array V are both of length N;
  • N is an integer within the range [1..100,000];
  • each element of array V is an integer within the range [1..10,000];
  • string R consists only of the characters “A” and/or “B”.

I passed the following test cases:

  • Given R = “BAABA” and V = [2, 4, 1, 1, 2], the function should return [2, 4].
  • Given R = “ABAB” and V = [10, 5, 10, 15], the function should return [0, 15].
  • Given R = “B” and V = [100], the function should return [100, 0].

I failed the following test cases:

failed testcase

Could you please advise me on how to replicate those test cases?

My test has been completed, but I am eager to learn how to replicate those results. it’s not homework

Thanks in Advance.

function solution(R, V) {
  let min_A = 0;
  let min_B = 0;
  let balance = 0;
  let arr = [];
  let final = [];

  R = R.split('');
  for (var i = 0; i < R.length; i++) {
    arr.push({
      receiver: R[i],
      amount: V[i],
    });
  }
  arr.map((k) => {
    if (k.receiver == 'A') {
      balance += k.amount;
      min_B = Math.min(-balance, min_B);
    } else {
      balance -= k.amount;
      min_A = Math.min(balance, min_A);
    }
  });
  final.push(Math.abs(min_A), Math.abs(min_B));
  console.log(final);
  console.log(min_A, min_B);
}
solution('ABBA', [1, 1, 1, 1]);

How do I export data from jQuery Datatable to excel with merged cells

I want to export a table like this,

as-is

But, It’s exported like this.

enter image description here

This is the table to export.

<div class="box-body">
<table class="table" id="excelTable" style="width: 100%">
    <tr>
        <th rowspan="2" style="width: 20%;">left</th>
        <th colspan="2" style="width: 45%;">right</th>
    </tr>
    <tr>
        <th>a</th>
        <th>b</th>
    </tr>
</table>

I want to make the export part using jQuery DataTable dom.

$(document).ready(function() {
$('#example').DataTable( {
    dom: 'Blfrtip',
    buttons: [{
        extend     : 'excel'
       ,filename   : 'filename'
       ,title      : ''
       ,text       : 'export excel'
       ,className  : 'btn'
 }]
} );  } );

Please tell me how to change the code above.

Thanks.

Can i setState of a react functional component from a external gloabal function present inside script tag?

I have an android app which calls the a function present inside the head of my react
page. All i want is to allow the the function to set a state inside the react component

<head>
  <script>
    webViewAndriodInteraction(parm1)
    {
      //Here i want this function to change the state of my react functional component
      //setSomeState("new data")
    }
  </script>
</head>;

function LiveScreen(props) {
  const [somedata, setSomeState] = useState();
  return <h1>someData</h1>;
}

Can’t mock service in NestJS

I want to create unit test for NextJS service. I have next service

import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { GiftOrder, GiftOrderDocument } from '@gift-orders/schemas/gift-order.schema';
import { ExperimentService } from '@providers/experiment/experiment.service';
import { PaymentService } from '@providers/payment.service';

@Injectable()
export class GiftOrdersService {
  private readonly logger: Logger;
  constructor(
    @InjectModel(GiftOrder.name)
    private readonly giftOrderModel: Model<GiftOrderDocument>,
    private readonly experimentService: ExperimentService,
    private readonly paymentService: PaymentService,
  ) {

  async handleOrderProcessed(
    giftId: string,
    productId: string,
    orderId: string,
    productPriceInUsd: number,
    taxInUsd: number,
  ): Promise<void> {
    console.log(12345);
    return [];
  }
}

I want to cover this service with unit test. I try to mock all dependencies

import { ModuleMocker, MockFunctionMetadata } from 'jest-mock';
import { Test } from '@nestjs/testing';
import { GiftOrdersService } from '@gift-orders/gift-orders.service';
import { getModelToken } from '@nestjs/mongoose';

const moduleMocker = new ModuleMocker(global);

describe('GiftsController', () => {
  let spyGiftOrdersService: GiftOrdersService;
  const [giftId, productId, orderId, productPriceInUsd, taxInUsd] = [
    'giftId',
    'productId',
    'orderId',
    10,
    5,
  ];

  beforeEach(async () => {
    const moduleRef = await Test.createTestingModule({
      providers: [GiftOrdersService],
    })
      .useMocker((token) => {
        if (typeof token === 'function') {
          const mockMetadata = moduleMocker.getMetadata(
            token,
          ) as MockFunctionMetadata<any, any>;
          const Mock = moduleMocker.generateFromMetadata(mockMetadata);
          return new Mock();
        }
        return jest.fn();
      })
      .compile();

    const spyGiftOrdersService =
      moduleRef.get<GiftOrdersService>(GiftOrdersService);
  });

  it('test', async () => {
    await spyGiftOrdersService.handleOrderProcessed(
      giftId,
      productId,
      orderId,
      productPriceInUsd,
      taxInUsd,
    );
  });
});

This code throw the error

TypeError: Cannot read properties of undefined (reading 'handleOrderProcessed')

Why the code above doesn’t working? Advice me please how I can test method handleOrderProcessed. I’ll very appreciate you for this. I really don’t understand why I can’t call handleOrderProcessed method from class GiftOrdersService