In Vue.js (v2), hoow do I prevent the sudden flash of old data, when there is only computed data?

I have a component that contains only computed data. When I navigate away from the page, and go back to the page with a different URL, the old data is displayed for a second while the new data is calculated. How do i prevent this flash of old data?

I tried

  • wrapping it a KeepAlive component with the key set to the id of a param
  • using vm.destroy()
  • toying around with other ways to delete the component and computed properties

How do I use something called Eruda in a web page?

I was wondering if there is a fix to my code, which should toggle a chrome inspect-like feature. However, everything I tried with a bookmarklet I found and made into formatted JS just didn’t work out. Here is the code I tried:

<html>
<head>
  <script src="http://cdn.jsdelivr.net/npm/eruda"></script>
</head>
<body>
  <button id="hi">Inspect</button>
<script>
  document.getElementById("hi").addEventListener("click",  function(){
  eruda.init();
});
</script>
</body>
</html>

If someone could help with my code in any way, I would appreciate the help. Thank you.

Error: Cannot find ffmpeg in firebase cloud function

i’m trying to compress some uploaded files to firebase storage .. using firebase cloud functions but it give me the error Error: Cannot find ffmpeg

here is my function :

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const ffmpeg = require("fluent-ffmpeg");
const ffmpegStatic = require("ffmpeg-static");
const axios = require("axios");

// const {onSchedule} = require("firebase-functions/v2/scheduler");

admin.initializeApp();

// Ensure fluent-ffmpeg uses the binary
ffmpeg.setFfmpegPath(ffmpegStatic.path);

const db = admin.firestore();
const bucket = admin.storage().bucket();
const fs = require("fs");
const downloadVideo = async (url, outputPath) => {
  const response = await axios.get(url, {responseType: "stream"});
  const writer = fs.createWriteStream(outputPath);
  response.data.pipe(writer);
  return new Promise((resolve, reject) => {
    writer.on("finish", () => resolve(outputPath));
    writer.on("error", reject);
  });
};

const compressVideo = (videoFullPath, outputFileName, targetSize) => {
  return new Promise((resolve, reject) => {
    ffmpeg.ffprobe(videoFullPath, (err, metadata) => {
      if (err) return reject(err);
      const duration = parseFloat(metadata.format.duration);
      const targetTotalBitrate =
      (targetSize * 1024 * 8) / (1.073741824 * duration);

      let audioBitrate =
      metadata.streams.find((s) => s.codec_type === "audio").bit_rate;
      if (10 * audioBitrate > targetTotalBitrate) {
        audioBitrate = targetTotalBitrate / 10;
      }

      const videoBitrate = targetTotalBitrate - audioBitrate;
      ffmpeg(videoFullPath)
          .output(outputFileName)
          .videoCodec("libx264")
          .audioCodec("aac")
          .videoBitrate(videoBitrate)
          .audioBitrate(audioBitrate)
          .on("end", resolve)
          .on("error", reject)
          .run();
    });
  });
};

const uploadVideoWithResumableUpload = (filePath, destinationBlobName) => {
  const blob = bucket.file(destinationBlobName);
  const options = {resumable: true, validation: "crc32c"};
  return blob.createWriteStream(options).end(fs.readFileSync(filePath));
};

