D3js TypeScript Not sure what the correct types for linkHorizontal() should be?

I am using the following Tidy Tree example from Observable but adding TypeScript.

I am using the following interface for the generic type Datum but I am having trouble with getting passed the following error.

Type 'any[]' is missing the following properties from type 'HierarchyPointNode<NodeData>': x, y, links, data, and 13 more.ts(2740)
index.d.ts(1885, 20): The expected type comes from the return type of this signature.
Property 'source' does not exist on type 'HierarchyNode<NodeData>'.ts(2339)
interface NodeData {
  name: string;
  children?: NodeData[];
}

Type error occurs here.

    const link = svg
      .append("g")
      .attr("fill", "none")
      .attr("stroke", "#555")
      .attr("stroke-opacity", 0.4)
      .attr("stroke-width", 1.5)
      .selectAll()
      .data(root.links())
      .join("path")
      // TypeError occurs in this line
      .attr("d", (d) => { 
        const linkGenerator = d3
          // .linkHorizontal()
          .linkHorizontal()
          .source((d) => [d.source.y, d.source.x])
          .target((d) => [d.target.y, d.target.x]);
        return linkGenerator(d);
      });

What should be the correct type annotation here?

Thanks

I’ve tried .linkHorizontal<d3.HierarchyLink, d3.HierarchyPointNode … but that doesn’t seem to work.

How to wait for Promise in a non-async function? (node-mssql) [duplicate]

I need to migrate to a MS SQL database and I’m using the node-mssql library.

Problem: the mssql library returns Promises and they don’t block the execution of my code.

But my code expects the code to block and I cannot effort refactoring the whole project so I’m looking for a solution to wait for a Promise until it’s done and to return its result.

All answers I found do not solve the problem.

When my code queries the database then it must return a result, not a Promise object that is resolved somewhen later. My code needs to block and wait for the Promise to finish (succeed or fail) and continue with its result.

I see that many others do have the same requirement. Why is it so hard to implement an await-like statement in a non-async function? These fancy Promise bullsh*t callbacks are driving you crazy.

An acceptable alternative is to switch to another MS SQL library that acts “like normal”.

Here’s an example:

// Emulate the node-mssql connect method
// Similar to: const sql = require('mssql')
const sql = {
  connect: (config) => new Promise(resolve => {
    setTimeout(() => resolve({query: (sql) => sql}), 2000)
  })
}

// Existing project structure
class Foo {
  db; // database connection
  
  constructor() {
    this.db_connect();
  }
  
  db_connect() {
    this.db = sql.connect(); // Promise, not connection object
    // must not return until done!
  }
  
  db_query(sql) {
    return this.db.query(sql); // Promise, not result object
    // must not return until done!
  }
}

const foo = new Foo();
console.log(foo.db_query(`SELECT * FROM bar WHERE spam='eggs'`));

// Uncaught TypeError: this.db.query is not a function

The program ‘app.js’ has exited with code 4294967295 (0xffffffff)

I’m trying to create my first hello.js app in Visual Studio 22. In started from a blank nodejs console app, and when I run the app I get the following message:

The program ‘app.js’ has exited with code 4294967295 (0xffffffff).

I’m not understanding if that is an issue or not, since the app prints Hello World as I expect.

Looking around in the web i’ve found only references about docker containers. Thanks in advance

How can I catch children added to a web component before first render?

I’m attempting to create a web component that modifies the behavior and style of its child elements. However, I’d like to do this modification before the first render, so that no flickering occurs.

Below is a (hopefully) small example of a web component that this is intended to create content (identified by the content class) that is hidden when the user clicks the header (identified by the trigger class).

shirinkable-content.js:

"use strict";

customElements.define(
  "shrinkable-content",
  class extends HTMLElement {
    static observedAttributes = ["shrunk"];

    constructor() {
      super();
    }

    connectedCallback() {
      setTimeout(() => {
        const triggers = Array.from(this.getElementsByClassName("trigger"));
        const contents = Array.from(this.getElementsByClassName("content"));
        if (typeof this.shrunk === "undefined") {
          this.shrunk = false;
        }
        contents.forEach( (content) => {
          content.oldStyle = content.style.display;
          if (this.shrunk) content.style.display = "none";
        });
        triggers.forEach((trigger) => {
          trigger.style.cursor = "pointer";
          trigger.addEventListener("click", (event) => {
            this.shrunk = !this.shrunk;
            contents.forEach((content) => {
              content.style.display = this.shrunk ? "none" : content.oldStyle;
            });
          });
        });
      });
    }

    attributeChangedCallback(name, oldValue, newValue) {
      if (name === 'shrunk') this.shrunk = (newValue === "true") || (newValue === "");
    }
  }
);

