Blob type application/pdf showing an empty blank page in javascript(react)

I have been facing some issue regarding Blob file convertion in react js application

I’m fetching data from the server with the help of axios package

after fetching data from the server then response would be looks like this
enter image description here

Like wise i have converted that response data by including in Blob constructor function
here it is

const blob = new Blob([data], { type: "application/pdf" });

After that convertion im showing that blob as a src url inside the ifame tag

so that will look like this

<div className="card " style={{ height: "100vh" }}>
      {loading && <SimpleLoader />}

      {!loading && fileBlob && (
        <iframe
          title="File Viewer"
          width="100%"
          height="100%"
          src={URL.createObjectURL(fileBlob)}
        />
      )}
    </div>

what ever i did it still showing the same issue, i got always blank pdf page

eventhough after adding {responseType : blob} issue was still existed

here is that api function

export function getFileAccessView(hashCode: string) {
  return axios.post(`authentication/${hashCode}`, {
    responseType: "blob",
  });
}

how do i fix this error

for better understanding i have pasted entire component below

const ViewFile: FC<Props> = () => {
  // @ts-ignore
  const { state }: LocationOrderfileDetails = useLocation();
  const fileDetails: urlParams = state.orderFileDetails || {};
  const [loading, setLoading] = useState<boolean>(false);
  const [fileBlob, setFileBlob] = useState<Blob | null>(null);
  const viewFileAPI = () => {
    setLoading(true);
    getFileAccessView(fileDetails.hashCode) // axios api =>  return axios.post('path')
      .then(({ data }) => {
        console.log(data);

        //   data looks like this
        //           %PDF-1.7
        // %�쏢
        // 5 0 obj
        // <</Length 6 0 R/Filter /FlateDecode>>
        // stream
        // x���o]�qMҒHB�d>d[��$˺W�=��C��j�
        //   įB��X�d:�Wz9ı��bp�J��V����6u@����㑦���9�MZG�Gv�AG+9�R�<����_vۘm��Oi�nl����]��GV�9�k��팿��G�q�x��<k�����v&&;a�Sb��.jȯ]�3ɧ�yf��l��C��=?~���F��vi��5&��A(g�0+Є�I��2M���>�!

        const blob = new Blob([data], { type: "application/pdf" });
        setFileBlob(blob); // set blob to state
      })
      .catch(() => {})
      .finally(() => {
        setLoading(false);
      });
  };
  useEffect(() => {
    viewFileAPI();
  }, [fileDetails.hashCode]); // based on hasCode value fetch the data

  return (
    <div className="card " style={{ height: "100vh" }}>
      {loading && <SimpleLoader />}

      {!loading && fileBlob && (
        <iframe
          title="File Viewer"
          width="100%"
          height="100%"
          src={URL.createObjectURL(fileBlob)}
        />
      )}
    </div>
  );
};

export default ViewFile;

please currect me if i did any mistake in the code

three.js instanceMatrix position ignores Z axis

I am trying to make a three.js scene with a gridded floor similar to a chess board.
The code I have manages to alter the colors of the tiles, but somehow the Z axis movement is ignored.
This is the code of the function:
`addFloor()
{

    const lightColor = new THREE.Color(0xB8D0D9);
    const darkColor = new THREE.Color(0xADC4CC);

    const cellSize = 1000;
    const countXY = 1000;
    const count = countXY*countXY;
    const xy0 = 0;

    const geometry = new THREE.BoxGeometry( cellSize,cellSize,cellSize );            // Create plane Geometry as template
    const material = new THREE.MeshBasicMaterial( {side: THREE.DoubleSide, opacity:0.6, depthWrite: false} );  // Create colored material

    const floor = new THREE.InstancedMesh(geometry, material, countXY);  // Create instanced mesh of template, one for each pixel

    let color;
    let idX = 0;
    let idZ = 0;
    for (let i = 0; i < count; i++) {
        idX = i % countXY;
        idZ = Math.floor(i / countXY);
        color = (idX + idZ) % 2 === 0 ? lightColor : darkColor;
        
        const pos = new Vector3(
            xy0 + idX * cellSize,
            0,
            xy0 + idZ*cellSize
        );

        const m = new THREE.Matrix4();
        m.makeTranslation(pos.x, pos.y, pos.z);

        floor.setMatrixAt(i, m);
        floor.setColorAt(i, color);
    }
    floor.instanceColor.needsUpdate = true;
    floor.instanceMatrix.needsUpdate = true;

    this.add(floor);
}`

