cant send javascript variable to server-side code behind

i want to send value (which is in my javascript) to an asp hiddenfield value so i can access the variable in code behind (C#).

so i have a hiddenfield:

<asp:HiddenField id="SendA" value="ee" runat="server" />

and in my javascript:

function test2() {
    
    document.getElementById("<%=SendA.ClientID%>").value = "nice";
    alert(document.getElementById("<%=SendA.ClientID%>").value);
}

but the console says: JavaScript.js:76 Uncaught TypeError: Cannot set properties of null (setting ‘value’)
at test2.

i have the right syntax and it should alert nice , whats my problem?

NextJS – type issue of Error handling in Route Handler

I have a route handler like below

app/api/transactions/route.ts

import { NextRequest, NextResponse } from "next/server";
import { AxiosError } from "axios";
import axios from "../axios";
import { AxiosResponse } from "axios";
import { Transaction } from "../../../types";

interface Error {
  message: string[];
  statusCode: number;
}

export async function GET(request: NextRequest) {
  try {
    const transactionsRes: AxiosResponse<Transaction[]> = await axios.get(
      `/transactions`
    );

    return NextResponse.json(transactionsRes.data);
  } catch (error) {
    const axiosError = error as AxiosError<Error>;
    return NextResponse.json(
      { error: axiosError?.response?.data.message },
      { status: axiosError?.response?.data.statusCode }
    );
  }
}

MyComponent.tsx

export const MyComponent = async() => {
  const raw = await fetch('api/transaction');
  const transactions: Transaction[] = await raw.json();
  if (transactions.error) {
    throw new Error(transactions.error);
  }
  ...
}

I also have a error.tsx served as a error boundary to catch error

The problem I found is that, when I handle error in this way, I might need to type the transaction response like this.

const transactions: Transaction[] | TransactionError = await raw.json();

The type seems so confusing and not extendable to me if I do in this way. Just wondering what is the best structure to handle errors in nextjs?

How to update a nested key containing a dot?

In a document like this:

[
  {
    a: "",
    b: 1,
    "createdAccounts": {
      "[email protected]": {
        "id": ["a", "b", "c"]
      }
    }
  }
]

I’m querying an email as:

    const email = "[email protected]"
    let account = await db.collection("users").aggregate(
    [
        {
            "$project": {
                "createdAccounts": {
                    "$objectToArray": "$createdAccounts"
                }
            }
        },
        {
            "$match": {
                "createdAccounts.k": email
            }
        },
        {
            "$project": {
                "createdAccounts": {
                    "$arrayToObject": "$createdAccounts"
                }
            }
        }
    ]).toArray().then(results =>
    {
        const document = results[0];
        if (document && document.createdAccounts)
            return document.createdAccounts[email];        
        return null; 
    })

I wonder if there’s a “better way” to query the email, I’m using aggregate because the searched key can contain a dot (.) in its path

and in this case, this:

const email = "[email protected]"
let account = await db.collection("users").findOne({ "createdAccounts.email": email });

wouldnt work.

Using the aggregate query I get as response:

"[email protected]": {
    "id": ["a", "b", "c"]
}

Suppose i need to modify the id array, as its inside a key containing a dot (.)
i couldn’t find how to update it.

Also, the update method will concatenate the array or overwrite it?

How to insert JSON string format into velo (WIX) textbox

I’m trying to show this JSON in textbox when the user selects ‘CHART JSON’ option in the dropdown

var data_chart = {"data":{"labels":["_2024_03_09","_2024_03_10","_2024_03_11","_2024_03_12","_2024_03_13","_2024_03_14","_2024_03_15"],"datasets":[{"label":"10JiFG1L7Y","type":"line","data":[0,0,0,0,0,0,802],"backgroundColor":"rgba(173,118,240,0.2)","borderColor":"rgba(173,118,240,1)","borderWidth":1},{"label":14029,"type":"line","data":[0,22,0,0,16,0,36],"backgroundColor":"rgba(29,22,1,0.2)","borderColor":"rgba(29,22,1,1)","borderWidth":1}]},"customization":{"borderWidth":1}}

To do so I used JSON.stringify(data_chart) to feed the dropdown with the “CHART JSON” value

 $w("#dropdown2").options  = [
        { label: "SQL", value: "No Code" },
        { label: "CHART JSON", value: JSON.stringify(data_chart)}
        
    ];

and insert it into the textBox:

export function dropdown2_change(event) {
    // Set the value of textBox1
    $w("#textBox1").value = $w("#dropdown2").value
}

But it shows item2 instead of the JSON, if I change it to string for example ‘chart’ it shows chart (as expected), how to fix this?
enter image description here

How to cut out a circle from a black background in Phaser 3

I am making a sidescroller Phaser 3 game and have been having issues with how to make a transparent circle around the player on a black background or how to move the player to the front after the circle and background are drawn (if i used a yellow circle instead of the transparent one).

I have tried using masks and drawing a transparent circle on top of the background but I can’t get it to work. I also tried a yellow circle and black background but both a bit transparent to get a cave and light like look but I didn’t know how to draw it behind the player and enemies.

This is my current code and result

this.blackBackground = this.add.graphics()
this.blackBackground.fillStyle(0x000000, 1)
this.blackBackground.fillRect(0, 0, this.cameras.main.width, this.cameras.main.height)

var holeRadius = 100
var holeX = this.player.x
var holeY = this.player.y

this.blackBackground.fillStyle(0x000000, 0)
this.blackBackground.fillCircle(holeX, holeY, holeRadius)

The first code shows this picture there should be a transparent circle around the player(the purple rectangle)

My original idea was to make a yellow circle and black background both a bit transparent but the player then isn’t seen enough and I don’t know how to fix that, I would also like to still cut out the circle so the yellow wouldnt be so dark

this.blackBackground = this.add.graphics()
this.blackBackground.fillStyle(0x000000, 0.9)
this.blackBackground.fillRect(0, 0, this.cameras.main.width, this.cameras.main.height)

var holeRadius = 100
var holeX = this.player.x
var holeY = this.player.y

this.blackBackground.fillStyle(0xffff00, 0.4)
this.blackBackground.fillCircle(holeX, holeY, holeRadius)

This is the second result

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

(Apologize for my english) Hey, I wanted to create a channel after command executes.
After executing command, it shows me the error

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

My ticket.js code below

const {
    Client,
    SlashCommandBuilder,
    PermissionFlagsBits,
    GatewayIntentBits
} = require('discord.js');

const client = new Client({
    intents: [GatewayIntentBits.Guilds]
});

module.exports = {
    data: new SlashCommandBuilder()
        .setName('ticket')
        .setDescription('Utwórz ticketa'),
    async execute(interaction, client) {
        interaction.guild.channels.create({
            name: `ticket`,
            type: ChannelType.GuildText,
            parent: cat[0].ID
            // your permission overwrites or other options here

        });

    }
};

How to easily setup RxDB in JavaScript [closed]

I’ve been trying to set up a secure real-time database for my website so I can add authentication/login and signup. I’ve been told that RxDB is secure for storing data. I can’t use Node.js before you tell me that’s what I need to do. I need a way to set up RxDB in my JavaScript.

FILES
login.html
signup.html
script.js

My login HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Login | WebsiteName</title>
    </head>
    <body>
        <h1>Login</h1>
        <form id="loginForm">
            <input id="loginUsername" type="text" placeholder="Username"/>
            <input id="loginPassword" type="password" placeholder="Password"/>
            <input id="submitLogin" type="submit"/>
        </form>
    </body>
    <script src="script.js"></script>
</html>

My signup HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Signup | WebsiteName</title>
    </head>
    <body>
        <h1>Signup</h1>
        <form id="signupForm">
            <input id="signupUsername" type="text" placeholder="Username"/>
            <input id="signupPassword" type="password" placeholder="Password"/>
            <input id="signupEmail" type="email" placeholder="Email"/>
            <input id="submitSignup" type="submit"/>
        </form>
    </body>
    <script src="script.js"></script>
</html>

My script

function login(username, password) {
    // send login request
};
function signup(username, password, email) {
    // send signup request
};
document.getElementById("submitLogin").addEventListener("click", () => {
    login(document.getElementById("loginUsername"), document.getElementById("loginPassword"));
});
document.getElementById("submitSignup").addEventListener("click", () => {
    signup(document.getElementById("signupUsername"), document.getElementById("signupPassword"));
});

Please comment on why you downvote this question if you downvoted this question, the feedback will help me ask better questions.

SyntaxError: Unexpected token ‘async’ when index.js file called

I have a node.js app running locally in netbeans. Its entry point is an app.js file:

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable @typescript-eslint/no-var-requires */
import * as express_1 from "express";
import * as cors_1 from "cors";
import * as logger_1 from "./config/logger.js";
import * as database_1 from"./database/index.js";
import * as auth_routes_1 from "./routes/auth.routes.js";
import * as auth_routes_2 from "./routes/items.routes.js";
// import cron from 'node-cron'
import * as index_1 from "./helper/scrapping/index.js";
import * as morgan_1 from "morgan";
var scrap = new index_1.Scrapping();
var app = (0, express_1.default)();
(0, database_1.default)();
var port = process.env.PORT || 8080;
import dotenv from 'dotenv';
dotenv.config();
app.use((0, cors_1.default)());
app.use(express_1.default.json({
    limit: "50mb",
    type: [
        "application/json",
        "text/plain", // AWS sends this content-type for its messages/notifications
    ],
}));
app.use(express_1.default.urlencoded({ extended: true }));
app.use((0, morgan_1.default)(':date *** :method :: :url ** :response-time'));
app.use(routes_1.default);
setInterval(function () { return __awaiter(void 0, void 0, void 0, function () {
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                console.log('running jobs');
                return [4 /*yield*/, scrap.saveDailyJobSimilarItem()];
            case 1:
                _a.sent();
                return [4 /*yield*/, scrap.saveDailyJobSameItem()];
            case 2:
                _a.sent();
                console.log('cleaning');
                return [4 /*yield*/, scrap.cleanDailyJobsCategories()];
            case 3:
                _a.sent();
                return [4 /*yield*/, scrap.cleanDailyJobsItems()];
            case 4:
                _a.sent();
                return [2 /*return*/];
        }
    });
}); }, 86400000);
// setInterval(async () => {
//   await scrap.saveDailyJobSameItem()
//   console.log('running same job')
// }, 92500000)
// setTimeout(async () => {
//   console.log('it begins')
//   await scrap.saveDailyJobSimilarItem()
//   console.log('running similar job')
// }, 1000)
// setTimeout(async () => {
// console.log('it begins 2.0')
//   await scrap.saveDailyJobSameItem()
//   console.log('running same job')
// }, 3600000)
app.get('/test-simi', function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: 
            // const x = await scrap.saveDailyJobSameItem()
            return [4 /*yield*/, scrap.saveDailyJobSimilarItem()];
            case 1:
                // const x = await scrap.saveDailyJobSameItem()
                _a.sent();
                res.json('running');
                return [2 /*return*/];
        }
    });
}); });
app.get('/test-same', function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, scrap.saveDailyJobSameItem()
                // const x = await scrap.saveDailyJobSimilarItem()
            ];
            case 1:
                _a.sent();
                // const x = await scrap.saveDailyJobSimilarItem()
                res.json('running');
                return [2 /*return*/];
        }
    });
}); });
app.listen(port, function () {
    logger_1.logger.info("server listening on http://localhost:".concat(port));
});