exports.processLessonsOnDemand =
functions.https.onRequest({timeoutSeconds: 3600, memory: "2GB"}
    , async (context) => {
      console.log("Fetching lessons from Firestore...");
      const lessonsRef = db.collection("leassons");
      const lessonsSnapshot = await lessonsRef.get();

      if (lessonsSnapshot.empty) {
        console.log("No lessons found in Firestore.");
        return; // Exit if no lessons are available
      }

      const lessonDoc = lessonsSnapshot.docs[0]; // Get the first document
      const lessonData = lessonDoc.data();

      if (lessonData.shrinked) {
        console.log(
            `Skipping lesson ID ${lessonDoc.id} as it's already shrunk.`,
        );
        return; // Exit if the first lesson is already shrunk
      }

      const videoURL = lessonData.videoURL;
      if (!videoURL) {
        console.log(
            `No video URL for lesson ID: ${lessonDoc.id}. Skipping...`,
        );
        return; // Exit if no video URL is available
      }

      const tempVideoPath = "/tmp/temp_video.mp4";

      try {
        await downloadVideo(videoURL, tempVideoPath);

        const targetSize = (fs.statSync(tempVideoPath).size * 0.30) / 1024;
        const outputCompressedVideo = `/tmp/compressed_${lessonDoc.id}.mp4`;

        await compressVideo(tempVideoPath, outputCompressedVideo, targetSize);

        await uploadVideoWithResumableUpload(
            outputCompressedVideo,
            `compressed_videos/compressed_${lessonDoc.id}.mp4`,
        );

        const newVideoURL = `https://storage.googleapis.com/${bucket.name}/compressed_videos/compressed_${lessonDoc.id}.mp4`;

        const oldVideoPath = videoURL.replace(`https://storage.googleapis.com/${bucket.name}/`, "");
        const oldBlob = bucket.file(oldVideoPath);
        await oldBlob.delete();

        await lessonsRef.doc(lessonDoc.id).update({
          videoURL: newVideoURL,
          shrinked: true,
        });

        console.log(`Processed lesson ID: ${lessonDoc.id}`);
        fs.unlinkSync(tempVideoPath); // Clean up temporary files
        fs.unlinkSync(outputCompressedVideo); // Clean up compressed file
      } catch (error) {
        console.error(`Error processing lesson ID ${lessonDoc.id}:`, error);
      }
    });


Audio Module Not Enabled Error in Firefox with Zoom Video SDK UI Toolkit

I’m working with the Zoom Video SDK (JavaScript) and specifically using the Video SDK UI Toolkit (following the example from the Zoom SDK UI Toolkit GitHub repository).

Description
I’m encountering an issue with audio in Firefox only. The setup and code work correctly on all other major browsers, but when using Firefox, attempting to start audio fails with an error. The error is reproducible both in my application and on Zoom’s own UI Toolkit Demo site.

Error
When trying to start audio, the following error message appears:

Audio: The operation is invalid, perhaps caused by duplicated operations

And in the console, more details are provided:

start audio error Object { type: "INVALID_OPERATION", reason: "Module:audio is not enabled" }

Troubleshooting Routes

  1. I confirmed that this issue does not occur on other browsers like Chrome or Edge.
  2. I followed the sample application exactly as provided in Zoom’s GitHub repository.
  3. I also tested on the official Zoom UI Toolkit Demo site (videosdk.dev/uitoolkit), and the same issue occurs on Firefox when joining a session with fictional data.

How to Reproduce

  1. Use Firefox (last version or earlier) as the browser. (On windows or MacOs)
  2. Open the Zoom Video SDK UI Toolkit Demo.
  3. Join a session using any fictitious data to authenticate.
  4. Attempt to start audio within the session.
  5. The above error should appear, preventing audio from working as expected.

Thank you for any guidance!

New environment variables reading as empty string in Vite project

I have set up a Vite project with an .env file to read some environment variables, but some environment variables I create for my machine appear as an empty string.

I have created a new environment variable in my terminal: export VITE_TEST="TESTING"

Printed it out to confirm it was set: echo $VITE_TEST // Output: TESTING as expected

I have set up an .env file to read this new env var:

VITE_ENV_TEST=$VITE_TEST

When I print out this env var I defined in my .env file::

App.tsx

...
function App() {
    const [count, setCount] = useState(0);
    const test = import.meta.env.VITE_ENV_TEST;
    console.log(test);

   return (
      <P>{test}</p>
   )
}
...

The output in an empty string.

However when I update my .env file to use a system env var such as $HOME:

.env

VITE_ENV_TEST=$HOME

It correctly prints out my home directory.

Does anyone know why the new environment variable I created would not print correctly while $HOME does?

Nuxt Content – 500 Failed to fetch dynamically imported module: http://localhost:3000/_nuxt/pages/index.vue

I have an error when I go to a markdown document from my main page, and I click on the arrow to go back in my browser.