The class this function is in inherits from THREE.Scene, so ‘this’ is of type Scene.

If I use the variable idX instead of idZ in the pos Vector, the tiles align themselves on a diagonal like they should in that case.
I thought it might be that the Math.floor does not correctly round down, but console.log shows it does.

What is the difference between Virtual DOM and ReactDOM?

I am going through lot of articles over the internet asking the difference between the two, but almost everyone of them explains the difference between Virual DOM and Real DOM. According to my current knowledge, VirtualDOM is just a software concept where a separate copy of Real DOM is maintained…
Is ReactDOM just an implementation of the Virtual DOM ?

Escaping Numeric IDs for QuerySelector – Unexpected Double Backslashes

I’m working with SVG elements in a TypeScript project and need to query foreignObject elements by their parent g element’s IDs. Some of these IDs start with a digit, so I’m using a function to escape the ID appropriately for use in document.querySelector.

However, I’m encountering an issue where the escaped ID seems to be represented with double backslashes in the debugger, leading to query selection failures.

In the SVG structure:

<g id="3735df69-8da5-45a9-8580-ffd0e50b3111" transform="translate(200,200)">...</g>
<g id="080640d2-e040-4c6b-b943-7311327f8129" transform="translate(300,200)">...</g>

And here is the function I’m using to sanitize the IDs:

function sanitizeId(id: string) {
  if (/^d/.test(id)) {
    return id.replace(/^(d)/, "\3$1 ").replace(/([^w-])/g, "\$1");
  } else {
    return id;
  }
}

const selector = `#${sanitizeId(props.__rd3t.id)} foreignObject`;
const foreignObject = document.querySelector(String(selector));

When I console.log the selector, I see the following output:

#\33 735df69-8da5-45a9-8580-ffd0e50b3111 foreignObject

However, in the debugger, the selector evaluates to:

#\\33\ 735df69-8da5-45a9-8580-ffd0e50b3111 foreignObject

I’m confused about why the escaped ID is showing up with double backslashes in the debugger and how this affects document.querySelector. How can I correctly escape these numeric IDs for use in CSS selectors in TypeScript? Any insights or suggestions would be greatly appreciated.

React router dom navigating to wrong path

We are using react router dom v6.19.0 and there are two you can find below.

<Route path="/route1/*" element={<RouteOneList />} />
<Route path="/route1/:one/:two/:three" element={<RouteAnother />} /> 

and in RouteOneList it has sub routes

<Route path="/add/:type/:id" element={<AddComponent />} />

Here I am trying to access

/route1/add/test/1 – It suppose to load addComponent but its falling into component

Is there any way tackle this problem ? I have tried changing the order but that also not helped me.

Thanks in advance

Embed javascript in the Blazor component in .NET 8

I’m migrating my ASP.NET Core website to .NET Blazor Web App with static render. I’ve encountered problems with embeding external js script into blazor component.

The scenario is I have one blazor page where I want to show some gists:

<script src="https://gist.github.com/robocik/9506834.js"></script>

By default, when I open this website, these scripts are not invoked. I found a partial solution described here:
https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/static-server-rendering?view=aspnetcore-8.0

This solution works with scripts which are hosted locally. But in this case, gist script is hosted externally therefore I get exception:

Access to script at ” from origin ” has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

How can I embed external script in my blazor component in .NET 8?

Exporting and Importing Automatic Tree Shake in Turborepo

In this “packages” folder, if I export all of this and import in the “apps” folder. Will it only load components that you imported?

packages > shared > ui > index.ts

import "./tailwind.css";

// components
export * from "./components/Button";
export * from "./components/Card";
export * from "./components/Footer";
export * from "./components/Header";
export * from "./components/Sidebar";

// layouts
export * from "./layouts/AuthLayout";
export * from "./layouts/DefaultLayout";

packages > shared > ui > package.json

{
  "name": "shared-ui",
  "version": "0.0.0",
  "main": "./index.ts",
  "types": "./index.ts",
  .....
}

apps > inventoryApp > app > index.ts

import { Header, Sidebar, DefaultLayout } from "shared-ui";

How to execute a function that runs after all the DOM is loaded in nuxtjs?

I created a function that adjusts the size of columns in a table.

When I navigate between pages, it doesn’t launch.