That app.js invokes an index.js file shown here:

// /* eslint-disable @typescript-eslint/no-empty-function */
import puppeteer from "puppeteer";
import Model from "../../schema/scrapped-items.model";
import _ from "underscore";
import dailyJob from "../../schema/daily-job.model";
import axios, { AxiosResponse } from "axios";
import CategoryModel from "../../schema/category.model";
import itemModel from "../../schema/item.model";
import { similarity } from "../utils/similarity";
import dailyJobModel from "../../schema/daily-job.model";
import categoryModel from "../../schema/category.model";
import { logger } from '../../config/logger';

class Scrapping {
public async scrapCall(item) {
    try {
      const url = `https://xxx-yyy.zzz.com/api/v1/scrap-item?item=${item}`;
      const response = await axios.get(url);
      return response.data;
    } catch (error) {
      console.log(error);
    }
  }
  public async ebayScrapping(item) {
    try {
      const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
      const page = await browser.newPage();
      await page.goto("https://www.ebay.com/");
      await page.waitForSelector("#gh-ac");
      await page.type("#gh-ac", `${item}`);
      await page.click('input[value="Search"]');

      await page.waitForSelector("div.s-item__wrapper");

      const link = await page.$$eval("img.s-item__image-img", (items) => {
        return items.map((item: any) => {
          return item.src;
        });
      });

      const title = await page.$$eval("h3.s-item__title", (items) => {
        return items.map((item: any) => {
          return item.innerText;
        });
      });

      const price = await page.$$eval("span.s-item__price", (items) => {
        return items.map((item: any) => {
          return item.innerText;
        });
      });

      const invs = [];

      for (let i = 0, length = 17; i < length; i++) {
        const inv: any = {
          price: this.priceToStr(price[i]),
          title: title[i],
        };
        if (i < link.length) {
          inv.link = link[i];
          inv.baseCurrency = "$";
          inv.date = new Date();
        }
        invs.push(inv);
      }

      return invs;
    } catch (error) {
      if (error instanceof puppeteer.errors.TimeoutError) {
        return error.message;
      }
    }
  }
  public async ebayScrappingDaily(
    itemId?: any,
    user?: any,
    id?: any,
    item?: any
  ) {
    try {

      const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
      const page = await browser.newPage();
      await page.goto("https://www.ebay.com/");
      await page.waitForSelector("#gh-ac");
      await page.type("#gh-ac", `${item}`);
      await page.click('input[value="Search"]');

      await page.waitForSelector("div.s-item__wrapper");

      const link = await page.$$eval("img.s-item__image-img", (items) => {
        return items.map((item: any) => {
          return item.src;
        });
      });

      const title = await page.$$eval("h3.s-item__title", (items) => {
        return items.map((item: any) => {
          return item.innerText;
        });
      });

      const price = await page.$$eval("span.s-item__price", (items) => {
        return items.map((item: any) => {
          return item.innerText;
        });
      });

      const invs = [];

      for (let i = 0, length = 17; i < length; i++) {
        const inv: any = {
          price: this.priceToStr(price[i]),
          title: title[i],
        };
        if (i < link.length) {
          inv.link = link[i];
          inv.baseCurrency = "$";
          inv.date = new Date();
        }
        invs.push(inv);
      }

      return invs;
    } catch (error) {
      console.log(error);
      throw new Error(error.message);
    }
  }
  public async saveScrapItem(category, item_title, itemId, user) {

    const same_data = await this.scrappingBee(item_title, itemId);
    same_data.forEach(x => x.similarity = similarity(x.title,item_title))

    let good_items = []
    for(const aitem of same_data){
      if(aitem.similarity >= 0.8) good_items.push(aitem)
    }
    if(good_items.length == 0){
      good_items = same_data.slice(0,30)
    }
    const similar_data = same_data.slice(good_items.length,same_data.length)

    const average = await this.getAveragePrice(good_items);
    const median = await this.getMedianPrice(good_items);
    const {high, low} = await this.getHighLowPrice(same_data)

    const createNewScrapItem = await Model.create({
      _itemId: itemId,
      _userId: user,
      similar_data: similar_data,
      same_data: same_data,
      average,
      median,
      highest_price: high,
      lowest_price: low,
    });

    if (createNewScrapItem) return true;
  }
  public async saveDailyJobSimilarItem() {

    // const data = await Model.find({});

    // const similar_data = data.map((item) => item.similar_data).flat()
    const categories = await CategoryModel.find({});

    const all_categories = categories[0].category


    const items = [];

    for (let i = 0; i < all_categories.length; i += 1) {
      items.push(all_categories.slice(i, i + 1));
    }
    let response;
    let offset = 0;

    _(items).each((item) => {
      setTimeout(() => {
        item.forEach(async (category) => {
          if (category) {
            // console.log(item.title)
            const data = await this.scrappingBeeDaily(category);

            // data.forEach(el => el.similarity = similarity(el.title,item.title))

            const average = await this.getAveragePrice(data);

            const median = await this.getMedianPrice(data);

            return await dailyJob.create({
              median: median,
              average: average,
              category: category,
              similar_data: data,
            });
          }
          return response;
        });
      }, 25000 + offset);
      offset += 25000;
    });
  }
  public async saveDailyJobSameItem() {

    const items_data = await itemModel.find({});
    const same_data = items_data.map((item) => {
      let item_keywords = item.item_keywords.filter(x=>x.toLowerCase() != item.item_title.toLowerCase())
      let title = item.item_title
      item_keywords.forEach(x=>title+=" "+x)
      return {
        title: title,
        item: item._id,
      }
    })


    const items = [];

    for (let i = 0; i < same_data.length; i += 1) {
      items.push(same_data.slice(i, i + 1));
    }
    let response;
    let offset = 0;

    _(items).each((item) => {
      setTimeout(() => {
        item.forEach(async (item) => {

          if (item.title !== 'Shop on eBay') {
            // console.log(item.title)
            const data = await this.scrappingBeeDaily(item.title, item.item);

            data.forEach(el => el.similarity = similarity(el.title,item.title))

            let same_data = data
            let good_items = []
            for(const aitem of same_data){
              if(aitem.similarity >= 0.8) good_items.push(aitem)
            }
            if(good_items.length == 0){
              good_items = same_data.slice(0,30)
            }

            const average = await this.getAveragePrice(good_items);

            const median = await this.getMedianPrice(good_items);

            const {high, low} = await this.getHighLowPrice(good_items)
             

            return await dailyJob.create({
              _scrapId: item.item,
              median: median,
              average: average,
              same_data: data,
              lowest_price: low,
              highest_price: high,
            });
          }
          return response;
        });
      }, 25000 + offset);
      offset += 25000;
    });
  }


              },
            },
          },
        },
      });

      const response = data.data;

      const invs = [];

      await response.map(async (item) => {
        if (item) {
          const inv: any = {
            price: await this.priceToStr(item.price),
            title: item.title,
          };
          if (item.link) {
            inv.link = item.link;
            inv.baseCurrency = "$";
            inv.date = new Date();
            inv.url = item.url
            inv.item = id
          }
          invs.push(inv);
        }
      });
      return invs.slice(0,100);
    } catch (error) {
      throw new Error("ScrapingBee Error: " + error.message);
    }
  }
  public async scrappingBeeDaily(items, id = null) {
    const url = items.split(" ").join("+")
    try {
      const { data } = await axios.get("https://app.scrapingbee.com/api/v1", {
        params: {
          api_key:
            "DCXO8PT2BDINHZNQDJUMHLK9FYAKG3MDW9U4T1A4G7KNZ4IN7WNYA796GELUFA1KW9VQ7R9ZXSXN28IH",
          url: `https://www.ebay.com/sch/i.html?_from=R40&_trksid=p2380057.m570.l1313&_nkw=${url}&_sacat=0`,
          // Wait for there to be at least one
          // non-empty .event-tile element
          wait_for: ".s-item",
          extract_rules: {
            data: {
              // Lets create a list with data
              // extracted from the .event-tile element
              selector: ".s-item",
              type: "list",
              // Each object in the list should
              output: {
                // have a title lifted from
                // the .event-tile__title element
                price: ".s-item__price",
                title: ".s-item__title",
                link: {
                  selector: ".s-item__image-wrapper img",
                  output: "@src",
                },
                url: {
                  selector: ".s-item__link",
                  output: "@href"
                }
              },
            },
          },
        },
      });

      const response = data.data;
      const invs = [];

      await response.map(async (item) => {
        if (item) {
          const inv: any = {
            price: await this.priceToStr(item.price),
            title: item.title,
          };
          if (item.link) {
            inv.link = item.link;
            inv.baseCurrency = "$";
            inv.date = new Date();
            inv.url = item.url
            inv.category = items
            inv.item = id
          }
          invs.push(inv);
        }
      });
      return invs.slice(0,100);
    } catch (error) {
      console.log(error)
      throw new Error("ScrapingBee Error: " + error.message);
    }
  }
  public async testing(id) {
    console.log('testing...')
    let items_data = await itemModel.find({});
    console.log('asdfasdf')
    console.log(items_data.length)
    items_data = items_data.filter(x=>x._id==id)
    if(items_data.length > 1 || items_data.length ==0){
      console.log('fail asdfss')
      console.log(items_data.length)
      return
    }
    console.log('whhhhaaat')
    // console.log(items_data)
    // console.log(items_data[0])
    const same_data = items_data.map((item) => {
      let item_keywords = item.item_keywords.filter(x=>x.toLowerCase() != item.item_title.toLocaleLowerCase())
      let title = item.item_title
      item_keywords.forEach(x=>title+=" "+x)
      return {
        title: title,
        item: item._id,
      }
    })


    const items = [];

    for (let i = 0; i < same_data.length; i += 1) {
      items.push(same_data.slice(i, i + 1));
    }
    let response;
    let offset = 0;

    _(items).each((item) => {
      // setTimeout(() => {
        item.forEach(async (item) => {

          if (item.title !== 'Shop on eBay') {
            // console.log(item.title)
            const data = await this.scrappingBeeDaily(item.title, item.item);

            // console.log(data)

            data.forEach(el => el.similarity = similarity(el.title,item.title))

            const average = await this.getAveragePrice(data);

            const median = await this.getMedianPrice(data);

            const {high, low} = await this.getHighLowPrice(data)
             
console.log('creating')
            return await dailyJob.create({
              _scrapId: item.item,
              median: median,
              average: average,
              same_data: data,
              lowest_price: low,
              highest_price: high,
            });
          }
          return response;
        });
      });
      // offset += 25000;
    // });
  }
}

