useState is not being set

could you guys please advise why my recipeById state is not being updated even tough i already set the state with the correct value response.data.meals
im able to see the value on response.data.meals but recipeById is always undifined
App.js


  const searchRecipe = async (id) => {
    try {
      setRecipeLoading(true);
      console.log("searchResult idmeal", id);
      const response = await api.get(`lookup.php?i=${id}`);
      console.log(response);
      console.log("response", response.data.meals);
      setRecipeById(response.data.meals);
    } catch (error) {
      console.log("error", error.message);
    } finally {
      console.log("searchRecipe done");
      setRecipeLoading(false);
    }
  };

SearchResult.js

function SearchResult({ searchResult, handleOpen, searchRecipe }) {
  //const { idMeal } = useParams;
  return (
    <>
      {searchResult.map((item) => (
        <div className="topic" id={item.idMeal}>
          <h2 className="topic-name">{item.strMeal}</h2>
          <nav>
            <Link to={item.idMeal} key={item.idMeal}>
              <img
                onClick={() => {
                  searchRecipe(item.idMeal);
                  handleOpen();
                }}
                style={{ width: "80%" }}
                src={item.strMealThumb}
                alt={item.idMeal}
              />
            </Link>
          </nav>
        </div>
      ))}
    </>
  );
}

i tried multiple solution but recipeById is always undifined which is really weird

In the typescript react code, when I try to access the fields of an existing object I get undefined

The point is that when I access an entire object of type ProductCardInterface ->

export interface ProductCardInterface {
  image_url: string;
  product_name: string;
  price: number;
}

I get the correct output in the console, but when I try to access the fields of this object, for example here ->

const { image_url, price } = product_data;
...
console.log('product_data:', product_data, 'price:', price, 'image_url:', image_url);

I get undefined ->

product_data: {"image_url":"...","product_name":"table","price":39.99} price: undefined image_url: undefined

Although data is sent and received correctly from the backend, the logs on the backend ->

[2024-01-08T15:51:33Z INFO  back::services::furniture::furniture_get_product_data] ..., table, 39.99
[2024-01-08T15:51:33Z INFO  actix_web::middleware::logger] 127.0.0.1 "GET /furniture/table_get_data HTTP/1.1" 200 698 "http://localhost:5173/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" 0.000857

Component code:

import React, { useEffect, useState } from "react";
import { ProductCardInterface } from "../../interfaces/ProductCardInterface.ts";
import { getProductDataByName } from "../../services/GetProductByName.ts";
import { MyLoader } from "../../utils/Loader/MyLoader.tsx";
import { AddToCart } from "../../services/AddToCart.ts";

export const ProductCard: React.FC<{ name: string }> = ({ name }) => {
  const [product_data, set_product_data] = useState<ProductCardInterface | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    (async () => {
      try {
        set_product_data(await getProductDataByName(name));
      } catch (error: unknown) {
        if (error instanceof Error) {
          console.error(`Error fetching furniture data for ${name}: ${error}`);
          setError(error);
        }
      } finally {
        setLoading(false);
      }
    })();
  }, [name]);

  if (loading) { return <MyLoader />; }

  if (error || !product_data) {
    console.log('Error or no product data:', error, product_data);
    return (
      <div className="error_div">
        <p className="error_definition" id="error_def">
          Internal Server Error: {error ? error.message : "YAR ERROR"}
        </p>
      </div>
    );
  }

  const { image_url, price } = product_data;
  console.log('product_data:', product_data, 'price:', price, 'image_url:', image_url);

  return (
    <div className="product-card">
      <h3 className="product-name">{name}</h3>
      {image_url && <img className="product-image" src={image_url} alt={name} />}
      {price !== undefined && <p className="product-price">Price: ${price}</p>}
      <button
        className="add-to-cart-button"
        id={`add-${name}-to-cart-button`}
        onClick={() => AddToCart(product_data!)}
      >
        Add to Cart
      </button>
    </div>
  );
}

getProductDataByName function:

export const getProductDataByName = async (product_name: string): Promise<ProductCardInterface> => {
  return fetch(`${URL}/furniture/${product_name}_get_data`)
    .then(response => {
      console.log(product_name);
      if (!response.ok) throw new Error(`Failed to fetch data for furnitureId ${product_name}. Status: ${response.status}`);
      return response.json();
    })
    .catch(error => {
      console.error(`Error in getFurnByName: ${error.message}`);
      throw error;
    });
};