It notes me this error:

500
Failed to fetch dynamically imported module: http://localhost:3000/_nuxt/pages/index.vue

Here is the full error:

nuxt] error caught during app initialization H3Error: 
Failed to fetch dynamically imported module: http://localhost:3000/_nuxt/pages/index.vue
Caused by: TypeError: Failed to fetch dynamically imported module: http://localhost:3000/_nuxt/pages/index.vue

Here is my […slug].vue code:

<template>
    <main>
        <div>
            <content-renderer :value="prodData" />
        </div>
    </main>
</template>

<script lang="ts" setup>
    import { queryContent, useAsyncData, useRoute } from '#imports';

    const route = useRoute();
    const path = route.path;

    const { data } = await useAsyncData('content-data', () =>
        queryContent(path).findOne(),
    );

    const prodData = data.value;
</script>

Here is my index.vue code:

<template>
    <AllPage>
         <Projects />
    </AllPage>
</template>

<script lang="ts" setup></script>
<style scoped></style>

this is the Projects component:

<template>
    <div class="d-flex flex-column h-100 ga-10">
        <Card
            v-for="doc in docs"
            :key="doc._path"
            :description="doc.description"
            :image="doc.firstImage"
            :path="doc._path"
            :title="doc.title"
        />
    </div>
</template>

<script lang="ts" setup>
    import { queryContent, useAsyncData } from '#imports';

    function extractFirstImage(content) {
        if (!content || !content.children) return null; // Checks that the content exists and has children

        // Recursively searches through children to find the first image
        for (const node of content.children) {
            if (
                node.type === 'element' &&
                node.tag === 'img' &&
                node.props &&
                node.props.src
            ) {
                return node.props.src; // Returns the URL of the first image found
            }

            // If the child has children, call the function recursively
            if (node.children) {
                const image = extractFirstImage(node);
                if (image) return image;
            }
        }
        return null; // No image found
    }

    const { data } = await useAsyncData('projects', () =>
        queryContent('/projects').find(),
    );

    const docs = data.value.map((doc) => ({
        ...doc,
        firstImage: extractFirstImage(doc.body), // Extracts the first image
    }));
</script>

<style scoped>
    @import 'assets/css/dark-theme-content.css';
</style>

This is the Card component :

<template>
    <v-card :href="path" class="project-card mx-auto rounded-lg" width="300px">
        <div class="img-container pa-3 w-100">
            <img
                v-if="displayImage"
                :src="images[`${displayImage}`]"
                alt="Image du document"
                class="card-img w-100 h-100 rounded-lg"
            />
        </div>

        <v-card-title class="card-title">{{ title }}</v-card-title>
        <v-card-subtitle class="card-description pb-3"
            >{{ description }}
        </v-card-subtitle>
    </v-card>
</template>
<script lang="ts" setup>
    import { filename } from 'pathe/utils';

    const props = defineProps({
        title: String,
        description: String,
        image: String,
        path: String,
    });

    console.log(props.path);

    const displayImage = props.image
      ?.replace('../../assets/img/content/', '')
      .replace(/.(png|jpe?g|gif|bmp|webp)$/gi, '');

    // Import all image files from the @/assets/img/content folder
    const glob = import.meta.glob(`@/assets/img/content/*`, {
        eager: true, // Immediately loads images to make them available as soon as the component is rendered
    });

    // Creates an images object where each key is a filename, and each value is the image URL
    const images = Object.fromEntries(
        Object.entries(glob).map(([key, value]) => [filename(key), value.default]),
    );
</script>
<style scoped></style>

This is my nuxt configuration file:

import vuetify, { transformAssetUrls } from 'vite-plugin-vuetify';