export { Scrapping };

When executed, the console log states:

"C:Program Filesnodejsnode.exe" "C:UserslincoDocumentsNetBeansProjectspricer_collectiblesapp.js" "run" "build" "&&" "node" "./bin/www"
file:///C:/Users/linco/Documents/NetBeansProjects/pricer_collectibles/helper/scrapping/index.js:15
public async scrapCall(item) {
       ^^^^^

SyntaxError: Unexpected token 'async'
    at ModuleLoader.moduleStrategy (node:internal/modules/esm/translators:168:18)
    at callTranslator (node:internal/modules/esm/loader:279:14)
    at ModuleLoader.moduleProvider (node:internal/modules/esm/loader:285:30)

Node.js v21.7.1
Done.

tsconfig.json file is:


{
  "compilerOptions": {
    /* Basic Options */
    "target": "ESNEXT",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
    "module": "ESNext",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "lib": ["dom","ESNext"],                        /* Specify library files to be included in the compilation. */
    "allowJs": true,                          /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    "jsx": "react-native",                    /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "removeComments": true,                /* Do not emit comments to output. */
    "noEmit": true,                           /* Do not emit outputs. */
    // "incremental": true,                   /* Enable incremental compilation */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    "isolatedModules": true,                  /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
"types": [ "node" ],
"typeRoots": [ "../node_modules/@types" ],
    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    "moduleResolution": "Node",               /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    "allowSyntheticDefaultImports": true,     /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "resolveJsonModule": true                 /* Allows importing modules with a ‘.json’ extension, which is a common practice in node projects. */

    /* Source Map Options */
    // "sourceRoot": "./",                    /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "./",                       /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
    },
    "exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"],
    "ts-node": {
        "esm": true,
        "experimentalSpecifierResolution": "node"
    }
}

