How to fix Next js 13 The resource was preloaded using link preload but not used within a few seconds from the window’s load event. error

In my next JS 13 app i’m fetching items from my server and displaying them as a list. and whenever one list selected it navigates to a detail page with dynamic route. but whenever i navigate, my console throws a warning.

The resource <URL> was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate `as` value and it is preloaded intentionally.

even if i switched a tab and return back this warning keeps thrown double the amount. and i think this is overloading my server with request. how i’m redirecting is as follows

{house.images.map((img, index) => {
          return (
            <Link
              prefetch={false}
              href={{
                pathname: `/living/${house.id}`,
              }}
              key={index}
            >
              <div
                key={index}
                className=" w-full relative -z-10 pt-[100%] cursor-pointer"
              >
                <Image
                  src={img}
                  alt="profile"
                  fill
                  className="w-full h-full top-0 left-0 -z-10 object-cover rounded-2xl ease-in-out duration-200"
                />
              </div>
            </Link>
          );
        })}

so if this warning keeps popping does that mean it calls the server the amount of the warning? and how can i fix this error?

REACT NATIVE – Passing Values Between Screens

I’m trying to pass values between two screens. Basically, the user interface of my app displays a bottom menu with 3 screens using import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs'; import { NavigationContainer } from '@react-navigation/native';

One of these screens is called ‘Patients’ and displays a top menu with 2 screens using the same import as above.
One of the screens of the top menu is called ‘OrderCategory’.

The second screen of the bottom menu (the main menu we can say) is called ‘Inventory’ and displays category/sub-categories and lists of items available to order from the inventory.

I’m trying to allow the user to choose a quantity of any item and pass the value to ‘OrderCategory’. But as the ‘Inventory’ screen and the ‘OrderCategory’ screen are not part of the same menu

I tried to use navigation.jumpTo(”, {}); but as the ‘Inventory’ screen and the ‘OrderCategory’ screen are not part of the same menu it’s not working

I was thinking about passing the value to the screen ‘Patients’ first as it is part of the same main menu as ‘Inventory’ and use a trigger to pass the value to the ‘OrderCategory’ from ‘Patients’

Comannd not executing in discord.js V14

Im making command what will insert different values based on your roles in discord server. But my command is not executing, any others yes. If I type that command to chat it’ll reply appliaction not answering and wont type anything to console.

My command file: (uplatnitrole.js)

//Importovani discord.js balicku do kodu
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');

var db = require('../nastaveni/db.js');