export default defineNuxtConfig({
  css: ['~/assets/css/style.css'],
  compatibilityDate: '2024-04-03',
  devtools: { enabled: true },
  app: {
    head: {
      meta: [
        { name: 'viewport', content: 'width=device-width, initial-scale=1' }
      ],
      link: [
        {
          rel: 'stylesheet',
          href: 'https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/3.0.1/modern-normalize.min.css'
        },
        {
          rel: 'preconnect', href: 'https://fonts.googleapis.com'
        },
        { rel: 'preconnect', href: 'https://fonts.gstatic.com' },
        {
          href: 'https://fonts.googleapis.com/css2?family=Ubuntu:ital,wght@0,300;0,400;0,500;0,700;1,300;1,400;1,500;1,700&display=swap',
          rel: 'stylesheet'
        }
      ],
      script: [
        {
          src: 'https://cdn.anychart.com/releases/v8/js/anychart-base.min.js'

        },
        {
          src: 'https://cdn.anychart.com/releases/v8/js/anychart-tag-cloud.min.js'
        }
      ]
    }
  },
  build: {
    transpile: ['vuetify']
  },
  modules: [
    (_options, nuxt) => {
      nuxt.hooks.hook('vite:extendConfig', (config) => {
        // @ts-expect-error
        config.plugins.push(vuetify({ autoImport: true }));
      });
    },
    '@nuxt/content'
  ],/*
  content: {
    documentDriven: true
  }, */
  vite: {
    vue: {
      template: {
        transformAssetUrls
      }
    }
  },
  runtimeConfig: {
    public: {
      imageBasePath: '~/assets/img'
    }
  }
});

Using window objects to define javascript variables for Chrome extension

I am trying to create a dynamic overlay for a browser game that will update team information as it updates within the game. The function that is used in the game to do so is:

updateGameInfo()

I have the HTML/CSS/JS defined, so for team member name, it would be

const memberName = document.getElementById("name")

And I would like to change it after updateGameInfo() is complete to be

memberName.textContent = window.gameInfo.party[0].name

How can I create this function to automatically run after updateGameInfo() and get the relevant information to change the variables?

Hamburger button is not expanding when pressed

On the mobile view, I turn my nav bar into a collapsible menu, however for some reason the javascript code is not working.

const hamburger = document.getElementById("hamburger");
const navLinks = document.getElementById("nav-links");
const profileIcon = document.querySelector(".profile-icon");

hamburger.addEventListener("click", () => {
 console.log("Hamburger clicked!"); 
 navLinks.classList.toggle("active");
 profileIcon.classList.toggle("active");
});   

Here is the css for creating the three line menu button:


.hamburger {
  display: none; /* Hidden by default; shown on mobile */
  cursor: pointer;
  flex-direction: column;
  gap: 0.3rem;
}

.hamburger span {
  display: block;
  width: 24px;
  height: 3px;
  background-color: #ffffff;
  transition: transform 0.3s ease;
}

/* Responsive Styles for Mobile */
@media screen and (max-width: 768px) {
 

  .hamburger {
      display: flex; /* Show hamburger on mobile */
  } 
}

Here is the website in question: https://enmasantos.github.io/vitality_vista/

Withdrawal BYBIT API

I’m trying to withdraw funds from my wallet via the BYBIT API, but it ends with an error:

{
  rateLimitApi: undefined,
  retCode: 131002,
  retMsg: 'Withdraw address chain or destination tag are not equal',
  result: {},
  retExtInfo: {},
  time: 1730925459032
}

Mine code:

const { RestClientV5 } = require('bybit-api');

const client = new RestClientV5({
  testnet: false,
  key: 'api_key', // stub, for example
  secret: 'secret_key', // stub, for example
});

client
  .submitWithdrawal({
    coin: 'USDT',
    chain: 'ETH',
    address: '0xfa3c24a644b03d20833866f59c539ec4794891ab',
    amount: '10',
    timestamp: Date.now(),
    forceChain: 0,
    accountType: 'FUND', // FUND, UNIFIED
  })
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.error(error);
  });

Here is an example from the documentation:

Documentation: https://bybit-exchange.github.io/docs/v5/asset/withdraw

const { RestClientV5 } = require('bybit-api');

const client = new RestClientV5({
  testnet: true,
  key: 'apikey',
  secret: 'apisecret',
});

