Yandex Metrika Integration Issue

The tracker starts sending data, but I am facing an issue where it only records visits to the main page.

Questions:

How can I ensure that Yandex Tracker sends data for all pages in my ReactJS application, not just the main page?
Are there additional configurations or methods I need to implement for tracking page views in a single-page application (SPA)?
Any guidance or insights would be greatly appreciated.

I attempted to resolve this issue by writing a tracking function and implementing it in my App.tsx, but it did not yield the desired effect. Additionally, I tried adding it to the innerHTML through a function, but this approach also did not solve the problem. I apologize if I have expressed myself incorrectly, as I primarily focus on back-end development. However, our front-end team has been unable to find a solution, which has resulted in this task being assigned to me.

I attempted to resolve this issue by writing a tracking function and implementing it in my App.tsx, but it did not yield the desired effect. Additionally, I tried adding it to the innerHTML through a function, but this approach also did not solve the problem. I apologize if I have expressed myself incorrectly, as I primarily focus on back-end development. However, our front-end team has been unable to find a solution, which has resulted in this task being assigned to me.


<script type="text/javascript">
    (function (m, e, t, r, i, k, a) {
      m[i] = m[i] || function () { (m[i].a = m[i].a || []).push(arguments) };
      m[i].l = 1 * new Date();
      for (var j = 0; j < document.scripts.length; j++) {
        if (document.scripts[j].src === r) { return; }
      }
      k = e.createElement(t), a = e.getElementsByTagName(t)[0], k.async = 1, k.src = r, a.parentNode.insertBefore(k, a);
    })(window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");

    ym(95474831, "init", {
      clickmap: true,
      trackLinks: true,
      accurateTrackBounce: true,
      webvisor: true,
      ecommerce: "dataLayer"
    });
  </script>
<noscript>
    <div><img src="https://mc.yandex.ru/watch/xxxxxxx" style="position:absolute; left:-9999px;" alt="" /></div>
  </noscript>

The image does not return to previous state after shrinking and expanding viewport again in Cropper.js

Officially Cropper.JS supports the resizing of the window (even by default), however when expand the viewport after shrinking, more than half of image is moving outside of bounds of initial canvas. Unfortunately, the images uploader has not allowed me to upload the GIF for the multiple reasons, so I’ll upload some frames instead:

Before viewport shrinking:

enter image description here

(Image by freepik)

After viewport shrinking:

enter image description here

After viewport expanding:

enter image description here

I am not sure this is the bug of Cropper.js, maybe it is just wrong configuration. My configuration is:

new CropperJS(
  this.imageElement,
  {
    aspectRatio: 1,
    viewMode: 1,
    responsive: true, // it is "true" by default but...
    movable: false,
    rotatable: false,
    scalable: false,
    zoomable: false,
    minCropBoxWidth: 128,
    minContainerHeight: 128,
    modal: false,
    highlight: false,
    background: false
  }
);

How to retain dynamically loaded scripts and page state on full page reload in a custom JavaScript SPA?

I’m maintaining a legacy web application that emulates Single Page Application (SPA) behavior using a custom JavaScript function called loadOnPage. This function dynamically loads external pages and replaces the element’s content with the id “content”, allowing us to switch between pages without reloading the entire page.

Here is a simplified version of the loadOnPage function:

async function loadOnPage(page, options = {}) {
    // Default options
    options = {
        contentDiv: "content",
        saveHistory: true,
        ...options
    };
    const { contentDiv, saveHistory } = options;

    // Prepare FormData for POST request
    const fd = new FormData();
    fd.append("PAGINA", page);

    try {
        // Fetch page content via AJAX
        const response = await axios.post("/lop.php", fd);

        if (response.data.status !== 200) {
            throw new Error(`Failed to load page: ${response.data.status}`);
        }

        // Replace content and execute scripts
        document.getElementById(contentDiv).innerHTML = response.data.detail.content;
        execAllScriptTags(contentDiv);

        // Update history state
        if (saveHistory) {
            saveWindowHistory({ page, options });
        }

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

// Helper to execute scripts within loaded content
function execAllScriptTags(containerId) {
    const container = document.getElementById(containerId);
    const scripts = container.querySelectorAll("script");
    scripts.forEach((script) => {
        const newScript = document.createElement("script");
        if (script.src) {
            newScript.src = script.src;
        } else {
            newScript.textContent = script.textContent;
        }
        script.parentNode.replaceChild(newScript, script);
    });
}

// Function to save history state
function saveWindowHistory(params = {}) {
    const { page } = params;
    window.history.pushState(params, "", `/${page}/`);
}

// Event listener for page load to handle browser refresh
window.addEventListener("load", function () {
    if (window.history.state) {
        reloadWithStateHistory();
    }
});

// Function to reload content based on history state
function reloadWithStateHistory() {
    const { state } = window.history;
    if (state) {
        const { page, options } = state;
        return loadOnPage(page, { ...options, saveHistory: false });
    }
    window.location.reload();
}

The Problem:

When a user refreshes the page using the browser’s reload button, the page loses access to the scripts and functions that were dynamically loaded via loadOnPage. This results in broken functionality because those scripts are essential for the page to work correctly.

What I’ve Tried:

  • Storing State: Using sessionStorage or cookies to store the page state, but this doesn’t solve the issue of missing scripts and functions after a reload.
  • Dynamic Script Loading on Reload: Attempted to inject scripts dynamically during page load based on the current URL or history state, but this approach is complex and hard to maintain.
  • Including All Scripts Globally: Including all possible scripts in the initial page load is not feasible devido a efeitos colaterais indesejados e problemas de desempenho.

Constraints:

  • No Modern Frameworks: Due to project constraints, I cannot use frameworks like React or Angular.
  • Legacy System: Significant architectural changes are not possible.
  • Deep Linking: The application needs to support deep linking for bookmarking and direct access to specific pages.
  • Page-Specific Scripts: Loaded pages may include scripts that are only relevant to that page and may have side effects.

My Question:

Given these constraints, how can I ensure that when a user refreshes the page, all necessary scripts and functions are reloaded so that the page functions correctly, just as if it had been loaded via loadOnPage?

Additional Information:

  • We use window.history.pushState to manage navigation history.
  • The execAllScriptTags function executes scripts within the dynamically loaded content.
  • The issue specifically arises because scripts loaded dynamically are not persistent across browser refreshes.

I would greatly appreciate any guidance or solutions on how to handle the reloading of necessary scripts and functions upon a browser refresh in this legacy system.

How to use date-fns instead of dayjs when creating custom calender header for MUI Date Picker

I am trying to add a custom calender header for the MUI Date Picker component but am running into troubles when changing the default dayjs type to date-fns.

Here is my Date Picker component and custom header component.

<StyledDatePicker
            open={open}
            value={date}
            onChange={(newValue) => onChange(newValue as Date)}
            slots={{
              openPickerIcon: CalendarIcon,
              shortcuts: CustomRangeShortcuts as any,
              calendarHeader: CustomCalendarHeader,
            }}
            slotProps={{
              actionBar: {
                actions: ['today'],
              },
              shortcuts: {
                items: MUI_DATE_PICKER_SHORTCUTS,
              },
              openPickerButton: {
                onClick: iconButtonOnClick,
              },
              textField: { variant: 'filled', onFocus: inputFocused, onBlur: close },
            }}
          />
const CustomCalendarHeader = (props: PickersCalendarHeaderProps<Date>) => {
  const { currentMonth, onMonthChange } = props;

  const selectNextMonth = () => onMonthChange(currentMonth.add(1, 'month'), 'left');
  const selectNextYear = () => onMonthChange(currentMonth.add(1, 'year'), 'left');
  const selectPreviousMonth = () => onMonthChange(currentMonth.subtract(1, 'month'), 'right');
  const selectPreviousYear = () => onMonthChange(currentMonth.subtract(1, 'year'), 'right');

  return (
    <CustomCalendarHeaderRoot>
      <Stack spacing={1} direction="row">
        <IconButton onClick={selectPreviousYear} title="Previous year">
          <KeyboardDoubleArrowLeftIcon />
        </IconButton>
        <IconButton onClick={selectPreviousMonth} title="Previous month">
          <ChevronLeft />
        </IconButton>
      </Stack>
      <Typography variant="body2">{currentMonth.format('MMMM YYYY')}</Typography>
      <Stack spacing={1} direction="row">
        <IconButton onClick={selectNextMonth} title="Next month">
          <ChevronRight />
        </IconButton>
        <IconButton onClick={selectNextYear} title="Next year">
          <KeyboardDoubleArrowRightIcon />
        </IconButton>
      </Stack>
    </CustomCalendarHeaderRoot>
  );
}

The custom header prop type in the example uses Dayjs (PickersCalendarHeaderProps<Dayjs>) but I want to use date-fns, how can I implement this using date-fns instead of dayjs?

Declaring a Javascript Array containing Objects

Is there a way I can declare an object array like this [{}]?

So in the following Code:

 club = {};
 club.player_DB                 = [{}]; // Player Database;
        
 // club.player_DB[0] = {};
 club.player_DB[0].code         = 44;
 console.log(club.player_DB[0].code);
            
 // club.player_DB[1] = {};
 club.player_DB[1].code         = 21;
        
 console.log(club.player_DB[0].code+" "+club.player_DB[1].code);    

I have declared the club.playerDB with [{}], i.e an array that contains an object;
Or do I have to declare the object on each array (commented out {} declaration) for each player.

Thanks.

Align symbols in similar lines into columns with ESLint

How to configure ESLint Stylistic for JavaScript to ignore or even force alignment of symbols in similar lines? I want to have something like this:

const manager = bank.createUser("John", "Doe",        25);
const admin   = bank.createUser("Max",  "Mustermann", 33);

But if the line is alone it should still break on all incorrect spaces before operators and arguments:

const manager  = bank.createUser( "John", "Doe",   25);
//           ^^                  ^              ^^^

It should be similar to what “key-spacing” rule does for object declarations.

in p5.js, how to display information of a datapoint when the mouse is hovered over it

Adding function for hover and changing draw function

I want to display the information of the datapoint when the mouse is hovered over the point. I tried adding a function and updated my draw function. It didn’t do anything. Even if I hover over the point, it does not show me any details.

Even after adding them, I do not see the details of the datapoints when I hover over them. I am not even getting any error messages

here is the code for my sketch.js

let table;
let genres = {};

function preload() {
    console.log("Attempting to load CSV file...");
    table = loadTable('/tmdb_5000_movies.csv', 'csv', 'header', loadSuccess, loadError);
}

function loadSuccess() {
    console.log("CSV loaded successfully");
}

function loadError() {
    console.error("Failed to load CSV file.");
}

function setup() {
    createCanvas(windowWidth * 2.5, windowHeight * 2.5);
    handleData();
    noLoop();
    console.log(table);
}

function handleData() {
    for (let i = 0; i < table.getRowCount(); i++) {
        let row = table.getRow(i);

        // Retrieve data from the row with default values
        let title = row.getString("original_title");
        let popularity = row.getNum("popularity");
        let revenue = row.getNum("revenue");
        let genreStr = row.getString("genres");

        // Parse genre string into an array
        let genreArr = JSON.parse(genreStr).map(g => g.name);

        // Create a new movie instance
        let movie = new Movie(title, popularity, revenue);

        // Add the movie to the corresponding genres
        for (let i = 0; i < genreArr.length; i++) {
            const g = genreArr[i];
            if (!genres[g]) {
                genres[g] = new Genre(g); // Create a new genre if it doesn't exist
            }
            genres[g].addMovie(movie); // Add the movie to the genre
        }
    }

    // Log the genres to check if they were populated correctly
    console.log(genres);
}

function draw() {
    background(123);
    let genreList = Object.keys(genres);
    let rows = int(genreList.length / 3);
    let colWidth = width / 3;
    let rowHeight = height / rows;

    for (let i = 0; i < genreList.length; i++) {
        let genre = genres[genreList[i]];
        let x = (i % 3) * colWidth + colWidth / 2;
        let y = int(i / 3) * rowHeight + rowHeight / 2;

        genre.display(x, y);
    }

    // Check for hover over any movie data point
    let hoveredMovie = getHoveredMovie();
    if (hoveredMovie) {
        fill(255);
        textSize(16);
        textAlign(CENTER);
        text(hoveredMovie.title, mouseX, mouseY - 10); // Display the movie title slightly above the mouse
    }
}

function getHoveredMovie() {
    let genreList = Object.keys(genres);
    for (let i = 0; i < genreList.length; i++) {
        let genre = genres[genreList[i]];
        for (let movie of genre.movies) {  // Assuming genre.movies is an array of movies
            let x = movie.x;  // Assuming movie x position is stored
            let y = movie.y;  // Assuming movie y position is stored
            let size = movie.getStarSize(); // Get the size of the star (point)

            // Check if mouse is within the radius of the movie point
            if (dist(mouseX, mouseY, x, y) < size / 2) {
                return movie;
            }
        }
    }
    return null; // Return null if no movie is hovered over
}

Apple Status 21002

I am trying to validate my in-app purchase receipt, but I keep getting the 21002 error from Apple, which indicates that the receipt data is either malformed or missing. I’ve ensured that my shared secret is correct because this code used to work before I refactored it to handle subscription purchases.

I’m running Firebase Functions for receipt validation, and everything looks correct based on the Apple documentation, but 21002 keeps coming back. Here’s the setup:

iOS App: Handles the purchase and sends the receipt data.
Firebase Functions: Processes the receipt and forwards it to Apple’s servers for validation.
Can anyone point out what might be causing this error? Below are snippets of my Swift and Node.js code. Any insight into why I’m getting 21002 and how to resolve it would be greatly appreciated.

func purchaseSubscription() async {
    let productID = subscriptionPlan.subscriptionApplePriceId
    guard !productID.isEmpty else {
        print("Product ID is not set for the selected subscription plan.")
        await updateUI(with: "Product ID is not set for the selected subscription plan.", isPurchasing: false)
        return
    }

    do {
        if let product = try await StoreKitManager.shared.fetchProduct(withIdentifier: productID) {
            if let transaction = try await StoreKitManager.shared.purchase(product: product) {
                if let receiptData = fetchReceiptData() {
                    await validateReceiptAndHandleResponse(receiptData: receiptData, subscriptionPlan: subscriptionPlan)
                } else {
                    await updateUI(with: "Unable to fetch receipt data.", isPurchasing: false)
                }
            } else {
                await updateUI(with: "Purchase failed: Transaction could not be completed.", isPurchasing: false)
            }
        } else {
            await updateUI(with: "Product not found", isPurchasing: false)
        }
    } catch {
        print("Error fetching product: (error.localizedDescription)")
        await updateUI(with: "Purchase failed: (error.localizedDescription)", isPurchasing: false)
    }
}

func fetchReceiptData() -> String? {
    guard let receiptUrl = Bundle.main.appStoreReceiptURL,
          let receiptData = try? Data(contentsOf: receiptUrl, options: .alwaysMapped) else {
        print("Receipt not found.")
        return nil
    }
    print("Receipt data size: (receiptData.count) bytes")
    return receiptData.base64EncodedString()
}

func validateReceiptAndHandleResponse(receiptData: String, subscriptionPlan: SubscriptionPlan) async {
    let result = await firebaseFunctions.testAppleReceipt(receiptData: receiptData)
    
    switch result {
    case .success(let response):
        print("Receipt validation response: (response)")
    case .failure(let error):
        print("Receipt validation failed: (error.localizedDescription)")
    }
}

func testAppleReceipt(receiptData: String) async -> Result<[String: Any], Error> {
    let data: [String: Any] = ["receiptData": receiptData]
    
    do {
        let result = try await functions.httpsCallable("testAppleReceipt").call(data)
        if let response = result.data as? [String: Any] {
            return .success(response)
        } else {
            return .failure(NSError(domain: "Invalid Response", code: -1, userInfo: [NSLocalizedDescriptionKey: "No valid data received from backend."]))
        }
    } catch {
        print("Error calling testAppleReceipt function: (error)")
        return .failure(error)
    }
}
const appleSandboxURL = "https://sandbox.itunes.apple.com/verifyReceipt";
const APPLE_SHARED_SECRET = functions.config().apple.shared_secret;

exports.testAppleReceipt = functions.https.onCall(async (data, context) => {
  const { receiptData } = data;
  
  console.log("Receipt data sent to Apple:", receiptData);

  const requestBody = {
    "receipt-data": receiptData,
    "password": APPLE_SHARED_SECRET,
    "exclude-old-transactions": true
  };

  try {
    const response = await fetch(appleSandboxURL, {
      method: "POST",
      body: JSON.stringify(requestBody),
      headers: { "Content-Type": "application/json" }
    });

    if (!response.ok) {
      console.error("Error in receipt validation request:", response.status, response.statusText);
      return { error: "Failed to validate receipt" };
    }

    const result = await response.json();
    console.log("Apple Receipt Validation Response:", result);
    return result;
  } catch (error) {
    console.error("Error occurred during receipt validation:", error);
    return { error: "An error occurred during receipt validation" };
  }
});


Tried validating my receipt. got 21002. expected it to work.

Sum function returns “Uncaught InternalError: too much recursion” [closed]

I know, this is a really stupid method to sum elements, but I just wanted to do it that way and can’t understand why it fails into an infinite recursion at the first step into a recursive function.

const sum = (...args) => {
  if (args.length <= 0) {
    return 0;
  } else {
    return args.splice(-1)[0] + sum(...args);
  }
}
console.log(sum(1, 2, 3));
console.log(sum(1, 2, 3, 4));

I don’t want to have a src folder in my dist foler

I’m using vite in a project and my folder structure is like this

youtube_comments/
   src/
    js/
     script.js
    sass/
     styles.sass
   index.html

When i move the index.html file in the root to the src folder and convert

 rollupOptions: {
      input: {
        main: path.resolve(__dirname, 'index.html'),
      },
    },

to

 rollupOptions: {
      input: {
        main: path.resolve(__dirname, 'src/index.html'),
      },

there appears to be a src folder in my dist folder
although i want my index.html to be in the root of the dist foler

make sweetalert2 html element dynamic via its html method

As anticipated by the title I want to make the html element of sweetalert2 dynamic.

I am using the sweetalert2 library.
https://sweetalert2.github.io/

In particular, I have an array with elements inside it.
My goal is to create as many checkboxes as there are elements in the array.

I tried to use foreach inside the html method that sweetalert2 provides, but as you can easily see from the reproducible example below I get nothing.

const arr = ['Alex','Jasmine','Andrie','Elton','Susy'];

function test() {
Swal.fire({
    html: 
    arr.forEach(user => {
        `  
        <div>
            <input type="checkbox" id="user" name="user" value="">
            <label for="">User</label><br>
        </div>
        `
    }),
    focusConfirm: false,
  })
}

document.getElementById ("test").addEventListener ("click", test);
<script src="https://unpkg.com/[email protected]/dist/sweetalert2.all.js"></script>



  <button type="button" id="test" class="button">
    Click
  </button>

Can someone help me? Can you tell me where I am going wrong?

Is there any reason not to extend built-in types with a namespace?

As I understand it, there are only two reasons why we avoid extending JavaScript’s builtin types:

  • Collisions with other libraries (if everyone did it).
  • Collisions with future extensions to the standard.

However, if we start every name with an obscure Unicode character, we avoid both issues entirely. Therefore, we should be free to create names in any scope, including builtin types (and prototypes).

Note: This would be implemented by a language that compiles to JavaScript, so users would only see these names while debugging (they never have to type them).

Does anyone know of any reason not to proceed like this?

the sum variable is not aggregated

I am trying to set up a script to calculate the monthly loan payment, but with the condition that if the loan term is less than 4 months, interest is not charged. But in line 25 I get the error monthcredit undefined, how can I fix this? The result is displayed on the links #msum and #ovsum. Tilda website builder.

Bad code –

<!-- Как сделать калькулятор расчета аннуитетных платежей по кредиту в ZeroBlock в Tilda mo-ti.ru --><script src="https://static.tildacdn.com/js/jquery-1.10.2.min.js" charset="utf-8" onerror="this.loaderr='y';"></script>
<style>
    a[href="#msum"] , a[href="#ovsum"] {pointer-events:none;}
</style>
<script>
    $( document ).ready(function() {
    //Значение процента    
    var percent = 10;
    $(".tn-atom__form").on('input', ".t-range", function() {
        setTimeout(function(){
             let summa = $('input[name="summa"]').next('.t-range__value-txt').html();
             let srok = $('input[name="srok"]').next('.t-range__value-txt').html();
             let monthPercent = percent/100/12;
             //Возведение в степень
             let degree = Math.pow( 1+monthPercent , -srok);
             if (srok <= 4) {
                 let monthCredit = summa/srok;
             let overCredit =0
             } else {
             let monthCredit = summa*(monthPercent/(1-degree));
             let overCredit = monthCredit*srok-summa
                 
             }
             //Выводим итоги в текст
             monthCredit = monthCredit.toFixed();
                 overCredit = overCredit.toFixed();
                 monthCredit = monthCredit.replace(/(d)(?=(ddd)+([^d]|$))/g, '$1 ');
                 overCredit = overCredit.replace(/(d)(?=(ddd)+([^d]|$))/g, '$1 ');     
             $('a[href="#msum"]').html(monthCredit+' руб.');
             $('a[href="#ovsum"]').html(overCredit+' руб.');
        }, 100);
    });
});
</script>

I have the same working script, but it does not provide for the condition about 4 months (attached below) –

Working code –

 <!-- Как сделать калькулятор расчета аннуитетных платежей по кредиту в ZeroBlock в Tilda mo-ti.ru --><script src="https://static.tildacdn.com/js/jquery-1.10.2.min.js" charset="utf-8" onerror="this.loaderr='y';"></script>
<style>
    a[href="#msum"] , a[href="#ovsum"] {pointer-events:none;}
</style>
<script>
    $( document ).ready(function() {
    //Значение процента    
    var percent = 10;
    $(".tn-atom__form").on('input', ".t-range", function() {
        setTimeout(function(){
             let summa = $('input[name="summa"]').next('.t-range__value-txt').html();
             let srok = $('input[name="srok"]').next('.t-range__value-txt').html();
             let monthPercent = percent/100/12;
             //Возведение в степень
             let degree = Math.pow( 1+monthPercent , -srok);
             let monthCredit = summa*(monthPercent/(1-degree));
             let overCredit = monthCredit*srok-summa
             //Выводим итоги в текст
             monthCredit = monthCredit.toFixed();
             overCredit = overCredit.toFixed();
             monthCredit = monthCredit.replace(/(d)(?=(ddd)+([^d]|$))/g, '$1 ');
             overCredit = overCredit.replace(/(d)(?=(ddd)+([^d]|$))/g, '$1 ');   
             $('a[href="#msum"]').html(monthCredit+' руб.');
             $('a[href="#ovsum"]').html(overCredit+' руб.');
             
       }, 100);
    });
});
</script>.

Webgl, framebuffer and texture color not render

I’m trying to create two textures, one for depth and one for color, but when I associate the depth texture with the framebuffer and render, the color texture comes up empty, why does this happen?

const createFramebufferWithTexture = () => {
    const ext = gl.getExtension('WEBGL_depth_texture');
    if (!ext) {
        console.error('WEBGL_depth_texture not found');
       // return;
    }

    const targetTexture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, targetTexture);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);

    const depthTexture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, depthTexture);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);

    const error = gl.getError();
    if (error !== gl.NO_ERROR) {
        console.error('Error create depth texture:', error);
     //   return;
    }

    const fb = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, targetTexture, 0);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);

    if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {
        console.error("Framebuffer error", gl.checkFramebufferStatus(gl.FRAMEBUFFER));
    }
    
  //  gl.drawBuffers([gl.COLOR_ATTACHMENT0])

    gl.bindFramebuffer(gl.FRAMEBUFFER, null);

    return [fb, targetTexture, depthTexture];
};