module.exports = {
    name: 'uplatnitrole',
    description: "Přidá role které máš na discordu na web!",
    data: new SlashCommandBuilder()
        .setName('uplatnitrole')
        .setDescription('Přidá role které máš na discordu na web!'),

    //Spusteni scriptu pri interakci
    async execute(interaction) {
        console.log("tvojemam")
        const config = require('./../nastaveni/nastaveni.json');
        const policerole = config.POLICIE_ROLE_ID
        const admin = config.ATEAM_ROLE_ID
        const hzsrole = config.HZS_ROLE_ID
        const zzs = config.ZZS_ROLE_ID
        const dispecink = config.DISPECINK_ROLE_ID
        var webid
        var policajt
        var hzst
        var zzst
        var admint
        var dispect
        db.query("SELECT * FROM users WHERE discordid = " + interaction.user.id, function (err, result) {
            if (err) {
                console.log(err)
                interaction.reply({content: "Byl problém s databází", ephemeral: true})
                return
            }
            if (result[0] == undefined) {
                interaction.reply({content: "Nemáte účet na webu přiřazený k vašemu discordu. Zaregistrujte se na našem webu. URL najdete v informacích", ephemeral: true})
                return
            }
            webid = result[0].id
        })
        console.log(webid)
        if (interaction.member.roles.cache.some(role => role.id === policerole)) {
            db.query("INSERT INTO user" + webid + " (path, name, data1) VALUES ('user-profile', 'group', 'pcr')", function (err, result) {
                if (err) {
                    console.log(err)
                    interaction.reply({content: "Byl problém s databází", ephemeral: true})
                    return
                }
            })
            policajt = "PČR,"
        }

        if (interaction.member.roles.cache.some(role => role.id === hzsrole)) {
            db.query("INSERT INTO user" + webid + " (path, name, data1) VALUES ('user-profile', 'group', 'hzs')", function (err, result) {
                if (err) {
                    console.log(err)
                    interaction.reply({content: "Byl problém s databází", ephemeral: true})
                    return
                }
            })
            hzst = "HZS,"
        }

        if (interaction.member.roles.cache.some(role => role.id === zzs)) {
            db.query("INSERT INTO user" + webid + " (path, name, data1) VALUES ('user-profile', 'group', 'zzs')", function (err, result) {
                if (err) {
                    console.log(err)
                    interaction.reply({content: "Byl problém s databází", ephemeral: true})
                    return
                }
            })
            zzst = "ZZS,"
        }

        if (interaction.member.roles.cache.some(role => role.id === admin)) {
            db.query("INSERT INTO user" + webid + " (path, name, data1) VALUES ('user-profile', 'group', 'admin')", function (err, result) {
                if (err) {
                    console.log(err)
                    interaction.reply({content: "Byl problém s databází", ephemeral: true})
                    return
                }
            })
            admint = "Admin,"
        }

        if (interaction.member.roles.cache.some(role => role.id === dispecink)) {
            db.query("INSERT INTO user" + webid + " (path, name, data1) VALUES ('user-profile', 'group', 'dispecink')", function (err, result) {
                if (err) {
                    interaction.reply({content: "Byl problém s databází", ephemeral: true})
                    return
                }
            })
            dispect = "Dispečink"
        }

        interaction.reply({content: "Úspěšně jsme vám na webu přidali permise pro tyto role: " + policajt + " "+ hzst + " "+ zzst + " "+ admint + " "+ dispect + ". n**PRO TO ABY SE VÁM ROLE PŘIDALI SE NA WEBU PŘIHLAŠTE A ODHLAŠTE**n**PRO TO ABY SE VÁM ROLE PŘIDALI SE NA WEBU PŘIHLAŠTE A ODHLAŠTE**n**PRO TO ABY SE VÁM ROLE PŘIDALI SE NA WEBU PŘIHLAŠTE A ODHLAŠTE**n**PRO TO ABY SE VÁM ROLE PŘIDALI SE NA WEBU PŘIHLAŠTE A ODHLAŠTE**n**PRO TO ABY SE VÁM ROLE PŘIDALI SE NA WEBU PŘIHLAŠTE A ODHLAŠTE**", ephemeral: true})
    }
}

Piece that executing interaction of mine main file (index.js):

//----------COMANNDY---------

//Hledání cesty
for (const file of commandFiles) {
    const filePath = path.join(commandsPath, file);
    const command = require(filePath);
    client.commands.set(command.data.name, command);
}

//Spuštění comanndu
client.on(Events.InteractionCreate, async interaction => {
    const command = client.commands.get(interaction.commandName);

    if (!command) return;

    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        await interaction.reply({ content: 'Byl tu error při dělání commandu!', ephemeral: true });
    }
});

Сypress ignores the index of the letter in the string

I have a test:

describe('string component works correctly', () => {
  ...
  it('reverses the string correctly', () => {
    cy.visit('http://localhost:3000/recursion');

    const inputString = 'Hello';
    const reversedString = 'olleH';

    cy.get('input')
      .type(inputString)
      .should('have.value', inputString);

    cy.contains('button', 'wrap').click();

    cy.wait(1000)

    cy.get('.circles').each((circle, index) => {
      const indexStr = reversedString[index]
      cy.wrap(circle).should('have.text', indexStr)
    })
  });
})

I am interested in this test:

cy.get('.circles').each((circle, index) => {
      const indexStr = reversedString[index]
      cy.wrap(circle).should('have.text', indexStr)
    })