package.json file is:

{
  "name": "pricer-collectibles",
  "version": "0.0.4",
  "main": "app.js",
  "type": "module", 
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "cors": "2.8.5",
    "debug": "~2.6.9",
    "dotenv": "16.4.5",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "jade": "~1.11.0",
    "less-middleware": "~2.2.1",
    "mongoose": "8.2.2",
    "morgan": "~1.9.1",
    "window": "4.2.7",
    "winston": "3.12.0"
  },
  "scripts": {
    "start": "node app.js run build && node ./bin/www"
  }  
}

Why is the environment showing an error where I’m trying to call asynchronous functions?

Multiple Image style HTML

How can I make something like this in html? With the possibility of scrolling horizontally too?enter image description here

I did something like this for starting, but it isn’t the same ofc

    `<div class="slide-container">
      <img src="images/grad.jpeg"  width="400" 
           height="500"/>
        <img src="images/tml.jpeg" width="400" 
           height="500" />
         <img src="images/tml2.jpeg" width="400" 
            height="500" />

            </div>`

WebXR Google Tutorial – Why is Browser Unsupported?

Have been following this tutorial for building a simple AR application : https://codelabs.developers.google.com/ar-with-webxr#1

When I connect to the local webserver on my phone, and I try to run the step03 or step04 folder, I get the error that my browser is not supported.