client
  .submitWithdrawal({
    coin: 'USDT',
    chain: 'ETH',
    address: '0x99ced129603abc771c0dabe935c326ff6c86645d',
    amount: '24',
    timestamp: 1672196561407,
    forceChain: 0,
    accountType: 'FUND',
  })
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.error(error);
  });

Response example (from docs):

{
    "retCode": 0,
    "retMsg": "success",
    "result": {
        "id": "10195"
    },
    "retExtInfo": {},
    "time": 1672196571239
}

How can this problem be solved? Thanks in advance for your advice, ladies and gentlemen!

I tried changing networks: TON, TRX, but still the same error…

Converting axios to useFetch Nuxt 3

The problem i am encountering is that i started a project , and i build the entire API call using axios. Since i am in Nuxt 3 , i am trying to convert it to useFetch. I am encountering a problem , and one is that when i reload the page , the data is not fetched again when i am using useFetch.

This is my ApiService.js (converted to useFetch) :

import { useUserStore } from "~/store/user";
import qs from "qs";

class ApiService {
    constructor(baseURL) {
        this.baseURL = baseURL;
    }

    async apiRequest(method, url, data = null, options = {}, returnData) {
        const store = useUserStore();
        const requestUrl = `${this.baseURL}/${url}`;
        const params = options.params ? `?${qs.stringify(options.params, { arrayFormat: 'comma' })}` : '';

        try {
            // Make the request using useFetch
            const { data: responseData, error, status } = await useFetch(`${requestUrl}${params}`, {
                method,
                body: data,
                credentials: options.withCredentials ? 'include' : 'omit',
                headers: {
                    'Content-Type': 'application/json',
                },
            });

            if (error.value) {
                // Handling specific error statuses based on error.value
                const errorStatus = error.value.response?.status || 500;
                const errorReturnObj = {
                    status: errorStatus,
                    message: error.value.response?._data || error.value.message,
                };

                // Handling specific error codes
                if (errorStatus === 401) {
                    console.error("Expired token");
                    store.showSnackbar("Token-ul a expirat/Access neautorizat!");
                    navigateTo('/user/logout');
                } else if (errorStatus === 400) {
                    return returnData ? errorReturnObj : -2;
                } else if (errorStatus === 515) {
                    return returnData ? errorReturnObj : -3;
                } else if (errorStatus === 404) {
                    return returnData ? errorReturnObj : -4;
                }
                console.error(error.value.message || error.value.response?.status);
                return 0;
            }

            console.log("data parameter",data)
            console.log("responseData",responseData.value)


            // Success response handling
            const returnObj = {
                status: status,
                message: responseData.value
            };

            if (returnData === null) {
                return returnObj;
            }
            return returnData ? responseData.value : 1;

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

    get(url, returnData = false, isBlob = false, isAnonymous = false, params = {}) {
        const options = {
            params,
            ...(isAnonymous ? { withCredentials: false } : { withCredentials: true }),
        };
        return this.apiRequest("GET", url, null, options, returnData);
    }

    post(url, data, returnData = false, isAnonymous = false) {
        const options = isAnonymous ? {} : { withCredentials: true };
        return this.apiRequest("POST", url, data, options, returnData);
    }

    put(url, data, returnData = false, isAnonymous = false) {
        const options = isAnonymous ? {} : { withCredentials: true };
        return this.apiRequest("PUT", url, data, options, returnData);
    }

    delete(url, data = null, returnData = false, isAnonymous = false) {
        const options = isAnonymous ? {} : { withCredentials: true };
        return this.apiRequest("DELETE", url, data, options, returnData);
    }
}

export default ApiService;

This is Products.js :

import ApiService from "./ApiService"

class ProductsService extends ApiService{
    constructor(){
        super("http://localhost:5043/api/product")
    }

    /**
     * @param {int?} pageNumber [The page number of with the current products]
     * @param {Array<string>} productTypes [The array of product types to filter]
     * @param {Array<string>} colorTypes [The array of color types to filter]
     * @param {Array<string>} widthRange [The array of product dimensions width to filter]
     * @param {Array<string>} heightRange [The array of product dimension height to filter]
     * @param {Array<int>} priceRange [The array of product price to filter]
     * @param {boolean} reverseFace [The type of reverse face (true or false)]
     * @returns {List} [The list with a limit of 15 products]
     */
    
    getProductsForUsers(pageNumber , productTypes , colorTypes, productDimensions, productPrice , productReverseFace, currency){
       
        const params = {
            productTypes,
            colorTypes,
            productDimensions,
            productPrice,
            productReverseFace
        }
        return this.get(`paginated/${pageNumber}/${currency}` , true , false , true , params) 
    }

    /**
     * @param {NONE}
     * @returns {Object
     * {
     *      filterColors : IMutableHashSet(ReadOnly),
     *      filterProductTypes : IMutableHashSet(ReadOnly)
     * }}
     *  [The class with the filter options - color and productTypes]
     */
    
    getFilterOptions(currency = "RON"){
        return this.get(`filterOptions/${currency}` , true , false , true) 
    }

    /**
     * @param {String} productCode [The product code]
     * @param {String} productType [The type of the product]
     * @param {String} currency [The current currency : RON or EUR]
     * 
     * @returns {Object{
     *      - integer : 1 or 0 (depends on succes)
     *      - productData : class (null if product has not been found )
     * }}
     */

    getProductData(productCode , productType, currency){
        console.log('IN PRODUCTS.JS',this.get(`${productCode}/${productType}/${currency}` , true , false, true))
        return this.get(`${productCode}/${productType}/${currency}` , true , false, true)
    }

    /**
     * @param {FormData} form [The form with the review info]
     * @returns {KeyValuePair<int,string>} [The info about the succefullness of the request]
     */

    postProductReview(form){
        return this.post('postReview' , form , false , false);
    }
}

export default new ProductsService()


And here i call getProductData in my .vue file:


const getProductData = async () => {
    const response = await productService.getProductData(productCode,productType , selectedCurrency.value);
    console.log("IN GET PRODUCT DATA" , response)
    if(response === -4){
        navigateTo(localePath('/error/notFound'))
    }else if(response === -2){
        navigateTo(localePath('/error/generalError'))
    }

    Object.assign(product.value , response)
    console.log(product.value)
    if (product.value.culoriProdus && product.value.culoriProdus.length > 0) {
        // Set the default color as the first color available
        selectedColor.value = {
           name : product.value.culoriProdus[0].numeCuloareDto,
           colorCode: product.value.culoriProdus[0].codCuloareDto
        };
        activeButtonColors.value = 0;
        filterImagesByColor(selectedColor.value.name);
    }
    if(product.value.dimensiuniProdus && product.value.dimensiuniProdus.length > 0){
        dimensionsLength.value = product.value.dimensiuniProdus.length;
        selectedDimension.value = { 
            width: product.value.dimensiuniProdus[0].lungimeDto,
            height: product.value.dimensiuniProdus[0].latimeDto,
            price :  product.value.dimensiuniProdus[0].pretDto,
            priceDiscount:  product.value.dimensiuniProdus[0].pretRedusDto
        }
        activeButtonDimensions.value = 0;
    }
    if(product.value.reviewsProdus){
        reviewsLen.value = product.value.reviewsProdus.length
    }
}

/* missing code */

onBeforeMount(async () => {
    getCurrentLocale()
   await getProductData()
  
})
</script>

multiple incarnations of “same” variable in JS local scope – chrome debugger

Have a look a this loop in javascript, and what is showing in the debugger. for some reason there are 4 occurrences of the item variable, however there should be only 1 (unless it seems I’m missing something).

You can see on the right side filteredAttributes.values is an array with 1 object. It gets sorted and mapped, the first time into the inner loop, when setting a breakpoint reveals unexpected values.

What is going on here?!

multiple variable occurrences

{filteredAttribute?.values.length > 0 ? (
  filteredAttribute?.values
    .sort((a, b) => a.fmOrder - b.fmOrder)
    .map((item, i) => {

PayPal Button Not Responding After Clicking “Pay” – React Integration

I’m integrating PayPal into my React app using the @paypal/react-paypal-js library, and I’m encountering an issue. When I click the “Pay” button after entering all payment details, nothing happens—the payment process doesn’t proceed, and no confirmation or error message appears.

The rest of the PayPal setup, including creating the order, works without issues. However, the final “Pay” button click doesn’t trigger any action, and there are no visible errors. I’ve tried several troubleshooting steps, but I’m not sure what else to check.

Here’s the code for my PayPal component:

import { clientId, ROOT_URL } from "../utils/constants";
import { useState } from "react";

const PayPalComponent = ({ amount, handlePayment }) => {
const [orderId, setOrderId] = useState(null);

return (
  <PayPalScriptProvider options={{ "client-id": clientId, currency: "USD", components: "buttons,funding-eligibility" }}>
    <div>
      <h2>Complete Payment</h2>
      <PayPalButtons
        fundingSource={FUNDING.CARD}
        createOrder={async (data, actions) => {
          try {  
            const order = await fetch(
              `${ROOT_URL}/paypal/create-order`,
              {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify({ amount: amount }),
              }
            );  
            const result = await order.json();
            if (result.status === "success") {
              setOrderId(result.data.id);
              return result.data.id;
            }
          } catch (error) {
            console.error("Error creating order:", error);
            throw error;
          }
        }}
        onApprove={async (data, actions) => {
          try {
            if (orderId) {
              const order = await fetch(
                `${ROOT_URL}/paypal/capture-order/${orderId}`,
                {
                  method: "POST",
                  headers: {
                    "Content-Type": "application/json",
                  },
                }
              );  
              const result = await order.json();
              console.log(result, "Results");
              if (result.status === "success") {
                handlePayment(true, orderId, data.payerID);
              }
            }
          } catch (error) {
            console.error("Error capturing order:", error);
            throw error;
          }
        }}
        onError={(err) => {
          console.error("Payment Error:", err);
        }}
        style={{ layout: "vertical" }}
        funding={{ disallowed: [FUNDING.PAYPAL] }}
      />
    </div>
  </PayPalScriptProvider>
);
};

export default PayPalComponent;```


Troubleshooting Steps I’ve Tried
Checked Browser Compatibility:

I tried different browsers and cleared the cache and cookies to ensure there were no issues caused by outdated or cached data.
I also checked that my browser's pop-up blocker was disabled to ensure that PayPal could open necessary pop-ups for payment.
Checked Developer Console for JavaScript Errors:

There are no JavaScript errors in the console when I click the "Pay" button, which makes it difficult to debug the issue.
PayPal Account Settings:

Verified that my PayPal account is active and that it supports the currency being used in the app.
Tried Different Devices and Browsers:

Tested on multiple devices and browsers to ensure the issue wasn't device-specific, but the problem persists.
Updated PayPal SDK:

I confirmed that my @paypal/react-paypal-js package is up-to-date to avoid issues due to outdated code.
Checked Network and Internet Connection:

Verified that the internet connection is stable during testing, so network interruptions are unlikely to be the cause.

Cannot find module or its corresponding type declarations in a deno project

I recently started exploring deno. I wanted to run a script and write data into a file and save it in a folder. In that case I used fs-extra. Even if I install the package, i am getting the error “Cannot find module ‘npm:fs-extra’ or its corresponding type declarations

Installation command I used:
deno install npm:fs-extra

deno.json file:

  "tasks": {
    "dev": "deno run --watch main.ts"
  },
  "imports": {
    "@std/assert": "jsr:@std/assert@1",
    "fs-extra": "npm:fs-extra@^11.2.0",
    "mongodb": "npm:mongodb@^6.10.0"
  }
}

I imported it to the main.ts like this:
import fs from 'npm:fs-extra';

I tried using this way as well:
import fs from 'fs-extra';

But neither way worked out

Variables in JavaScript

I’m just wondering if it’s possible to exclude the “var” part when creating a variable in JavaScript. For example if I were to type “var greeting = hi” could I just say “greeting = hi” like in Python?
Thanks.