React-pdf Loading Issue: Endless Loading of a PDF-file

I’m working on a React project where I use a PdfArea component to display PDF files. I receive a link on a PDF-file from server and then use react-pdf to show it. It works fine most of the time but sometimes when I load a PDF file, it doesn’t display and I encounter an endless “Loading page…” text even though the file i pass to the Document component is valid. This is how i receive a file:

const fetchTemplate = async () => {
        const { pdf } = await templateApi.getOne(id as string);
        const url = pdf.download_url;

        const response = await fetch(url);
        const blob = await response.blob();
        const file = new File([blob], 'uploadedFile', { type: blob.type });

        setUploadedFile(file);
};

This is how i render the PDF.

import { pdfjs, Document, Page } from 'react-pdf';

pdfjs.GlobalWorkerOptions.workerSrc = new URL(
    'pdfjs-dist/build/pdf.worker.min.mjs',
    import.meta.url,
).toString()

export const DroppableArea = (uploadedFile) => {

    return (
        <div className='h-full relative'>
                <Document loading={<Spinner loading={true} color="#ff4c04" override={spinnerStyleOverride} />} file={uploadedFile} onLoadSuccess={handleLoadSuccess}>
                    <Page pageNumber={1} renderAnnotationLayer={false} renderTextLayer={false} />
                </Document>
                {children}
        </div>
    );
}

I thought there might be the problem with the worker but i don’t have a clue of how to debug it because there is no any errors. Are there any ways i can encounter the problem?