However running this webpage provided by google: https://immersive-web.github.io/webxr-samples/ , states that my browser is supported and AR support is detected ? I can run all of the AR samples on the webpage ?

I am running this on a Google Pixel 6 on Google Chrome ?

The code for step03’s app.js is below:

/*
 * Copyright 2017 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Query for WebXR support. If there's no support for the `immersive-ar` mode,
 * show an error.
 */
(async function() {
  const isArSessionSupported = navigator.xr && navigator.xr.isSessionSupported && await navigator.xr.isSessionSupported("immersive-ar");
  if (isArSessionSupported) {
    document.getElementById("enter-ar").addEventListener("click", window.app.activateXR)
  } else {
    onNoXRDevice();
  }
})();

/**
 * Container class to manage connecting to the WebXR Device API
 * and handle rendering on every frame.
 */
class App {
  /**
   * Run when the Start AR button is pressed.
   */
  activateXR = async () => {
    try {
      // Initialize a WebXR session using "immersive-ar".
      this.xrSession = await navigator.xr.requestSession("immersive-ar");

      // Create the canvas that will contain our camera's background and our virtual scene.
      this.createXRCanvas();

      // With everything set up, start the app.
      await this.onSessionStarted();
    } catch(e) {
      console.log(e);
      onNoXRDevice();
    }
  }

  /**
   * Add a canvas element and initialize a WebGL context that is compatible with WebXR.
   */
  createXRCanvas() {
    this.canvas = document.createElement("canvas");
    document.body.appendChild(this.canvas);
    this.gl = this.canvas.getContext("webgl", {xrCompatible: true});

    this.xrSession.updateRenderState({
      baseLayer: new XRWebGLLayer(this.xrSession, this.gl)
    });
  }

  /**
   * Called when the XRSession has begun. Here we set up our three.js
   * renderer, scene, and camera and attach our XRWebGLLayer to the
   * XRSession and kick off the render loop.
   */
  async onSessionStarted() {
    // Add the `ar` class to our body, which will hide our 2D components
    document.body.classList.add('ar');

    // To help with working with 3D on the web, we'll use three.js.
    this.setupThreeJs();

    // Setup an XRReferenceSpace using the "local" coordinate system.
    this.localReferenceSpace = await this.xrSession.requestReferenceSpace('local');

    // Start a rendering loop using this.onXRFrame.
    this.xrSession.requestAnimationFrame(this.onXRFrame);
  }

  /**
   * Called on the XRSession's requestAnimationFrame.
   * Called with the time and XRPresentationFrame.
   */
  onXRFrame = (time, frame) => {
    // Queue up the next draw request.
    this.xrSession.requestAnimationFrame(this.onXRFrame);

    // Bind the graphics framebuffer to the baseLayer's framebuffer.
    const framebuffer = this.xrSession.renderState.baseLayer.framebuffer
    this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, framebuffer)
    this.renderer.setFramebuffer(framebuffer);