If I refresh the page, thanks to SSR, they execute correctly (because the dom is entirely constructed before the javascript is executed).

This is not the case for navigation between pages.

<script setup>
// Function to adjust column widths
const adjustTableColumnWidths = () => {
    const tables = document.querySelectorAll('.prose table');

    tables.forEach((table) => {
        const totalWidth = table.offsetWidth;
        const firstColWidth = totalWidth / 3; // Largeur de la première colonne
        const otherColWidth = (totalWidth - firstColWidth) / (table.rows[0].cells.length - 1); // Width of other columns

        // Go through all table rows to fit columns
        Array.from(table.rows).forEach(row => {
            // Ajuster la première colonne
            const firstCell = row.cells[0];
            if (firstCell) {
                firstCell.style.width = `${firstColWidth}px`;
            }

            // Adjust the other columns
            for (let i = 1; i < row.cells.length; i++) {
                const cell = row.cells[i];
                cell.style.width = `${otherColWidth}px`;
            }
        });
    });
};

// Call the function after the content is loaded and rendered
onMounted(async () => {
    await nextTick(); // Wait for the next 'tick' for the DOM rendering to complete
    adjustTableColumnWidths();
    // Add an event handler for window resizing
    window.addEventListener('resize', adjustTableColumnWidths);
});

// Clean event listener when unmounting component
onUnmounted(() => {
    window.removeEventListener('resize', adjustTableColumnWidths);
});
</script>

How to test emails with mailtrap (automatically)?

I want to assert that the right email with the right information is sent after registration. How do I do it in my auto-test?

I use the Nightwatch framework and js. I’ve seen that the mailtrap tool can be used for this purpose, but all the resources that I could find lacked good documentation or were focused on it from developer’s point of view.

Can someone please provide some good resources where it’s described how to configure and test emails via code (I don’t need to send them via code, they are sent during my auto-tests, I just need to have a way to get them and assert that they have the right information).

Make an object key from passed literal argument in TypeScript

I would like to know whether the below is possible.
Based on the argument passed, recoginize the object key and access with that key.

Any solutions?

function async func(arg:'key1'|'key2'){
  // fetchResult returns an object which includes {key1:'result1'} or {key2:'result2'}
  const obj:{[arg]:string} = await fetchResult('url')
  console.log(obj[arg])
}

await func(key1) //Expect console.log('result1')

await func(key2) //Expect console.log('result2')

Why does performing DFS with this code result in duplicate leaves?

I am writing an algorithm that discerns whether two trees have the same leaves.

These have the same leaf numbers in the same order so this returns true

These have the same leaf numbers in the same order so this returns true.

This is the code I wrote:

function leafSimilar(root1: TreeNode | null, root2: TreeNode | null): boolean {

    console.log(DFS(root1))

    const leavesRoot1 = DFS(root1);
    const leavesRoot2 = DFS(root2);

    for (let i = 0; i < Math.max(leavesRoot1.length, leavesRoot2.length); i += 1) {
        if (leavesRoot1[i] !== leavesRoot2[i]) {
            return false;
        }
    }

    return true;
};

function DFS(root, leaves = [] ) {

    if(!root) return leaves; 

    if (!root.left && !root.right) {
        leaves.push(root.val);
        return leaves;
    }

    // return DFS(root.left).concat(DFS(root.right)); // this is the correct answer

    return DFS(root.left, leaves).concat(DFS(root.right, leaves)); // why doesn't this work?
}

The last line in the code is what i initially thought, but it is wrong.

I couldn’t draw it in my mind so I logged them as seen in the second line.

It logs:

[
  6, 7, 4, 
  6, 7, 4, 
  6, 7, 4, 
  6, 7, 4, 9, 8,
  6, 7, 4, 9, 8
] 

After 2 hours, I cannot figure out why this is.

I would think it should be at least something similar to this:

[6, 
 6, 7, 
 6, 7, 4, 
 6, 7, 4, 9,
 6, 7, 4, 9, 8,
]

or just

[6,7,4,9,8]

which is the correct one.

Would someone be able to explain to me why?

The DFS function takes leaves array argument from the previous call.

This means that it should receive leaves from the node above, not below, so there shouldn’t be a repeat pattern in the leaves array because it is empty.

The DFS is in preorder according to the code I wrote, so the left-most nodes are evaluated first.

Please help me understand.