SciChart’s Waterfall chart with .NET Blazor wrapper

I’m trying to add this beautiful Waterfall chart SciChart has with this wrapper:
https://github.com/NRTDP/SciChartBlazor
But it looks like there is a problem with rendering 2d surfaces.

I’ve created a Chart.razor on Client side using new Blazor Web App with following code:

@page "/chart"
@using SciChartBlazor
@using SciChartBlazor.Axes
@using SciChartBlazor.DataSeries
@using SciChartBlazor.Modifiers
@using SciChartBlazor.RenderableSeries
@using SciChartBlazor.Services
@rendermode InteractiveAuto
@inject IJSRuntime JsRuntime 

<div id="@Id" @ref="_chart" style="height:600px" />
<button @onclick=Load>Load</button>
@code
{
    private string Id { get; set; } = "C" + Guid.NewGuid().ToString();

    private protected ElementReference _chart;

    SciChartBuilder _chartBuilder = default!;

    int _seriesCount = 10;

    private async void Load()
    {

        for (int i = 0; i < _seriesCount; i++)
        {
            var XAxis = new NumericAxis()
                {
                    Id = $"X{i}",
                    MaxAutoTicks = 5,
                    DrawMajorGridLines = false,
                    GrowBy = new SciChartNumberRange(0, 0.2),
                    VisibleRange = new SciChartNumberRange(-1000.0, 1000.0),
                    VisibleRangeLimit = new SciChartNumberRange(-1000.0, 1000.0),
                    IsVisible = (i == 0),
                    //OverrideOffset = 0
                };

            await _chartBuilder.AddAxis(XAxis, AxisType.X);
            var YAxis = new NumericAxis()
                {
                    Id = $"Y{i}",
                    MaxAutoTicks = 5,
                    DrawMajorGridLines = false,
                    VisibleRange = new SciChartNumberRange(-100.0, 100.0),
                    VisibleRangeLimit = new SciChartNumberRange(-1000.0, 1000.0),
                    IsVisible = (i == 0),
                    //OverrideOffset = 0
                };

            await _chartBuilder.AddAxis(YAxis, AxisType.Y);

            double[] x = new double[10];
            double[] y = new double[10];


            for (int j = 0; j < 10; j++)
            {
                x[j] = (double)j;
                y[j] = Math.Sin(j) * 100 + i;
            }

            var ser = new XyDataSeries<double, double>(x, y) { DataSeriesName = $"N{i}" };

            var fastLineRenderableSeries = new SciChartBlazor.RenderableSeries.FastLineRenderableSeries<double, double>(ser)
                { Id = $"S{i}", XAxisId = $"X{i}", YAxisId = $"Y{i}", StrokeThickness = 1, Stroke = "#64BAE4" };

            await _chartBuilder.AddSeries(fastLineRenderableSeries);
        }

    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            //Create the chart
            _chartBuilder = new SciChartBuilder(_chart, JsRuntime, new SciChartBlazorService(JsRuntime, new SciChartOptions()));
            await _chartBuilder.CreateChart();
        }
    }
} 

With _seriesCount equals 1 it builds a simple chart, but adding more series returns an error in a line:

 this.nativeArgs.StartIndex = rp.indexesRange.min

Full trace:

Error from chart in div Ced51579e-26cc-4536-96e2-49f46254f9db: TypeError: Cannot read properties of undefined (reading 'min')
    at ExtremeResamplerHelper.resetAndFillBasicNativeArgs (ExtremeResamplerHelper.js:178:54)
    at ExtremeResamplerHelper.needsResampling (ExtremeResamplerHelper.js:50:18)
    at BaseRenderableSeries.needsResampling (BaseRenderableSeries.js:935:37)
    at SciChartRenderer.resampleSeries (SciChartRenderer.js:65:17)
    at SciChartRenderer.prepareSeriesRenderData (SciChartRenderer.js:328:57)
    at SciChartRenderer.render (SciChartRenderer.js:144:35)
    at SciChartSurface.doDrawingLoop (SciChartSurface.js:707:35)
    at SciChartSurface.onRenderSurfaceDraw (SciChartSurface.js:1337:18)
    at RenderSurface.onRenderTimeElapsed (RenderSurface.js:37:14)
    at Object.Draw (createMaster.js:294:60)

Following this stacktrace at SciChartRenderer.resampleSeries (SciChartRenderer.js:65:17)

 var rp = new ResamplingParams_1.ResamplingParams(seriesViewRect, rs, xAxis);