    // Retrieve the pose of the device.
    // XRFrame.getViewerPose can return null while the session attempts to establish tracking.
    const pose = frame.getViewerPose(this.localReferenceSpace);
    if (pose) {
      // In mobile AR, we only have one view.
      const view = pose.views[0];

      const viewport = this.xrSession.renderState.baseLayer.getViewport(view);
      this.renderer.setSize(viewport.width, viewport.height)

      // Use the view's transform matrix and projection matrix to configure the THREE.camera.
      this.camera.matrix.fromArray(view.transform.matrix)
      this.camera.projectionMatrix.fromArray(view.projectionMatrix);
      this.camera.updateMatrixWorld(true);

      // Render the scene with THREE.WebGLRenderer.
      this.renderer.render(this.scene, this.camera)
    }
  }

  /**
   * Initialize three.js specific rendering code, including a WebGLRenderer,
   * a demo scene, and a camera for viewing the 3D content.
   */
  setupThreeJs() {
    // To help with working with 3D on the web, we'll use three.js.
    // Set up the WebGLRenderer, which handles rendering to our session's base layer.
    this.renderer = new THREE.WebGLRenderer({
      alpha: true,
      preserveDrawingBuffer: true,
      canvas: this.canvas,
      context: this.gl
    });
    this.renderer.autoClear = false;

    // Initialize our demo scene.
    this.scene = DemoUtils.createCubeScene();

    // We'll update the camera matrices directly from API, so
    // disable matrix auto updates so three.js doesn't attempt
    // to handle the matrices independently.
    this.camera = new THREE.PerspectiveCamera();
    this.camera.matrixAutoUpdate = false;
  }
};

window.app = new App();

How to fix the error “Invalid authorization code” on the Spotify API?

Please help me understand why my Spotify authentication fails.

I have checked all the common errors:

  • The Redirect URI is set in the Spotify dashboard and consistent between api calls.

  • client_id, code_verifier and state are consistent between /authorize and /api/token calls.

Settings.tsx hosts the “connect to Spotify” button,
which sends the user to Spotify.authenticate().
Spotify.authenticate() redirects back to Settings.tsx, where a useEffect catches the spotify code in the URL, and call Spotify.fetchAccessToken(code).

/* Settings.tsx */
import YoutubeMusic from '../../api/providers/YoutubeMusic'
import ProviderButton from '../../components/ProviderButton/ProviderButton'
import './Settings.css'
import React, { useEffect, useState } from 'react'
import Spotify from '../../api/providers/Spotify'
import { useNavigate } from 'react-router-dom'
import ProvidersConfig from '../../api/ProvidersConfig'
import { useGoogleLogin } from '@react-oauth/google'

const Settings = (): JSX.Element => {
  const [isConnectedYoutubeMusic, setIsConnectedYoutubeMusic] = useState(ProvidersConfig.getAccessToken(YoutubeMusic.prefix) !== '')
  const [isConnectedSpotify, setIsConnectedSpotify] = useState(ProvidersConfig.getAccessToken(Spotify.prefix) !== '')
  const navigate = useNavigate()

  useEffect(() => {
    const spotifyURLChecks = async (): Promise<void> => {
      const urlParams = new URLSearchParams(window.location.search)

      const error = urlParams.get('error')
      if (error !== null) {
        Spotify.clean()
        setIsConnectedSpotify(false)
        navigate('/settings', { replace: true })
        throw new Error(`Error authenticating with Spotify: ${error}`)
      }

      const code = urlParams.get('code')
      if (code !== null) {
        const state = urlParams.get('state')
        if (state === null) {
          Spotify.clean()
          setIsConnectedSpotify(false)
          navigate('/settings', { replace: true })
          throw new Error('State mismatch error. Potential CSRF attack.')
        }
        try {
          await Spotify.fetchAccessToken(code)
          setIsConnectedSpotify(true)
          navigate('/settings', { replace: true })
        } catch (error) {
          Spotify.clean()
          setIsConnectedSpotify(false)
          throw new Error(`Error fetching access token: ${String(error)}`)
        }
      }
    }
    void spotifyURLChecks()
  }, [navigate])

  const youtubeLogin = useGoogleLogin({
    onSuccess: (tokenResponse): void => {
      ProvidersConfig.setAccessToken(YoutubeMusic.prefix, tokenResponse.access_token)
      setIsConnectedYoutubeMusic(true)
      // const response = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
      //   headers: { Authorization: `Bearer ${tokenResponse.access_token}` },
      // });
      // const userInfo = await response.json();

      // console.log(userInfo);
    },
    onError: errorResponse => { throw new Error(String(errorResponse)) }
  })

  return (
    <div>
      <h1>Connect to your music apps</h1>
      <div className="provider-buttons-container">
        <ProviderButton
          providerName={YoutubeMusic.name}
          isConnected={isConnectedYoutubeMusic}
          toggleConnect={async () => {
            if (ProvidersConfig.getAccessToken(YoutubeMusic.prefix) !== '') {
              YoutubeMusic.clean()
              setIsConnectedYoutubeMusic(false)
            } else {
              youtubeLogin()
              await YoutubeMusic.authenticate()
            }
          }}
        />
        <ProviderButton
          providerName={Spotify.name}
          isConnected={isConnectedSpotify}
          toggleConnect={async (): Promise<void> => {
            if (ProvidersConfig.getAccessToken(Spotify.prefix) !== '') {
              Spotify.clean()
              setIsConnectedSpotify(false)
            } else {
              await Spotify.authenticate()
            }
          }}
        />
      </div>
    </div>
  )
}