React Quill | quill.js:5824 Uncaught RangeError: Maximum call stack size exceeded

in nextjs I am using react-quill so it in I have create and edit logic so on Add time I paste the html into code-block and the content is very large so after saving that data on edit time the same content I am passing into the react-quill but getting this error quill.js:5824 Uncaught RangeError: Maximum call stack size exceeded

here is my code

export const modules = {
  toolbar: [
    [{ size: [] }],
    [{ align: [] }],
    [{ color: [] }, { background: [] }],
    ['bold', 'italic', 'underline', 'strike'],
    [{ list: 'bullet' }, { list: 'ordered' }],
    ['link', 'image', 'code-block', 'blockquote'],
  ],
  clipboard: {
    matchVisual: false,
  },
};

/*
 * Quill editor formats
 * See https://quilljs.com/docs/formats/
 */
export const formats = [
  'size',
  'align',
  'color',
  'background',
  'bold',
  'italic',
  'underline',
  'strike',
  'bullet',
  'list',
  'link',
  'image',
  'code-block',
  'blockquote',
];

/**
 * Checks if a Quill editor content is empty.
 *
 * By default, the Quill editor adds HTML tags to the text for markup purpose.
 * Therefore, even when the user removes a value from the editor, the Quill still contains HTML markup.
 * This function determines whether the editor is actually empty.
 */
export const isQuillEmpty = (value: string | null) => {
  if (!value) return false;
  return (
    value.replace(/<(.|n)*?>/g, '').trim().length === 0 &&
    !value.includes('<img')
  );
};

const ReactQuill = dynamic(() => import('react-quill'), { ssr: false });

export interface WysiwygEditorProps
  extends Omit<ReactQuillProps, 'modules' | 'formats' | 'onChange' | 'value'> {
  value: string;
  error?: string | null;
  onChange?: (content: string | null) => void;
}

const WysiwygEditor = ({
  value,
  error,
  onChange,
  ...restProps
}: WysiwygEditorProps) => {
  const [editorValue, setEditorValue] = useState<string>();

  useEffect(() => {
    if (value) {
      setEditorValue(hasNoContentOrOnlyLineBreaks(value) ? '' : value);
    }
  }, [value]);

  const debouncedOnChange = useCallback(
    useDebouncedCallback((content: string) => {
      onChange?.(hasNoContentOrOnlyLineBreaks(content) ? '' : content);
    }, 300),
    [onChange],
  );

  const handleEditorChange = (content: string) => {
    setEditorValue(content);
    debouncedOnChange(content);
  };

  return (
    <>
      <ReactQuillStyledWrapper $isError={!!error}>
        <ReactQuill
          modules={modules}
          formats={formats}
          value={editorValue}
          {...restProps}
          onChange={handleEditorChange}
        />
      </ReactQuillStyledWrapper>
      {!!error && (
        <ErrorMessageWrapper>
          <ErrorMessage>
            <CmsWarning />
            {error}
          </ErrorMessage>
        </ErrorMessageWrapper>
      )}
    </>
  );
};

export default WysiwygEditor;

this error I am getting on edit time in short the content I passed on add time so that i am getting from api on edit time and that I am passing here
this error I am getting on edit time

as well one mmore thing is the above error I am getting only when I use code-block like on add time I add the html content into code-block </> otherwise without code-block using this is working fine
as well one mmore thing is the above error I am getting only when I use code-block like on add time I add the html content into code-block </> otherwise without code-block using this is working fine
whenrever I try to use this code-block with large content that time the getting error and ui gone frezze for some time and after that gone breack
enter image description here
I tried using useRef to direct activate code-block but not worked. expected so when I add the value in code-block so on edit time as well this will work without error.

Why am I getting this “Invalid hook call” error here?

Based on an array, I’m trying to create audio elements and [Slider][1]s to control their volume:

import { useState, useRef, useEffect } from 'react';
import Slider from 'rc-slider';
import 'rc-slider/assets/index.css';