I get that error:

assertexpected <div.circles.string_circles__AE6EW> to have text o, but the text was olleH
AssertionError
Timed out retrying after 4000ms: expected '<div.circles.string_circles__AE6EW>' to have text 'o', but the text was 'olleH'
cypress/e2e/stringTest.cy.js:27:23
  25 |     cy.get('.circles').each((circle, index) => {
  26 |       const indexStr = reversedString[index]
> 27 |       cy.wrap(circle).should('have.text', indexStr)
     |                       ^
  28 |     })
  29 |   });
  30 | })

it as if doesnt see [index] after reversedString

initially I had the code: cy.wrap(circle).should(‘have.text’, reversedString[index]), then i try to use const, but it didn’t work

How to create a Stripe payment link on client side without exposing secret key

I am trying to make a simple website to sell various products that does not rely at all on a backend server. The goal is to make the end website completely static, meaning it is able to be served by something like GitHub pages. I am trying to use Stripe payment links for users to checkout. The following process is what I am trying to do –

  1. user navigates the website adding various products to a cart (cart info is stored in browser local storage)
  2. user clicks the checkout button which makes a post request to https://api.stripe.com/v1/payment_links to create a new Stripe payment link with the correct body corresponding to the items in the user’s cart
  3. response comes from back from Stripe with the new payment link, redirect the user here to checkout with Stripe

The problem I am facing is that in order to make this request a secret key has to be used. So in the client side code I could have the following –

fetch("https://api.stripe.com/v1/payment_links", {
    method: "POST", 
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer {{STRIPE_SECRET_KEY}}',
    },
    body: makeBody(),
})

This is not good because it reveals to anyone using the website the Stripe secret key. Is there anyway to get this functionality I am looking for without having to run a server and without revealing any secret API keys?