index.html:

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <title>HTML + JavaScript</title>
    <script src="./shrinkable-content.js"></script>
  </head>
  <body>
    <ul>
      <li>
        <shrinkable-content shrunk>
          <button class="trigger">Alpha Item</button>
          <ul class="content">
            <li>Item One</li>
            <li>Item Two</li>
          </ul>
        </shrinkable-content>
      </li>
    </ul>
  </body>
</html>

Notice the setTimeout() call early in the connectedCallback() function. I added that because without it, the function is called before the children are added/mounted. However, it also delays the execute until after the first render, resulting in flickering.

For some more context: I’m really trying to avoid the ‘shadow’ DOM approach here; it really goes against the design principals I’m trying to follow.

res.status is not a function Next.js 14

I am new to Next js and I am facing a problem whole day

This is my api for checking in mongoDB if user exists


import {connect} from '../../../../lib/mongodb';
import User from '../../../models/userModel';

export async function POST(req, res) {
    try {
        // Get email from request body
        const {email} = await req.json();

        // Connect to database
        await connect();

        // Find user by email
        const user = await User.findOne({email});

        // If user exists, return error
        if (user) {
            return res.status(400).json({message: "User already exists"});
        } else {
            // Return response
            return res.status(201).json({message: "Email is non registered."});
        }
    } catch (error) {
        console.error(error);
        return res.status(500).json({message: "Something went wrong while register"});
    }
}

TypeError: res.status is not a function

I tried to switch req with res, I tried to use NextResponse and NextRequest but I read that they are used only in middleware

Mocking one item in a module in jest tests

My goal is to mock foo, but not mock bar. This is a simplified example that demonstrates my issue, but I also have several other functions that i do NOT want to mock. I call the function bar from inside foo as shown below:

utils.js

const foo = async () => {
  const result = await bar();
  return result;
};

const bar = async () => {
  return 'THINGIMTRYINGTOMOCK';
};

module.exports = {
  foo,
  bar,
};

This is my file for utils.test.js

const { foo, bar } = require('../../utils');

jest
  .spyOn(require('../../utils'), 'bar')
  .mockResolvedValue('1234567890ABCDEF');

describe('who designed this shit', () => {
  test('test description', async () => {
    const result = await foo();
    expect(result).toBe('1234567890ABCDEF');
  });
});

However, this test fails, and the result is “THINGIMTRYINGTOMOCK”, which means it’s not being mocked correctly.

I also tried this alternative approach that I’ve seen posted on stack overflow for my test.js file, but I get the same result:

const { foo, bar } = require('../../utils');

jest.mock('../../utils', () => ({
  ...jest.requireActual('../../utils'),
  bar: jest.fn().mockResolvedValue('1234567890ABCDEF'),
}));

describe('who designed this shit', () => {
  test('test description', async () => {
    const result = await foo();
    expect(result).toBe('1234567890ABCDEF');
  });
});