function App() {
  const initialAudioSources = [
    { src: '/fire.mp3', volume: 1 },
    { src: '/ocean.mp3', volume: 1 },
    // Add more audio sources as needed
  ];

  const [audios, setAudios] = useState([]);
  const audioRefs = useRef([]);

  useEffect(() => {
    // Create audio elements and set initial volume for each audio source
    const audioElements = initialAudioSources.map((audioSource) => {
      const audio = new Audio(audioSource.src);
      audio.volume = audioSource.volume;
      audio.loop = true;
      return audio;
    });

    setAudios(audioElements);
    audioRefs.current = audioElements.map(() => useRef(null));

    // Start playing the audios
    audioElements.forEach((audio, index) => {
      if (audioRefs.current[index].current) {
        audioRefs.current[index].current.volume = audio.volume;
        audioRefs.current[index].current.play();
      }
    });
  }, []);

  const handleSliderChange = (newValue, index) => {
    const updatedAudios = audios.map((audio, i) => {
      if (i === index && audioRefs.current[i].current) {
        audioRefs.current[i].current.volume = newValue / 100;
      }
      return audio;
    });

    setAudios(updatedAudios);
  };

  return (
    <>
      <div className="audio-controls">
        {audios.map((audio, index) => (
          <div key={index} className="audio-control">
            <audio ref={audioRefs.current[index]} controls>
              <source src={initialAudioSources[index].src} type="audio/mpeg" />
              Your browser does not support the audio element.
            </audio>
            <div className="slider-wrapper">
              <Slider
                className="slider"
                min={0}
                max={100}
                step={1}
                value={audio.volume * 100}
                onChange={(newValue) => handleSliderChange(newValue, index)}
                vertical
              />
              <p>{audio.volume * 100}%</p>
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

export default App;

Right now, I’m getting this error:

Error Invalid hook call. Hooks can only be called inside of the body
of a function component. This could happen for one of the following
reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug
    and fix this problem.

I’m confused, I’m not calling hooks outside of a function component. What could the the problem and how to fix it?

Edit rc-slider-custom-handle-warning (forked)

hyperlink that will follow the position on the screen when pressing ctrl – or + from keyboard in javascript

how do I make this hyperlink follow its position every time I maximize or minimize, press ctrl – or + from my keyboard? I followed this style position property from https://www.w3schools.com/jsref/prop_style_position.asp but only fixed value is the one making the hyperlink appear and it seems that the position just stayed on it’s coordinates.

Looking forward to anyone’s kind assistance. Thank you very much in advance.

// ==UserScript==
// @name         Launch a Web Page
// @namespace    http://your-website.com
// @version      1.0
// @description  Will launch a WebPage
// @author       me
// @match        https://example.com/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_openInTab
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function() {
'use strict';

// Function to launch the webpage
function launchWebpage() {
    // Adjust the URL to the webpage you want to launch
    const targetURL = 'https://example.com/';
    window.open(targetURL, '_blank');
}

// Create a hyperlink positioned on the upper middle of the screen
const launchLink = document.createElement('a');
launchLink.href = 'javascript:void(0)';
launchLink.textContent = 'WebPage';
launchLink.style.position = 'fixed';
launchLink.style.top = '10px';
launchLink.style.right = '30%';
launchLink.style.transform = 'translateX(-50%)';
launchLink.style.color = 'white';
launchLink.style.padding = '10px';
launchLink.style.borderRadius = '5px';
launchLink.style.textDecoration = 'none';
launchLink.style.fontSize='18px';
document.body.appendChild(launchLink);

// Add event listener to the hyperlink
launchLink.addEventListener('click', launchWebpage);

})();

How to implement equivalence among arrays in JavaScript? How to enumerate and count each equivalence class?

I find myself genuinely intrigued by how the JavaScript community addresses fundamental challenges, ranging from object equivalence to the formal evaluation of expressions.

At the moment, I’m exploring a unified, queue-based pattern that aims to address a variety of challenges. You can take a look at my work on classifier.js.

I would be very interested in comparing the effectiveness of this pattern against the established methods prevalent within the JavaScript community. My nickname, ‘challenger’ is intended to reflect such an aspiration.

I would start with a fundamental concept: equivalence among objects in its simplest form—specifically, the equivalence among flattened arrays.

Consider an iteration of flattened arrays:

const 
        DATA = [[1, 0], [0, 1], [0], [0]]

Suppose you aim to establish equivalence by value among them. This means that arrays sharing the same values should not be duplicated. Additionally, you might want to tally the occurrences of each array and potentially enumerate all arrays sharing certain components. In the provided example:

  • the arrays are: [1, 0], [0, 1], [0]
  • the number of occurrences of the array [0] is 2
  • the set of arrays having 0 as first component is [0], [0, 1].

How would one go about implementing these functionalities? Could you provide a script to accomplish this?