One approach that I tried is to use a restricted API key (https://stripe.com/docs/keys#limit-access), which only has write access to payment links. Unfortunately, anyone with this key could also do something malicious like deactivate all payment links as soon as they are created.

How would I set a input to have a different form state than what the UI displays

I have a standard text input in my code base

I have a use case where I need to call the change function in react final form and set a value, but I need the text value to read something else.

For example

const NameInput = () => {
  return (
    <div>
      <label htmlFor="name">Name:</label>
      <Field name="name" component="input" type="text" placeholder="Enter your name" />
    </div>
  );
};


const MyForm = () => {
  const onSubmit = (values) => {
    console.log(values);
  };

  return (
    <Form
      onSubmit={onSubmit}
      render={({ handleSubmit }) => (
        <form onSubmit={handleSubmit}>
          <NameInput />
          {/* Include other form fields */}
          <button type="submit">Submit</button>
        </form>
      )}
    />
  );
};

Then in a separate hook I call the change function
change(‘name’, ‘Jack’)

This sets the form state to Jack, and the text box now reads Jack. However when the form state is Jack, I wan’t to show something else in the text box.

How to sort movies according to their year of release in JavaScript

I’ve created a sort function to sort movies, but when I click NEW TO OLD or vice versa, the list of movies disappear. How do I fix this problem.

const moviesWrapperEl = document.querySelector(`.movies__bottom`);
const searchResultsEl = document.querySelector(`.search__results`);
const headerEl = document.querySelector(`#header`);
let movies = [];

function showMovies() {
  document.querySelector(`.movies__container`).style.display = "flex";
  headerEl.classList.remove(`header__padding`);
}

function moviesHTML(movie) {
  return `<div class="movie__wrapper">
      <figure class="movie__img--wrapper">
        <img src="${movie.Poster}" alt="" class="movie__img" />
      </figure>
      <div class="movie__information">
        <h2 class="movie__title">${movie.Title}</h2>
        <h2 class="movie__year">${movie.Year}</h2>
      </div>
    </div>`;
}

function onSearchChange(event) {
  const search = event.target.value;
  searchResultsEl.innerHTML = search;
  event.preventDefault();
  renderMovies(search);
}

async function renderMovies(search) {
  let movies = await fetch(
    `https://www.omdbapi.com/?i=tt3896198&apikey=12345678&s=${search}`
  );
  let moviesResult = await movies.json();
  movies = moviesResult.Search;
  console.log(movies);
  moviesWrapperEl.innerHTML = moviesResult.Search.map((movie) =>
    moviesHTML(movie)
  ).join("");
}

async function sortMovies(event) {
  const filterOption = event.target.value;
  if (filterOption === "new") {
    movies.sort((a, b) => parseInt(b.Year) - parseInt(a.Year));
  } else if (filterOption === "old") {
    movies.sort((a, b) => parseInt(a.Year) - parseInt(b.Year));
  }
  moviesWrapperEl.innerHTML = movies.map((movie) => moviesHTML(movie)).join("");
}

I tried make a function to sort it, but it just makes the movies disappear. I think the problem is that my let movies = [] variable is being processed before I reassign the movies variable in the async function. But I don’t know how to solve it.

Architecural Design of Elastic Search Javascript Client

I’m looking for any Architecural Design of javascript client for elastic search implementation with error handling.

I’m trying to migrate bulk data from graph database to elastic so i can ingest data using bulk api divided into chunks and chunks are streamed to elastic.

I have tried creating a elastic client and a proxy class basically implementing wrapper functionality of the cilent functions on top of client.

Elastic Client is also implemented with singleton desing pattern.

aws cognito check if user email exists in UserPool

What I’m trying to do ?

Run on all users and check if the email exists in the cognito user pool

What actually happens ?

I get the following error:

Custom auth lambda trigger is not configured for the user pool.

on Edit app client information,
I added the following permissions:

enter image description here

my question:

Is it necessary to configure lamda in AWS in order to receive all users?

Javascript Phaser: cut polygon using mouse to draw a line through the shape

enter image description hereI am trying to cut my polygon into 2 pieces. I have created the shape and the line draws using the mouse, however I cannot work out how to cut the shape into 2 once the line has been drawn through it. I want it to only cut the polygon when the line intersects both sides.
Any help would be gretly appreciated!

This is why I have so far:

let level6;
window.onload = function() {
    let gameConfig = {
        type: Phaser.AUTO,
        scale: {
            mode: Phaser.Scale.FIT,
            autoCenter: Phaser.Scale.CENTER_BOTH,
            parent: "thegame",
            width: 600,
            height: 700
        },
        scene: scene6,
        physics: {
            default: "matter",
            matter: {
                gravity: {
                    y: 0
                },
                debug: true,
            }
        }
    }
    level6 = new Phaser.Game(gameConfig);
    window.focus();
}

var polygon
class scene6 extends Phaser.Scene{
    constructor(){
        super("PlayGame");
    }

    
    create(){

        this.matter.world.update30Hz();
        this.matter.world.setBounds(10, 10, level6.config.width - 20, level6.config.height - 20);

        
        



        const polygon = this.add.polygon(200, 200, [720,20, 600,-20, 400,20, 250,-20, 110,20, 110,80, 250,40, 400,80 ,600,40 ,720,80], 0xff0000).setInteractive();
        this.lineGraphics = this.add.graphics();
        this.input.on("pointerdown", this.startDrawing, this);
        this.input.on("pointerup", this.stopDrawing, this);
        this.input.on("pointermove", this.keepDrawing, this);
        this.isDrawing = false;
        }

   
   startDrawing(){
        this.isDrawing = true;
    }
    keepDrawing(pointer){
        if(this.isDrawing){
            this.lineGraphics.clear();
            this.lineGraphics.lineStyle(1, 0xff0000);
            this.lineGraphics.moveTo(pointer.downX, pointer.downY);
            this.lineGraphics.lineTo(pointer.x, pointer.y);
            this.lineGraphics.strokePath();
        }
    }
    stopDrawing(pointer){
        this.lineGraphics.clear();
        this.isDrawing = false;
        let bodies = this.matter.world.localWorld.bodies;
        let toBeSliced = [];
        let toBeCreated = [];
        for(let i = 0; i < bodies.length; i++){
            let vertices = bodies[i].parts[0].vertices;
            let pointsArray = [];
            vertices.forEach(function(vertex){
                pointsArray.push(vertex.x, vertex.y)
            });
            let slicedPolygons = PolyK.Slice(pointsArray, pointer.downX, pointer.downY, pointer.upX, pointer.upY);
            if(slicedPolygons.length > 1){
                toBeSliced.push(bodies[i]);
                slicedPolygons.forEach(function(points){
                    toBeCreated.push(points)

                })

            }
        }
        toBeSliced.forEach(function(body){
            this.matter.world.remove(body)
        }.bind(this))
        toBeCreated.forEach(function(points){
            let polyObject = [];
            for(let i = 0; i < points.length / 2; i ++){
                polyObject.push({
                    x: points[i * 2],
                    y: points[i * 2 + 1]
                })
            }
            let sliceCentre = Phaser.Physics.Matter.Matter.Vertices.centre(polyObject)
            let slicedBody = this.matter.add.fromVertices(sliceCentre.x, sliceCentre.y, polyObject, {
                isStatic: false
            });
            this.add.text(13, 11, 'Level 6 Complete!',{fontFamily: 'Georgia, "Goudy Bookletter 1911", Times, serif'});
    
        }.bind(this))
    }
    

};



[enter image description here](https://i.stack.imgur.com/jsHnt.png)

Error – Cannot read properties of undefined (reading ‘get’)

when I run my program, I get the following error:

Cannot read properties of undefined (reading 'get')
TypeError: Cannot read properties of undefined (reading 'get')
    at Proxy.mounted (webpack-internal:///./node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./src/views/HdHistory.vue?vue&type=script&lang=js:563:29)
    at eval (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:2811:88)
    at callWithErrorHandling (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:296:18)
    at callWithAsyncErrorHandling (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:304:17)
    at hook.__weh.hook.__weh (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:2791:19)
    at flushPostFlushCbs (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:461:41)
    at flushJobs (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:499:5)

This is my code :

 mounted() {
    Promise.all([
      this.$http.get('/api/v0/tickets/divisions')
        .then((response) => {
          this.customer.items = response.data;
        }),
      this.$http.get('/api/v0/hd/groups')
        .then((response) => {
          this.groups.items.push(...response.data);
          // by default select all
          if (this.groups.selected.length === 0) this.groups.selected = this.groups.items
        }),
    ])
      .then(() => {
        this.timeScaleSelected();
      })
      .catch((e) => {
        console.error(e);
      });
  },

does anyone have any ideas?

I am trying to upgrade my program from vue2 to vue3.

window.event value is same as function param “e”

Can anyone explain the reason for this? Given that window.event is not defined anywhere and after this callback if you check window.event, it comes as undefined.
I have checked this on Chrome, Safari and Firefox, the behavior is the same.
This is also applicable for onmessage.

document.addEventListener("click", function(e) {
        console.log("event clicked: ", e); // PointerEvent
        console.log(window.event); // PointerEvent
    })

NOTE: Once you set window.event , then it doesn’t behave like this.

Reason for this behaviour of the browsers

Implement Star Rating for every element inside a html table, which is generated by User Inputs

I am trying to build a Website, which is able to dynamically store arbitrary events from user inputs on the website in a html table. Every event stored can be rated by a star rating system which i already implemented with html, js & css.

The problem is, my current system only allows to rate one of the elements. If I have two elements in my list and I try to rate the second one, it changes the value of the first element and doesn’t allow me to change the value of the second one.

How can i fix this?

Here is my Code (Some Alerts/Comments are in German but just dont mind these really)

HTML:

<!DOCTYPE html>

<head>
    <meta charset="utf-8" />
    <title>Eventüberblick</title>
    <link href="style.css" rel="stylesheet" type="text/css">

    <!-- Bootstrap 4 CDN -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src="Script1.js"></script>

    <!-- Fontawesome CDN Link -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" />
</head>

<header>
    <a href="index.html">Überblick</a>
    <a href="CreateEvent.html">Event erstellen</a>
</header>

<body>
    <h1 class="headline" style="text-align: center;">Neues Event</h1>
    

    <div class="container">

        <div class="form-div">
            <div class="row">
                <div class="col-md-3">
                    <input type = "text" class="form-control" id="eventname" placeholder="Eventname">
                </div>
                <div class="col-md-3">
                    <input type = "datetime" class="form-control" id="eventdate" placeholder="Eventdatum">
                </div>
                <div class="col-md-3">
                    <input type = "text" class="form-control" id="eventloc" placeholder="Eventort">
                </div>
                <div class="col-md-3">
                    <input type = "text" class="form-control" id="eventauthor" placeholder="Eventautor">
                </div>
                <div class="col-md-3">
                    <input type = "text" class="form-control" id="eventdesc" placeholder="Eventbeschreibung">
                </div>
                <div class="col-md-3" style="text-align: right;">
                    <button class="btn btn-primary" id="addData">Hinzufügen</button>
                </div>
            </div>
        </div>

        <h2 class="headline" style="text-align: center;">Eventliste</h2>
        <div class="container">
            <table class="table">
                <thead>
                    <tr>
                        <th>All<input type="checkbox" id="select-all"></th>
                        <th>Eventname</th>
                        <th>Eventdatum</th>
                        <th>Eventort</th>
                        <th>Eventbeschreibung</th>
                        <th>Eventautor</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><input type="checkbox" id="select-row"></td>
                        <td>Phase 1</td>
                        <td>08.06.2023</td>
                        <td>Uni Passau</td>
                        <td>Abschluss Phase 1 </td>
                        <td>Gruppe 3</td>
                        <td><button class="btn btn-link like-button">Gefällt mir</button></td>
                        <td></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    
   <script></script> 

</body>

Javascript:

$(document).ready(function () {
    function addData() {
        var eventname = $("#eventname").val();
        var eventdate = $("#eventdate").val();
        var eventloc = $("#eventloc").val();
        var eventauthor = $("#eventauthor").val();
        var eventdesc = $("#eventdesc").val();

        if (eventname.trim() === '' || eventdate.trim() === '' || eventloc.trim() === '' || eventauthor.trim() === '' || eventdesc.trim() === '') {
            alert("Bitte f�llen Sie alle Felder aus");
            return;
        }

        if (!isValidDate(eventdate)) {
            alert("Datum muss folgendem Format entsprechen: dd.mm.yyyy ein");
            return;
        }

        // Validierung und Hinzuf�gen zur Tabelle

        $(".table tbody tr").last().after(
            '<tr>' +
            '<td><input type="checkbox" id="select-row"></td>' +
            '<td>' + eventname + '</td>' +
            '<td>' + eventdate + '</td>' +
            '<td>' + eventloc + '</td>' +
            '<td>' + eventdesc + '</td>' +
            '<td>' + eventauthor + '</td>' +
            '<td><button class="btn btn-link like-button">Gefällt mir</button></td>' +
            '<td><div class="rate"><input type="radio" id="star5" name="rate" value="5" /><label for="star5" title="text">5 stars</label><input type="radio" id="star4" name="rate" value="4" /><label for="star4" title="text">4 stars</label><input type="radio" id="star3" name="rate" value="3" /><label for="star3" title="text">3 stars</label><input type="radio" id="star2" name="rate" value="2" /><label for="star2" title="text">2 stars</label><input type="radio" id="star1" name="rate" value="1" /><label for="star1" title="text">1 star</label></div></td>'
            + '</tr>'
        );

        function isValidDate(dateString) {
            var regex = /^d{2}.d{2}.d{4}$/;
            return regex.test(dateString);
        }

    }

    // Eventlistener f�r den Button
    $('#addData').click(addData);

    $('.table').on('click', '.like-button', function () {
        $(this).toggleClass('liked');
        if ($(this).hasClass('liked')) {
            $(this).text('Gefällt mir nichtmehr');
            $(this).closest('tr').addClass('liked-event');
        } else {
            $(this).text('Gefällt mir');
            $(this).closest('tr').removeClass('liked-event');
        }
    });
});

Code for Star Rating in CSS:

*{
    margin: 0;
    padding: 0;
}
.rate {
    float: left;
    height: 46px;
    padding: 0 10px;
}
.rate:not(:checked) > input {
    position:absolute;
    top:-9999px;
}
.rate:not(:checked) > label {
    float:right;
    width:1em;
    overflow:hidden;
    white-space:nowrap;
    cursor:pointer;
    font-size:30px;
    color:#ccc;
}
.rate:not(:checked) > label:before {
    content: '★ ';
}
.rate > input:checked ~ label {
    color: #ffc700;    
}
.rate:not(:checked) > label:hover,
.rate:not(:checked) > label:hover ~ label {
    color: #deb217;  
}
.rate > input:checked + label:hover,
.rate > input:checked + label:hover ~ label,
.rate > input:checked ~ label:hover,
.rate > input:checked ~ label:hover ~ label,
.rate > label:hover ~ input:checked ~ label {
    color: #c59b08;
}

Function to list digits from long singly-linked list, [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1] return 100000000000000000, instead of 100000000000000001

I created two functions. “turnArray” is a function to turn array into singly linked list. And another function, “getDigit” to turn singly linked list into a reversed digit. Here are my code:

let turnArray = function (arr) {
  var head = {val: -1, next: null};
  var pointer = head;
    
  for (var i = 0; i < arr.length; i++) {
    var curr = {val : arr[i], next: null};
    pointer.next = curr;
    pointer = pointer.next;
  }
    
  return head.next;
}

let getDigit = function (head) {
        var currentNode = head;
        var digit = 0;
        var time = 1;

        while (currentNode.next != null) {
            digit += currentNode.val*time;
            currentNode = currentNode.next;
            time *= 10;
        }
        digit = digit + currentNode.val * time;
        return digit;
}

I have passed most of the test. However, when array’s length is higher than 18, the digit that i got back from the function was getting weird.

when i log:
console.log(getDigit(turnArray([5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2])))

my output is 20000000000000004
my expected output is 20000000000000005

when i log:
console.log(getDigit(turnArray([9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2])))

my output is 20000000000000010
my expected output is 20000000000000009

— But it works just find in smaller array — :

console.log(getDigit(turnArray([5,6,4])))
my output is 456 // OK

console.log(getDigit(turnArray([9,0,0,0,0,0,0,0,0,0,0,2])))
my output is 200000000009 // OK

I couldn’t find a way to debug this.

Anyone knows what’s happening?, I really appreciate all you help.

How to navigate to the same URL adding and parameter using react-router-dom

In my React application, a Route in the nav menu points to /persons url. When clicked, the rendered page shows all the available persons, let’s say in a table. The user can then select a particular person to see the detail at the url /persons/:personId. However, when there is only one user available, the requirement is to directly show the person detail, and bypass the step to show table of persons.

In the React Component, I am trying to identify if there is only one person available in the useEffect() and using react-router-dom’s navigate(useLocation().pathname + “/” + personId).

Here is the relevant code snippets.

...
<Route path="/persons/:personId?" element={<Persons />} />
...
const { personId } = useParams();
const persons = // via some service call;
useEffect(() => {
    if (!personId && persons.length === 1) {
      useNavigate()(useLocation().pathname + "/" + thisClaimId);
    }
}, []);
...

With this I receive => ‘Too many re-renders. React limits the number of renders to prevent an infinite loop.’

Here are my questions

  • How to navigate to the same page having added a parameter from within the page?
  • What is the best practice around this use-case? Should I render another component for /persons/:personId?