export default Settings
/* extract from Spotify.ts */
async authenticate (): Promise<void> {
  const APIKey = process.env.REACT_APP_SPOTIFY_API_KEY
  const scope = process.env.REACT_APP_SPOTIFY_SCOPE
  if ((APIKey == null) || (scope == null)) {
    throw new Error('Spotify API key or scope not set')
  }
  const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  const randomValues = crypto.getRandomValues(new Uint8Array(64))
  const randomString = randomValues.reduce((acc, x) => acc + possible[x % possible.length], '')

  const codeVerifier = randomString
  const data = new TextEncoder().encode(codeVerifier)
  const hashed = await crypto.subtle.digest('SHA-256', data)

  const codeChallengeBase64 = btoa(String.fromCharCode(...new Uint8Array(hashed)))
    .replace(/=/g, '')
    .replace(/+/g, '-')
    .replace(///g, '_')

  localStorage.setItem(`${this.prefix}_code_verifier`, codeVerifier)

  const state = new Uint32Array(1)
  window.crypto.getRandomValues(state)
  const stateString = state.join('')

  const authUrl = new URL('https://accounts.spotify.com/authorize')
  const params = {
    response_type: 'code',
    client_id: APIKey,
    scope,
    code_challenge_method: 'S256',
    code_challenge: codeChallengeBase64,
    redirect_uri: window.location.href.split('?')[0],
    state: stateString
  }

  console.log('auth params', params)
  authUrl.search = new URLSearchParams(params).toString()
  window.location.href = authUrl.toString()
}

async fetchAccessToken (code: string): Promise<void> {
  const APIKey = process.env.REACT_APP_SPOTIFY_API_KEY
  const codeVerifier = localStorage.getItem(`${Spotify.prefix}_code_verifier`)
  if (APIKey === undefined || codeVerifier === null) {
    throw new Error('Spotify API key or code verifier not set')
  }

  const payload = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: new URLSearchParams({
      client_id: APIKey,
      grant_type: 'authorization_code',
      code,
      redirect_uri: window.location.href.split('?')[0],
      code_verifier: codeVerifier
    }).toString()
  }

  console.log('code to token params', payload)

  const response = await fetch('https://accounts.spotify.com/api/token', payload)
  const data = await response.json()
  console.log('access token', data)
  if (!response.ok) throw new Error(String(data.error_description))

  ProvidersConfig.setAccessToken(this.prefix, String(data.access_token))
  localStorage.setItem(`${this.prefix}_refresh_token`, String(data.refresh_token))
  localStorage.setItem(`${this.prefix}_expiry_time`, (new Date().getTime() + data.expires_in * 1000).toString())
}

How to get a local file via fetch/axios?

For study reasons I need to use some of these network APIs like fetch or axios but to get a LOCAL file, so WITHOUT using fs module, or WITHOUT importing them.

I tried with both fetch and axios, but they have not implemented this “feature” to get a local file, also because I think it’s not so secure/safe.

fetch:

return new Promise((resolve, reject) => {
    fetch('file://users.js')
    .then(data => {
        console.log(data);
        resolve(data);
    })
    .catch(error => {
        console.error('Errore durante il recupero del file:', error);
        reject(error);
    });
});

I get this error:

cause: Error: not implemented… yet…

axios:

return new Promise((resolve, reject) => {
        axios.get('file://users.js')
        .then(response => {
            console.log(response.data);
            resolve(response.data);
        })
        .catch(error => {
            console.error('Errore durante il recupero del file:', error);
            reject(error);
        });
    });

I get this error:

generatedMessage: false,
code: ‘ERR_ASSERTION’,
actual: ‘file:’,
expected: ‘http:’,
operator: ‘==’

Is there some other network api that let me to that?

How can I use vue-i18n configuration inside and outside Vue components with Quasar?

colleagues. I’m trying to implement internationalization in Quasar, Vue 3 (Composition API), and vue-i18n, and I would like to have internationalization available throughout my application, even outside Vue components, but it always throws an error.

This is how I have set up i18n initialization for Quasar:

I saw the corresponding i18n = lang in a blog

import { boot } from 'quasar/wrappers'
import VueI18n from 'vue-i18n'
const { createI18n } = VueI18n
import messages from '../config/i18n'

let i18n

export default boot(({ app, Vue }) => {
  Vue.use(VueI18n)

  const lang = createI18n({
    locale: 'en',
    legacy: false,
    messages,
  })

  i18n = lang

  app.use(lang)
})

export { i18n }

In the following usage example, I import the configuration variable, but I have tried importing what the export default returns, but neither of the two options has worked for me:

import { i18n } from './../boot/i18n'

console.log(i18n)

export default {
  required: (value) => !!value || i18n.t('errors.rules.required'),
  email: (value) => {
    return (
      /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/.test(value) ||
      i18n.global.t('errors.rules.email')
    )
  },
  password: (value) => value.length >= 6 || i18n.t('errors.rules.password'),
  integer: (value) => /^d+$/.test(value) || i18n.t('errors.rules.integer'),
  float: (value, decimals) => {
    const regex = new RegExp(`^\d+\.\d{${decimals},}$`)
    return regex.test(value) || i18n.t('errors.rules.float', { decimals })
  },
  stringsOnly: (value) => !/d/.test(value) || i18n.t('errors.rules.stringsOnly'),
  min: (value, min) => value >= min || i18n.t('errors.rules.min', { min }),
  max: (value, max) => value <= max || i18n.t('errors.rules.max', { max }),
  minLength: (value, min) => {
    value = String(value)
    return value.length >= min || i18n.t('errors.rules.minLength', { min })
  },
  maxLength: (value, max) => {
    value = String(value)
    return value.length <= max || i18n.t('errors.rules.maxLength', { max })
  },
  isUrl: (value) => {
    return /^(https?|ftp)://[^s/$.?#].[^s]*$/.test(value) || i18n.t('errors.rules.isUrl')
  },
}