where

var ResamplingParams_1 = __webpack_require__(/*! ../Numerics/Resamplers/ResamplingParams */ "./node_modules/scichart/Charting/Numerics/Resamplers/ResamplingParams.js");

it looks like rp is not created correctly but I don’t understand why?

Ps I’ve downloaded the package from git and didn’t use NuGet. Also you can find js equivalent of this here https://github.com/ABTSoftware/SciChart.JS.Examples/blob/master/Examples/src/components/Examples/FeaturedApps/ScientificCharts/InteractiveWaterfallChart/index.tsx

Also you will need to add this line in your App.razor:

<script async src="_content/SciChartBlazor/SciChart/sciChartBlazorJson.js"></script>

calling a function from javascript in html as a button

I wrote a function in Javascript that determines the eligibility to vote, greater than 18 eligible, if not, not eligible to vote. when I tried to call the function using the button Verify in HTML it was not working. I tried to display the result as a pop-up window. please look at my code and see what I am doing wrong.

The code is as follows:

    <html>
    <head><title>Java script</title>
    </head>
    <script>
    function age()
      { 

         if(document.getElementById("age")>=18)

             {
               window.alert("ELIGIBLE FOR VOTE!!");
             }
         else

             {
               window.alert("YOU ARE NOT ELIGIBLE FOR VOTING");
             }

    </script>
    <body>
    <h1>Enter your age:<input type="text" id="age"><br></h1>
    <button type="button" onclick="javascript:age()">VERIFY</button><br>
    </body>
    </html>

enter image description here This is the output I got. I could not display the pop-up window

Can i open an android app using just the package name in a website?

I want to know if its possible to make a button that can launch any app (assuming the user has it installed) with the package name, i dont think its possible but someone out there might know how.

document.location.href = 'intent:#Intent;scheme=app_scheme;package=app_package;end;';

just goes to the google play app showing the app_package app

ive tried one or two other things but there hasnt been anything else that works

Bypass Email Validation with Javascript

I receive hundreds of documents from the courts that my system processes. I used to get public urls to view documents but recently the court software put an email validation link in the url that must be entered before the document will download. I need to find a way to bypass this so I can download the documents with a GET call.

Example:

https://minnesota.tylertech.cloud/DownloadResource.ashx?RID=4df7d320-8d9a-4cee-a9ee-4b94ef8128b8

I was hoping to just be able to add a URL parameter with my email but I cannot get that to work.

This is the response now on my call (instead of just downloading the doc):

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
    Validate Authorization to this Document:
</title><link href="css/tylerui.min.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>


<body>
        <form method="post" action="./DownloadResourceValidate.aspx?RID=4df7d320-8d9a-4cee-a9ee-4b94ef8128b8" id="formValidate">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTEzOTU4MjgxOWRkP23EwOMM3RpTrXIodb3e8jyilvHeboA8NB9OwIIaz1I=" />

<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="A580CC42" />
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAAMazmUF/tC1u6vGSgb5f+cMItpF8jP9UFQUAQAedodKY3ciJN2LpkiT3kPbz9Ne/Fe2Ot8f9lm6hsw03/5DToyrZBt9XGqE2NEXEjgwH5ZJjA==" />
            <div class="row">
                <div class="col-md-4 col-md-offset-4">
                    <div class="form-group pristine">
                        <div class="editor-label">
              <p  style="margin-top:2cm;" />
                            <label for="emailAddress" id="lblEmailAddress">Enter your email address</label>
              <p>To download the document please enter your email address below and click validate.</p>
                        </div>
                        <div class="editor-field">
                            <input name="emailAddress" type="text" id="emailAddress" class="form-control" onchange="clearMessage(&#39;emailAddressMessage&#39;)" />
                            <span id="emailAddressMessage" class="alert-danger"></span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
        <div class="col-md-4 col-md-offset-4">
            <input type="submit" name="SubmitEmailAddressButton" value="Validate" id="SubmitEmailAddressButton" class="tyler-btn tyler-btn-primary" />
                    <br/><br/>
            </div>
      </div>  
   </form>
        
  <script type="text/javascript">
    function clearMessage(messageElementID) {
        var element = document.getElementById(messageElementID);
        element.style.display = 'none';
    }
  </script>
</body>
</html>

Adding my email as a url parameter.

ReactJS Sweep Line: Optimizing SciChartJS Performance, Reusing wasmContext for Multiple Chart Rendering

I have a performance problem with scichartjs, when initializing about 40 charts/surfaces the rendering state drops to 5-10 frames per second.

I think it might be related to the fact that I run the create function each time and not reusing the wasmContext maybe?
but I am not sure how to reuse the wasmContext or what is the best performance for this kind of type

demo : https://9669tv.csb.app/

enter image description here
(sorry for the low quality of the Giff due to 2 MB max size of upload)

this is my init function


export const initScichart = async (divElementId) => {
  SciChartSurface.UseCommunityLicense();
  //console.log(divElementId.id);
  const { sciChartSurface, wasmContext } = await SciChartSurface.create(
    divElementId,
    {
      theme: new SciChartJsNavyTheme(),
    }
  );

  sciChartSurface.xAxes.add(
    new NumericAxis(wasmContext, {
      visibleRange: new NumberRange(0, 5),
    })
  );
  sciChartSurface.yAxes.add(
    new NumericAxis(wasmContext, {
      autoRange: EAutoRange.Always,
    })
  );

  const xyDataSeries = new XyDataSeries(wasmContext, {
    fifoCapacity: 220_000, // set fifoCapacity. Requires scichart.js v3.2 or later
    fifoSweeping: true,
    fifoSweepingGap: 2_200,
    containsNaN: false,
    isSorted: true,
  });

  sciChartSurface.renderableSeries.add(
    new FastLineRenderableSeries(wasmContext, {
      dataSeries: xyDataSeries,
      strokeThickness: 1,
      stroke: "#50C7E0",
    })
  );

  xyDataSeries.sciChartSurfaceToDelete = sciChartSurface;

  return xyDataSeries;
};

enter image description here

the reason I need the charts on different surfaces is that I need to wrap them in SortableJS (to be able to drag them across the website)

How to use the map function to input JSON data into a div element

I have an API URL which is this

https://api-amvstrm.nyt92.eu.org/api/v1

/popular and the API response looks like this

t

itle": "Dungeon Meshi",

      "id": "dungeon-meshi",

      "image_url": "https://gogocdn.net/cover/dungeon-meshi-1704169699.png",

      "released": "2024"

And so I want to use the map function in js to redirect the data from the API into this html container



                                    </div>

                                    <div class="product__item__text">

                                        <ul>

                                            <li>Active</li>

                                            <li>Movie</li>

                                        </ul>

                                        <h5><a href="#">Kizumonogatari III: Reiket su-hen</a></h5>

                                    </div>

                                </div>

                            </div>

                            <div class="col-lg-4 col-md-6 col-sm-6">

                                <div class="product__item">

                                    <div class="product__item__pic set-bg" data-setbg="img/popular/popular-3.jpg">

                                        <div class="ep">18 / 18</div>

                                        <div class="comment"><i class="fa fa-comments"></i> 11</div>

                                        <div class="view"><i class="fa fa-eye"></i> 9141</div>

Is there a way I can use the js map function to only display the title and image picture only ? Thanks ki

Improve performance of simple Javascript code to generate and shuffle a deck of cards

The below code will crash my browser if the number of decks is more than one. What can I do to resolve this? Disabling the shuffle does not seem to have any impact. I tried putting it JSFiddle and that also crashes.

function shuffleDeck(jokers) {
  let deck = [
    '&hearts;A', '&hearts;2', '&hearts;3', '&hearts;4', '&hearts;5', '&hearts;6', '&hearts;7', '&hearts;8', '&hearts;9', '&hearts;T', '&hearts;J', '&hearts;Q', '&hearts;K',
    '&diams;A', '&diams;2', '&diams;3', '&diams;4', '&diams;5', '&diams;6', '&diams;7', '&diams;8', '&diams;9', '&diams;T', '&diams;J', '&diams;Q', '&diams;K',
    '&clubs;A', '&clubs;2', '&clubs;3', '&clubs;4', '&clubs;5', '&clubs;6', '&clubs;7', '&clubs;8', '&clubs;9', '&clubs;T', '&clubs;J', '&clubs;Q', '&clubs;K',
    '&spades;A', '&spades;2', '&spades;3', '&spades;4', '&spades;5', '&spades;6', '&spades;7', '&spades;8', '&spades;9', '&spades;T', '&spades;J', '&spades;Q', '&spades;K'
  ];

  if (jokers) {
    for (i = 0; i < jokers; i++) {
      deck.push('&star;');
    }
  }

  for (let i = deck.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [deck[i], deck[j]] = [deck[j], deck[i]];
  }

  return deck;
}

function generateRandomDeck() {
  let jokers = document.getElementById('cardsInputNumberOfJokers').value;
  let numberOfDecks = document.getElementById('cardsInputNumberOfDecks').value;

  currentArray = [];

  for (i = 0; i < numberOfDecks; i++) {
    let deck = shuffleDeck(jokers);
    currentArray = currentArray.concat(deck);
  }

  console.log(`generating ${numberOfDecks} deck(s)`);
  console.log(currentArray);
}

generateRandomDeck();
<input type="text" value="2" id="cardsInputNumberOfJokers" />
<input type="text" value="2" id="cardsInputNumberOfDecks" />

Updating the coordinates of the child element after scaling

Help me figure out how to update coordinates for child elements in the form of imgElement images in div canvas-cameras. In the center there is a div with a background picture. In the div, I add as many small images as I want using the ShowImage() function. Using mouse events, I can move both the entire div (with all the pictures inside with reference to a specific location) and the pictures themselves. There are no problems with this. The problem appears when scaling. When I scale the whole div and start moving the picture in this div, it abruptly moves away from the mouse to the left or right (depending on the degree of scaling), but if I release the picture and try to move it again, it does not jump away. As I understand it, this is due to the fact that when zooming, the coordinates of the images inside the div are also “scaled” and when the image is moved for the first time, it “adapts” to the new coordinates. How to fix it? The code is a bit “dirty”, I’m experimenting with it.

var scale = 1,
    images = document.querySelectorAll('.draggable-image'),
    activeImage = null,
    minScale = 0.7,
    maxScale = 2,
    panning = false;

function setTransform(element, pointX, pointY) {
    element.style.transform = "translate(" + pointX + "px, " + pointY + "px) scale(" + scale + ")";
}
function setTransform2(element, pointX, pointY) {

    element.style.transform = "translate(" + pointX + "px, " + pointY + "px)";
}

function handleMouseDown(e) {
    e.preventDefault();
    var target = e.target;

    if (target.classList.contains('draggable-image')) {
        activeImage = target;


        activeImage.startX = (e.clientX - window.scrollX - parseInt(activeImage.dataset.pointX || 0)) / scale;
        activeImage.startY = (e.clientY - window.scrollY - parseInt(activeImage.dataset.pointY || 0)) / scale;

        panning = true;
    }
}

function handleMouseUp() {
    panning = false;
    activeImage = null;
}

function handleMouseMove(e) {
    if (!panning || !activeImage) {
        return;
    }

    var newPointX = (e.clientX - window.scrollX - activeImage.startX * scale);
    var newPointY = (e.clientY - window.scrollY - activeImage.startY * scale);

    activeImage.dataset.pointX = newPointX;
    activeImage.dataset.pointY = newPointY;

    if (activeImage.id == 'canvas-cameras') {
        setTransform(activeImage, newPointX, newPointY);
    } else {
        setTransform2(activeImage, newPointX / scale, newPointY/ scale);
    }
}

function handleWheel(e) {
    var delta = (e.wheelDelta ? e.wheelDelta : -e.deltaY);

    if (delta > 0 && scale < maxScale) {
        scale *= 1.2;
    } else if (delta < 0 && scale > minScale) {
        scale /= 1.2;
    }

    var canvasDiv = document.getElementById('canvas-cameras');
    var xs = (e.clientX - parseInt(canvasDiv.dataset.pointX)) / scale,
        ys = (e.clientY - parseInt(canvasDiv.dataset.pointY)) / scale;
    canvasDiv.dataset.pointX = e.clientX - xs * scale;
    canvasDiv.dataset.pointY = e.clientY - ys * scale;
    setTransform(canvasDiv, parseInt(canvasDiv.dataset.pointX), parseInt(canvasDiv.dataset.pointY));
}

document.addEventListener('mousedown', handleMouseDown, { passive: false });
document.addEventListener('mouseup', handleMouseUp);
document.addEventListener('mousemove', handleMouseMove, { passive: false });
document.addEventListener('wheel', handleWheel, { passive: false });

var imageCounter = 1;

document.getElementById('addCamera').addEventListener('click', function () {
    showImage();
});

function showImage() {
    var imgElement = document.createElement('img');
    var canvasDiv = document.getElementById('canvas-cameras');

    imgElement.src = '/images/cameras_img/camera.png';
    imgElement.alt = 'Картинка ' + imageCounter;
    imgElement.className = 'draggable-image';

    imgElement.style.position = 'absolute';
    imgElement.style.top = '20px';
    imgElement.style.left = '20px';
    imgElement.style.height = '20px';
    imgElement.style.width = '20px';

    var uniqueId = 'image' + imageCounter;
    imgElement.id = uniqueId;

    canvasDiv.appendChild(imgElement);

    images = document.querySelectorAll('.draggable-image');
    imgElement.dataset.pointX = 0;
    imgElement.dataset.pointY = 0;
    imageCounter++;
}

I have already tried to update the coordinates as best I could after scaling all the pictures, but nothing comes out…

How to create a private custom event?

I would like to create a private custom event, an event nobody else can dispatch or listen. I tried this, but it does not work:

new CustomEvent(Symbol("validate"));

Is it possible?

I know I can do something like this:

new CustomEvent(crypto.randomUUID());

Discord.js v14 Missing permissions when given

So today I’ve tried to create command in discord bot that can rename user which typed the command to something else. However no matter what I do this code allways returns error Missing Permissions.

const {Client, GatewayIntentBits, EmbedBuilder, SlashCommandBuilder, Guild} = require('discord.js');
const client = new Client(
    {
        intents:
        [
            GatewayIntentBits.Guilds,
            GatewayIntentBits.GuildMessages,
            GatewayIntentBits.GuildMembers,
            GatewayIntentBits.MessageContent,
        ]
    }
);

client.on("ready", () =>
{
    console.log("Bot is ready!");

    const nicknameCH = new SlashCommandBuilder()
    .setName('changenick')
    .setDescription('Changing nickname')
    .addStringOption((option) =>
        {
            return option
            .setName("newnick")
            .setRequired(true)
        })

    client.application.commands.create(nicknameCH);

});

client.on('interactionCreate', (interaction) => 
{
    if(!interaction.isChatInputCommand()) return;
    if(interaction.commandName === 'changenick')
    {
        const stringOption = interaction.options.getString("newnick").toString();

        const thisUser = interaction.guild.members.cache.get(interaction.user.id);
        thisUser.setNickname(stringOption);

        interaction.reply('Changing to: ' + stringOption);
    }
});

client.login(TOKEN)

enter image description here

I’ve set bot role to highest place in roles tab on discord server settings and given him Admin permission, reinvited him.

I’m expecting to change user nickname no matter if he has permissions to do that or not via bot

rawError: { message: ‘Unknown interaction’, code: 10062} on discord.js v14

When I run every other command it works perfectly fine, but when I use /rank it shows the “Unknown interaction” error, the error only occurs when the error handeling doesn’t have any problems, for example a valid user id and rank id, when it does though, it works perfectly fine.

I’m not a fan of try{} so if theres a away to fix it with using .try, let me know

Code:

if (interaction.commandName === "rank") {
    const tuser = interaction.options.getNumber("targetuser");
    const trank = interaction.options.getNumber("targetrank");

    noblox
      .changeRank(5156922, tuser, trank)
      .then(async () => {
        const username = await noblox.getUsernameFromId(tuser);
        const grn = await noblox.getRankNameInGroup(5156922, tuser);
        interaction.reply(
          `The rank of ${username} has been updated and they have been ranked to **${grn}**`
        );
      })
      .catch((error) => {
        console.error(error.stack);
        interaction.respond({
          content: `Something went wrong, Here is what can have gone wrong: nn- **The user id does not exist or isn't in the group**n- **The rank number does not exist**nPlease double check the fields. Thank you!`,
          ephemeral: true,
        });
      });
  }

Error:

rawError: { message: 'Unknown interaction', code: 10062 },
  code: 10062,
  status: 404,
  method: 'POST',
  url: 'https://discord.com/api/v10/interactions/1193921932316377109/aW50ZXJhY3Rpb246MTE5MzkyMTkzMjMxNjM3NzEwOTpjRkVPQTZlSzUxNE1RQmxzM0M4Y3h1TFN6VU45ZmpkVEtXTXk2cThCalpGUWtiSXZHVnVtVVBxTzR2U01HcDZRb0RRT3RxeXAwYmZxTlpicDZIMjAwb3RreFQ4Wm5CaEN4MXVKdmx1cGZpZGRWdW5YUXo4Q2Zxd3NDZmNOM05WNQ/callback'
}

I’m trying to fix the /rank thing, please let me know.