Can someone explain what is this { default: Simplify<Serialize> return datatype when using useFetch() in nuxt3 3.8.1?

I’m fetching data using useFetch() in nuxt3(version 3.8.1)

var { data: myFixture, pending, refresh, error } = await useFetch('/api/getFixture'). 

useFetch return type

The problem is that I’m receiving data but I cannot access it via attributes myFixture.latestfixtureData.details for example, I mean I can do that but I always get error underline picture bellow
enter image description here

I upgraded from nuxt3 3.0 to nuxt3 3.8.1(latest version), when I was working with nuxt 3.0 everything worked fine but after upgrade this { default: Simplify<Serialize<{ // }>> return datatype is here.

If I access data like this

{{ myFixture?.latestfixtureData.result_info }}

data will display but in visual code there will be an error Property ‘latestfixtureData’ does not exist on type { default: Simplify<Serialize<{ /…*/ }>> *, but I’m validating data on server side with ZOD so I have my own datatype.

But if I use myFixture?.default.latestfixtureData I receive back undefined

What Am I doing wrong with this new version of nuxt3?? What even is this { default: Simplify<Serialize<{ // }>> return datatype

Problem adding a stage to Mastermind game

I am working on Mastermind game, but I want it to have two stages (hard and easy). The easy stage is done, but I had a problem with the hard stage. I want to change the number of selected colors to 8, the guess to 6 circles, and the chance of the game to 12

and also let the user choose the stages in the beginning

Can you help me?



const main_display = document.querySelector('main');
const div_select_colors = document.getElementById('select-color');
const check_button = document.getElementById('check-btn');

const red = '#E42244';
const yellow ='#FFBB36';
const green ='#70C030';
const blue ='#38BEDD';
const purple ='#9F66DF';


let codeLength = 4;
let trys = 10;
let colors = [red, yellow, green, blue, purple];


let random_code = [];
let crackTry = 1;


init();

function init() {
    random_code = [];
    crackTry = 1;
    main_display.innerHTML = '';
    div_select_colors.innerHTML = '';
    

    for (let i = 1; i <= trys; i++) {
        let div_try = document.createElement('div');
        div_try.setAttribute('id', 'try-'+i);
        div_try.setAttribute('class', 'try');
        let div_left = document.createElement('div');
        div_left.setAttribute('class', 'left');
        let div_right = document.createElement('div');
        div_right.setAttribute('class', 'right');

        for (let i = 1; i <= codeLength; i++) {
            let div_l = document.createElement('div');
            let div_r = document.createElement('div');
            div_left.append(div_l);
            div_right.append(div_r);
        }

        div_try.append(div_left);
        div_try.append(div_right);
        main_display.prepend(div_try);
        
    }
    

    for (let i = 1; i <= codeLength; i++) {
        let div_select_wrapper = document.createElement('div');
        div_select_wrapper.setAttribute('class', 'select-wrapper');
        let select = document.createElement('select');

        
        for (let color of colors) {
            let option = document.createElement('option');
            option.setAttribute('style', 'background-color:'+color);
            option.setAttribute('value', color);
            select.append(option);
        }
        select.setAttribute('style', 'background-color:'+colors[0]);

        select.addEventListener('change', (e) => {
            e.target.setAttribute('style', 'background-color:'+e.target.value);
        });

        div_select_wrapper.append(select);
        div_select_colors.append(div_select_wrapper);
    }
    createRandomCode();
}

function createRandomCode() {
    for (let i = 1; i <= codeLength; i++) {
        let random_color = colors[Math.floor(Math.random() * colors.length)]
        random_code.push(random_color);
    }
    console.log(random_code);
}

check_button.addEventListener('click', (e) => {
    
    let input_colors = document.querySelectorAll('.select-wrapper>select');
    let input_colors_arr = [];
    for (let v of input_colors) {
        input_colors_arr.push(v.value);
    }
    show('left', input_colors_arr);
    correction_Array = createCorrectionArray(input_colors_arr);
    show('right', correction_Array);
    crackTry++;
    checkWin(correction_Array);

});


function show(type, colors) {
    let tryView = document.querySelectorAll('#try-'+crackTry+'>.'+type+'>div');
    tryView.forEach((v, i) => {
        v.setAttribute('style', 'background-color:'+colors[i]);
    });
}

function createCorrectionArray(input_colors_arr) {
    let random_code_copy = [...random_code];
    let correction_Array = [];
    
   
    for (let i in random_code_copy) {
        if (random_code_copy[i] == input_colors_arr[i])  {
            random_code_copy[i] = null;
            input_colors_arr[i] = null;
            correction_Array.push('black');
        }
    }
  
    for (let i in random_code_copy) {
        for (j in input_colors_arr) {
            if (random_code_copy[i] != null && random_code_copy[i] == input_colors_arr[j]) {
                random_code_copy[i] = null;
                input_colors_arr[j] = null;
                correction_Array.push('white');
            }
        }
    }
    return correction_Array;
}

function checkWin(correction_Array) {
    let countCorrect = 0;
    for (let v of correction_Array) {
        if (v == 'black') {
            countCorrect++;
        }
    }
    if (countCorrect == codeLength) {
        alert('You did it!');
        init();
    } else if(crackTry > trys) {
        alert(`unfortunatly you lost! the secret pattern was: ${random_code}`);
        init();
    }
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>MasterMind</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>

    <div id="game">
      <header>
        <h1>MasterMind</h1>
      </header>

      <div id="select-color">
        <div class="select-wrapper">
          <select>
            <option class="red"></option>
            <option class="yellow"></option>
            <option class="green"></option>
            <option class="blue"></option>
            <option class="purple"></option>
          </select>
        </div>
      </div>

      <input id="check-btn" type="button" value="Check" />

      <main>
        <div id="try-1" class="try">
          <div class="left">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
          </div>
          
          <div id="correction-1" class="right">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
          </div>
        </div>
      </main>
    </div>
    <script src="./app.js"></script>
  </body>
</html>

* {
  margin: 0px;
  font-family: 'myFont';
}

@font-face {
  font-family: 'myFont';
  src: url(./fonts/Cabin/Cabin-Italic-VariableFont_wdth,wght.ttf);
}
html {
  background-color: #bab3b6;
  margin-bottom: 30px;
}



#game {
  text-align: center;
  color:black;
  background-color: #bab3b6;
  max-width: 400px;
  margin: 10px auto;
}

header{
  padding: 10px;
}

main {
  margin: 10px auto;
}

.try {
  display: flex;
  justify-content: space-around;
  align-items: center;
  border:2px solid black;
  margin: 0 5px 5px 5px;
}

.left,
.right {
  display: flex;
}

.left > div{
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #bab3b6;
  border: 1px solid black;
  margin: 5px;
}
.right > div {
  width: 10px;
  height: 10px;
  background-color: #bab3b6;
  border: 1px solid black;
  margin-right:5px;
}


.select-wrapper {
  border-radius:50%;
  display:inline-block;
  overflow:hidden;
  margin: 5px;
}

.select-wrapper select {
  width:40px;
  height:40px;
  border:0px;
  outline:none;
}

input[type=button] {
  background-color:#bab3b6;
  cursor: pointer;
  color:black;
  font-size:15px;
  border-radius: 15px;
  height:30px;
  width:20%;
  margin: 5px auto;
  transition: 0.5s;
  border: 2px solid ;

  
}

select:hover,
input:hover {
  opacity: 0.8;
}


input[type=button]:hover {
  background-color: black;
  color: #bab3b6;
}

Format the data table of the highcharts.com library

I’m working in Laravel and I’m making a chart with the highcharts.com library and I’m already formatting the chart with values in thousands,
but this library also has a data table, but this table is not formatted with values in thousands, below I share my code

<div class="">
    <figure class="highcharts-figure">
        <div id="container"></div>
    </figure>
</div>

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script>
        var anio = {!! json_encode($anio) !!};
        var mes = {!! json_encode($mes) !!}; ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
        var venta = {!! json_encode($venta) !!}; ['1356940858.000000', '1945419126.000000', '934706589.000000', '1803607453.000000', '78415027.000000']


        venta = venta.map(function(value) {
            return parseFloat(value);
        });

        Highcharts.setOptions({
            lang: {
                thousandsSep: ','
            }
        });

        Highcharts.chart('container', {
            chart: {
                type: 'column'
            },
            title: {
                text: 'Ventas Mensuales',
                align: 'left',
                style: {
                    fontSize: '16px'
                }
            },
            xAxis: {
                categories: mes, // Uses the JavaScript array "mes" for month names
                crosshair: true,
                accessibility: {
                    description: 'Meses'
                }
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Ventas Mensuales'
                },
                labels: {
                    format: '{value:,.0f}'
                }
            },
            tooltip: {
                valueSuffix: ' (COP)'
            },
            plotOptions: {
                column: {
                    pointPadding: 0.2,
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        formatter: function() {
                            return '$' + Highcharts.numberFormat(this.y, 0);
                        }
                    }
                }
            },
            series: [{
                name: 'Ventas',
                data: venta
                // data: valoresY
            }],
            data: {
                table: 'datatable'
            },
            exporting: {
                tableCaption: "Tabla de Ventas Mensuales"
            }

        });


    </script>

Just this link <script src="https://code.highcharts.com/modules/export-data.js"></script> is the one that generates the data Table, next I share images how it looks like

Imagen 1

Imagen 2

the sales value is the one that I want to show formatted in thousands in the data Table

Javascript code to increase element height works in console, but not as a bookmarklet

I have the following code to change the height of a box on the fly:

javascript:(function(){document.getElementsByClassName("tox tox-tinymce")[0].style.height = '700px'})()

If I put this in the console, it works as expected. Then I make it a bookmarklet like so


javascript:(function(){document.getElementsByClassName("tox tox-tinymce")[0].style.height = '700px'})()

// Also tried this using a bookmarklet converter online
// javascript:(function()%7Bdocument.getElementsByClassName(%22tox%20tox-tinymce%22)%5B0%5D.style.height%20%3D%20'700px'%7D)()

When I click the bookmark, I get the following error:

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

This was working a week ago, but suddenly doesn’t. I have no idea why.

Can’t read/parse Riot API Match v5 results (Javascript/NodeJS)

So i’m trying to use the https://americas.api.riotgames.com/lol/match/v5/matches/ get function and read values from the results. I can read it fine, but when I go to reference a field from it, i get this undefined issue, (https://i.stack.imgur.com/7DIyo.png). When I try to do JSON.parse to it, I get this:(https://i.stack.imgur.com/DOjok.png) even though when I copy and paste the json to json lint, it validates it all fine.

At this point I’ve tried every possible naming convention, validating the JSON, I’ve tried converting it to string to remove white spaces. Honestly I’m just a bit stumped as the other Riot API calls I’ve used have been working completely fine with no issue (match/v5/matches/by-puuid/ and summoner/v4/summoners/by-name/). Here is the code:

function getMatch(matchId,puId){

const https = require(‘node:https’);

https.get(‘https://americas.api.riotgames.com/lol/match/v5/matches/’+matchId+’?api_key=’+riotApiKey, (resp) => {

    resp.on('data', (d) => {        
      
      process.stdout.write(d.info.gameDuration);
      let matchResults = JSON.parse(d);
   
    });        
});

}

How to pass body data to jquery ajax function

Using the below function I would to post data (key and value) to PHP, calling this function from another function by passing arguments, but I do not know how to pass data parameter (key and value) as parameter, When I tried getting error from PHP as undefined array key ‘test’

in PHP echo $_POST['test'];

How to pass data value as parameter?

//function to execute ajax

async function doAjax(ajaxType,url,args) {

    let result;
    try {
        result = await $.ajax({
            url: url,
            type: ajaxType,
            data: args //   if I place directly as {test:'123'} its working
        });

     return result;

    } catch (error) {
        console.error(error);
    }

}
//function to call
async function callAjax(){

  const postdata="{test:'123'}";
  let x=await doAjax('POST','ajaxtest.php',postdata);
  alert(x);
}

Web page touch is offset? Doesn’t detect direct touch but will bellow element?

I am updating my webpage to accept touch events so that it can work on mobile but since adding them it would seem they are offset for some reason. This can be seen in browser as well when toggling device type to something touch based.

Elements such as buttons don’t react when touched directly but will if touched bellow the element but all works fine with a mouse. I notice the issue when I updated my function that allows users to drag elements.

function dragElement(elmnt, moveParent = false) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  // move the DIV from anywhere inside the DIV:
  elmnt.onmousedown = dragMouseDown;
  elmnt.addEventListener("touchstart", dragTouch, passiveSupported ? { passive: false } : false);
  if (moveParent) {
    if (!elmnt.parentElement.classList.contains("moveable")) {
      elmnt.parentElement.classList.add("moveable");
    }
  }
  else {
    if (!elmnt.classList.contains("moveable")) {
      elmnt.classList.add("moveable");
    }
  }
  

  function dragMouseDown(e) {
    if (e.button == 0) {
      e.preventDefault();

      if ((moveParent && e.target.parentElement.classList.contains("moveable")) || (!moveParent && e.target.classList.contains("moveable"))) {
        // get the mouse cursor position at startup:
        pos3 = e.clientX;
        pos4 = e.clientY;
        document.onmouseup = closeDragElement;
        // call a function whenever the cursor moves:
        document.onmousemove = elementDrag;
      }
    }
  }
  function dragTouch(e) {
    e.preventDefault();
    if ((moveParent && e.target.parentElement.classList.contains("moveable")) || (!moveParent && e.target.classList.contains("moveable"))) {
      // get the mouse cursor position at startup:
      pos3 = e.changedTouches[0].clientX;
      pos4 = e.changedTouches[0].clientY;
      
      document.addEventListener("touchend", closeDragElement, passiveSupported ? { passive: false } : false);
      document.addEventListener("touchmove", elementDrag, passiveSupported ? { passive: false } : false);
    }
    
  }

  function elementDrag(e) {
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - (e.clientX || e.changedTouches[0].clientX);
    pos2 = pos4 - (e.clientY || e.changedTouches[0].clientY);
    pos3 = (e.clientX || e.changedTouches[0].clientX);
    pos4 = (e.clientY || e.changedTouches[0].clientY);
    
    
    // set the element's new position:
    if (moveParent) {
      elmnt.parentElement.style.top = (elmnt.parentElement.offsetTop - pos2) + "px";
      elmnt.parentElement.style.left = (elmnt.parentElement.offsetLeft - pos1) + "px";
    }
    else {
      elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
      elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
    }
  }

  function closeDragElement() {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
    document.removeEventListener("touchend", closeDragElement);
    document.removeEventListener("touchmove", elementDrag);
  }
}

You can see the webpage here: https://pantheradigital.github.io/
Just click any of the 3 buttons. The windows that popup are what are affected. They can be dragged by moving them from the lighter grey bar at their top.

I haven’t ever dealt with this situation as I am rather inexperienced with web dev so I’m unsure what to do or what is going on here.

Generating an OTP in Postman via JavaScript

I am trying to generate and OTP via JavaScript within Postman. I am doing some automated testing and needs to use and OTP to meet MFA requirements. I have found that I am limited in my options within native Postman.

I have tried the code below along with some other example code using Crypto-JS to no avail… I always get the wrong 6 digit OTP value. I know the correct, working OTPs for the key and counter combination because I have successfully created a similar utility in C#.

I am trying to use the following code within a Pre-Request Script:

function hotp( key, counter, digits ) {

  const buffer = Buffer.alloc(8);
  for (let i = 0; i < 8; i++) {
      buffer[7 - i] = counter & 0xff;
      counter = counter >> 8;
  }
  
  const hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA1, key); 
  hmac.update(CryptoJS.lib.WordArray.create(buffer));

  return zeropad(truncate(Buffer.from(hmac.finalize().toString(), 'hex'), digits), digits);

    function zeropad( value, digits = 16 ) {
        var fill = '0'.repeat( digits )
    return ( fill + value ).slice( -digits )
    }

    function truncate( hmac, digits ) {
    var offset = hmac[ hmac.length - 1 ] & 0x0F
    var value = ( hmac[ offset + 0 ] & 0x7F ) << 24 |
        ( hmac[ offset + 1 ] & 0xFF ) << 16 |
        ( hmac[ offset + 2 ] & 0xFF ) <<  8 |
        ( hmac[ offset + 3 ] & 0xFF )
    return value % ( 10 ** digits )
    }
}

var key = "10f869eadb33edf1160477cfcc503d875aeaa17c"; - example key
var counter = 0;

The values generated for counters 0-8 come out as:
962076
661983
564874
692146
270493
542260
345608
998477
964548

However these values do not work against the application backend. I’ve successfully done this same algorithm in C# and get the OTPs to be accepted.

The correct OTP values for counters 0-8 should be:
529311
627331
461764
308872
837476
597284
520251
728342
407976

Can anyone see what I am doing wrong here?

Not allowed to use async/await while using serverActions in Client component in next.js

Building an infinite scroll in next.js, I am trying to call my serverAction to loadMoreData and using async/await with it to wait for the API call and get result.

Getting an error:

“async/await is not yet supported in Client Components, only Server Components.”

page.tsx is a server component and calls the same server action one time for initial images.

// page.tsx

const Home = async ({ searchParams }) => {

  const searchKeyword =
    typeof searchParams.keyword === "string" ? searchParams.keyword : "";
  
  let apiResponse = await getPhotos({ query: searchKeyword });

  return (
    <main className='p-6 flex justify-center w-full min-h-screen bg-black'>
      <InfiniteScrollData
        search={searchKeyword}
        initialData={apiResponse?.results || []}
      />
    </main>
  );
};

export default Home;

Here is the server action:

// actions.ts

"use server";


export const getData = async ({
  query,
}) => {
  
  const { response } = await fetchData({
    query,
  });
  apiResponse = response;
  
  return response;
};

And following is the client component

// InfiniteScrollData.tsx

"use client";

// imports


const InfiniteScrollImages: = ({
  search,
  initialData,
}) => {
  const [data, setData] = useState(initialData);
  const [page, setPage] = useState(1);
  const [loaderRef, inView] = useInView();

  const loadMoreData = useCallback(async () => {
    const next = page + 1;
    const response = await getData({ query: search, page: next });
    if (response?.results?.length) {
      setPage(next);
      setData((prev) => [...prev, ...(response?.results || [])]);
    }
  }, [page, search]);

  useEffect(() => {
    if (inView) {
      loadMoreData();
    }
  }, [inView, loadMoreData]);

  return (
    <>
      <div>
        {photos?.map((item) => (
          <Card key={item.id} data={item} />
        ))}
      </div>
      <div ref={loaderRef}>
        <Loader />
      </div>
    </>
  );
};

export default InfiniteScrollImages;


Using [email protected]

Maybe there is another way of calling server actions from client components?