Yes, I made sure the path is correct, and it is. But when I try to translate the object, it fails.

This is the English language object (en):

export default {
  errors: {
    rules: {
      required: 'Required',
      email: 'Invalid email address',
      password: 'This password is weak',
      integer: 'Only integers are allowed',
      float: 'Only numbers with at least {decimals} decimals are allowed',
      stringsOnly: 'Only text strings are allowed, no numbers',
      min: 'Value must be greater than or equal to {min}',
      max: 'Value must be less than or equal to {max}',
      minLength: 'Value length must be greater than or equal to {min}',
      maxLength: 'Value length must be less than or equal to {max}',
      isUrl: 'Invalid URL',
    },
  },
}

This is the version I am using:

{
   "dependencies":{
      "@quasar/extras":"^1.16.9",
      "quasar":"^2.14.5",
      "vue":"^3.3.11",
      "vue-i18n":"^9.9.0"
   }
}

How can I use internationalization outside Vue components?

Please, I have tried several things, but nothing works.

login in nextjs

The backend of my site is written with Laravel. When I try with postman, everything is correct and I see the entered user information, but with next js, after entering the site (Auth::attempt(…)), the result is true, but I can’t see user information.
Even a cookie is set, but auth()->user() always returns null. And I also use sanctum Laravel package

axios component

import axios from 'axios';

export default axios.create({
  baseURL: 'http://api.lanext.test',
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
  },
  withCredentials: true
});

useAuth component

import useSWR from "swr";
import axios from '@/lib/axios'
import { useRouter } from "next/navigation";



export default function useAuth({} = {}) {

    const router = useRouter()

    const { data: user, error, mutate } = useSWR('/api/v1/admin',
        () => axios.get('/api/v1/admin').then(response => console.log(response.data.data, "ok"))
    )

    const csrf = () => axios.get('/sanctum/csrf-cookie')

    const login = async ({ setErrors, ...props }) => {

        axios.post('/api/v1/login', props)
            .then(
                () => mutate && router.push('/')
            )
            .catch(
                error => {
                    console.log(error)
                    // if (error?.response?.status !== 422) throw error
                    // setErrors(Object.values(error.response.data.errors).flat())
                }
            )
    }

    return {
        user,
        csrf,
        login
    }
}

login component

    const [submitting, setSubmitting] = useState(false);

    const {login} = useAuth();

    const handleSubmit = async (values, actions) => {
        setSubmitting(true);
        await login(values)
        setSubmitting(false);
    };

user component = It always returns null

const { user } = useAuth();

Tailwind color rendering issue when hiding desktop/mobile component

I’m currently working on a card component using Tailwind CSS (and Next JS) for both desktop and mobile views. To handle the responsive design, I’m hiding the desktop version on mobile and vice versa using Tailwind’s classes (hidden).

However, I’m encountering an issue where the colors are not being displayed correctly for an SVG inside the card component. Specifically, the correct color is only shown on the card that is being rendered first (mobile), on desktop color is not being displayed on screen.

const Card = ({ card }: IProps) => {
  return (
    <>
      <CardMobile card={card} />
      <CardDesktop card={card} />
    </>
  );
};

const CardDesktop = ({ card }: IProps) => {
  return (
    <li className="hidden sm:block">
      <PolygonIcon />
    </li>
  );
};

const CardMobile = ({ card }: IProps) => {
  return (
    <li className="sm:hidden flex flex-col gap-4">
      <PolygonIcon />
    </li>
  );
};

SVG has some linear gradient inside, so I’m guessing thats the problem:

<svg width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.0712 18.8489C14.9804 18.8489 18.96 14.8693 18.96 9.96006C18.96 5.05086 14.9804 1.07117 10.0712 1.07117C5.16198 1.07117 1.18229 5.05086 1.18229 9.96006C1.18229 14.8693 5.16198 18.8489 10.0712 18.8489Z" fill="url(#paint0_linear_5_1947)"/>
<path d="M12.6362 11.8822L15.1511 10.4301C15.2843 10.3532 15.3667 10.2102 15.3667 10.0563V7.15235C15.3667 6.99882 15.2839 6.85546 15.1511 6.77851L12.6362 5.32637C12.503 5.24943 12.3379 5.24979 12.2047 5.32637L9.68984 6.77851C9.55664 6.85546 9.47425 6.99882 9.47425 7.15235V12.3421L7.71071 13.3602L5.94716 12.3421V10.3056L7.71071 9.28755L8.87394 9.959V8.59288L7.92629 8.04592C7.86096 8.00817 7.7862 7.98821 7.71034 7.98821C7.63449 7.98821 7.55972 8.00817 7.49475 8.04592L4.97991 9.49806C4.84671 9.57501 4.76432 9.71801 4.76432 9.8719V12.7758C4.76432 12.9293 4.84707 13.0727 4.97991 13.1497L7.49475 14.6018C7.62759 14.6784 7.79309 14.6784 7.92629 14.6018L10.4411 13.15C10.5743 13.0731 10.6567 12.9297 10.6567 12.7762V7.58643L10.6887 7.56828L12.4203 6.56837L14.1838 7.58643V9.62292L12.4203 10.641L11.2589 9.97025V11.3364L12.2047 11.8826C12.3379 11.9592 12.503 11.9592 12.6362 11.8826V11.8822Z" fill="white"/>
<defs>
<linearGradient id="paint0_linear_5_1947" x1="-2.06658" y1="2.53231" x2="16.2861" y2="13.7633" gradientUnits="userSpaceOnUse">
<stop stop-color="#A229C5"/>
<stop offset="1" stop-color="#7B3FE4"/>
</linearGradient>
</defs>
</svg>

Does anyone know the solution to this problem and the reason why this is happening?