Jest/React-testing-library not supporting React Helmet

I am writing test case to test my homepage but jest giving error while compiling the code and breaks at helmet tag.

I searched and found out that I should replace react-helmet with react-helmet-async and use HelmetProvider.

Now I am stuck at below error.

console.error
    The above error occurred in the <HelmetDispatcher> component:
    
        at construct (/Users/utkarshgupta/Documents/Fynd/quintessa/node_modules/react-helmet-async/src/Dispatcher.js:8:22)
        at construct (/Users/utkarshgupta/Documents/Fynd/quintessa/node_modules/react-helmet-async/src/index.js:15:14)
        at div
        at App
        at construct (/Users/utkarshgupta/Documents/Fynd/quintessa/node_modules/react-helmet-async/src/Provider.js:37:5)
        at construct (/Users/utkarshgupta/Documents/Fynd/quintessa/node_modules/react-router/cjs/react-router.js:113:30)
        at construct (/Users/utkarshgupta/Documents/Fynd/quintessa/node_modules/react-router/cjs/react-router.js:202:35)
        at fn (/Users/utkarshgupta/Documents/Fynd/quintessa/node_modules/react-query/lib/react/QueryClientProvider.js:45:21)
        at fn (/Users/utkarshgupta/Documents/Fynd/quintessa/node_modules/react-redux/lib/components/Provider.js:21:20)
        at fn (/Users/utkarshgupta/Documents/Fynd/quintessa/src/__test__/helpers/test-utils.js:28:22)

I am using custom SSR so, I have wrapped render to string elements in HelmetProvider.

My render function :

export const render = (
  ui,
  {
    initialState = initialReducerState,
    store = createStore(rootReducer, initialState),
    ...renderOptions
  } = {}
) => {
  const Wrapper = ({ children }) => (
    <Provider store={store}>
      <QueryClientProvider client={queryClient} contextSharing={true}>
        <Router>
          <HelmetProvider>{children}</HelmetProvider>
        </Router>
      </QueryClientProvider>
    </Provider>
  );

  return {
    ...rtlRender(ui, {
      wrapper: Wrapper,
      ...renderOptions,
    }),
    store,
  };
};

SSR JSX:

let jsx = extractor.collectChunks(
  <Provider store={store}>
    <QueryClientProvider client={queryClient}>
      <Hydrate state={dehydratedState}>
        <StaticRouter location={req.originalUrl} context={null}>
          <HelmetProvider context={helmetContext}>
            <App />
          </HelmetProvider>
        </StaticRouter>
      </Hydrate>
    </QueryClientProvider>
  </Provider>
); 

The above error not letting me to test all pages which use Helmet and other seo tags in react components.

How to set up the counter when it is detected

In my project, there should be a counter. I have used the “reveal function”. I want the counter to start when it goes to “reveal function”. And when the bottom-up scrolling is done again, the “function reveal” will be performed again.
Given that I used the “reveal function”, but when the scroll moves from bottom to top, the counter does not start again.
How can I solve this problem?
Thanks in advance for your guidance.

//counter
const counter = (EL) => {

  const duration = 4000; // Animate all counters equally for a better UX

  const start = parseInt(EL.textContent, 10); // Get start and end values
  const end = parseInt(EL.dataset.counter, 10); // PS: Use always the radix 10!

  if (start === end) return; // If equal values, stop here.

  const range = end - start; // Get the range
  let curr = start; // Set current at start position

  const loop = (raf) => {
    if (raf > duration) raf = duration; // Stop the loop
    const frac = raf / duration; // Get the time fraction
    const step = frac * range; // Calculate the value step
    curr = start + step; // Increment or Decrement current value
    EL.textContent = parseInt(curr, 10); // Apply to UI as integer
    if (raf < duration) requestAnimationFrame(loop); // Loop
  };

  requestAnimationFrame(loop); // Start the loop!
};

document.querySelectorAll("[data-counter]").forEach(counter);
//counter

// reveal
      function reveal() {
        var reveals = document.querySelectorAll(".reveal");

        for (var i = 0; i < reveals.length; i++) {
          var windowHeight = window.innerHeight;
          var elementTop = reveals[i].getBoundingClientRect().top;
          var elementVisible = 10;

          if (elementTop < windowHeight - elementVisible) {
            reveals[i].classList.add("active");
          } else {
            reveals[i].classList.remove("active");
          }
        }
      }

window.addEventListener("scroll", reveal);
// reveal
/* reveal */
.reveal {
  position: relative;
  opacity: 0;
}

.reveal.active {
  opacity: 1;
}
/* reveal */
<div class="reveal">
  <span>A: </span>
  <span data-counter="10">0</span>
  <br>
  <span>B: </span>
  <span data-counter="2022">1000</span>
  <br>
  <span>C: </span>
  <span data-counter="0">9999</span>
  <br>
  <span>D: </span>
  <span data-counter="-1000">1000</span>
  <br>
  <span>E: </span>
  <span data-counter="666">0</span>
  <br>
</div>

HTML canvas (Draw with Mouse) mouse cursor point mismatch

I want to use Draw with Mouse on the canvas. The code is as follows:

// Stores the initial position of the cursor
let coord = {x:0 , y:0}; 

// // set a flag
let paint = false;
// Updates the coordianates of the cursor when an event e is triggered 
function getPosition(event){
  coord.x = event.clientX - canvas.offsetLeft;
  coord.y = event.clientY - canvas.offsetTop;
}
  
// The following functions toggle the flag to start and stop drawing
function startPainting(event){
    if (mouseID.checked){
    myCanvas.style.cursor = "url('/paint.cur'),auto"
    paint = true;
    getPosition(event);
    }
}

function stopPainting(){
  paint = false;
}
    
function sketch(event){
  if (!paint) return;
  ctx.beginPath();
    
  ctx.lineWidth = mouseline.value;
   
  // set to a round shape.
  ctx.lineCap = "round";
    
  ctx.strokeStyle = bcolor.value;
      
  // The cursor to start drawing
  ctx.moveTo(coord.x, coord.y);
   
  // The position of the cursor gets updated when move the mouse around.
  getPosition(event);
   
  ctx.lineTo(coord.x , coord.y);
    
  // Draws the line.
  ctx.stroke();
}

The problem is when I run it on my desktop the mouse is fine but on another computer, the mouse gets a mismatched position with the drawing. Can anyone help me with the issue?

What will be the react-router v6 version of this?

I’m trying to migrate from react-router v5 to react-router v6. I can’t figure out a clear way of converting this code to v6 syntax.
What will be the v6 equivalent of this snippet?

import React, { Suspense } from "react";
import { Route, Switch, Redirect } from "react-router-dom";
import AuthLayout from "Layouts/auth.layout";
import Loading from "pages/loading";

const LoginPage = React.lazy(() => import("./login"));
const SignupPage = React.lazy(() => import("./signup"));

const User = (props) => {
  return (
    <AuthLayout>
      <Suspense fallback={<Loading />}>
        <Switch>
          <Redirect
            exact
            from={`${props.match.url}/`}
            to={`${props.match.url}/login`}
          />
          <Route
            path={`${props.match.url}/login`}
            render={() => <LoginPage />}
          />
          {/* <Route
            path={`${props.match.url}/signup`}
            render={() => <SignupPage />}
          /> */}
          <Redirect to="/error" />
        </Switch>
      </Suspense>
    </AuthLayout>
  );
};

export default User;

nodemon not updating the page after save

I am trying to learn nodeJS and installed nodemon, and it seems to be installed, but it does not actually restart the server. But after that, when I make some changes to the page, it displays, but it does not actually reload the server (so I have to do it manually). How can I fix this problem, because it is properly installed, using npm install -g nodemon. If there is no way out of this problem, is there an alternative to nodemon? Here’s my package.json:

{"dependencies": {"express": "^4.17.3","nodemon": "^2.0.15"}}

I tried installing nodemon locally, reinstalling visual studio code, deleting all nodeJS modules, deleting nodeJS, reinstalling nodemon globally

Console output after first nodemon command

Console output after all next nodemon commands (notice it is not restarting the server)

jest – how to check if a word is a english word

I am using Jest to test for a function, which generate a english word.

I tried below but not working. Just want to check if the word is combined by english characters

  it("generate a english word", () => {
    const word = "APPLE";
    expect(word).toMatch('/^[A-Za-z]*$/');
  });

What’s wrong with it?

How to implement hmacSHA256 with Javascipt using CryptoJS

We can calculate a hmac with CryptoJS.HmacSHA256(message, key)

But I want to implement it with the formula Sha256( concat ( key xor opad, Sha256( concat( key xor ipad, message ) )

I did the following

const key   = "e9058ab198f6908f702111b0c0fb5b36f99d00554521886c40e2891b349dc7a1";
const ipad  = "3636363636363636363636363636363636363636363636363636363636363636";
const opad  = "5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c";
const mess  = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";

const alpha = "b559d6edc4aaccd32c7d4dec9ca7076aa5c15c09197dd4301cbed54768c19bfd"; // key xor opad
const beta  = "df33bc87aec0a6b946172786f6cd6d00cfab36637317be5a76d4bf2d02abf197"; // key xor ipad

const hmac  = CryptoJS.SHA256( alpha + String ( CryptoJS.SHA256( ( beta + mess ) ) ) ) ;

But it doesnt work, any help ?

for example, with the code below I found hmac = “594b7b8b1dea8dd016c1702c5b2d8b75ba20d744423b08e8897f02454000abad”

but the real one is : “fc7e0b4417a84790035480f97f9a792d8328a497039ae483b4b85197c008669e”
and it’s calculated with CryptoJS.HmacSHA256(CryptoJS.enc.Hex.parse(mess), key))

Node.js installation stuck in power shell

I tried to install node.js and the power shell got stuck at this line::
Created a UnelevatedInstallerTelemetryDecorator

I closed the power shell and ran the installation package >> clicked on repair >> it finished installation but didn’t open power shell nor cmd.

I am able to load node.js in my vscode now…. Is that ok??

Pass multiple values to a param in getStaticPaths() in nextjs

I want to have two routes

  1. /midterm/cs611
  2. /finalterm/cs611

All i am trying to do is when i hit endpoint /midterm/cs611
it should display different content
and when it hits to /finalterm/cs611 it should display different content.
But i end up with correct results when hitting /finalterm/cs611 and when i hit /midterm/cs611 it shows 404 page.

If i replace like ‘midterm’ || ‘finalterm’, i see 404 page for finalterm and correct results for midterm.

Here i have my code

enter image description here

Here is the result hitting /midterm/cs611
enter image description here

Here is the result while hitting /finalterm/cs611
enter image description here

my code for getting the Y axis movement on a canvas

My code doesnt work when I use the cursor lock api but does without it
my code:

    function getmouse(event) {
      document.getElementById("canvas_parent").style.top = (event.movementY - (event.movementY *       2)) + "px"
    }

It works the same way with ClientY too so i want it to change the value of event.movementY

What is the practice to generate random symmetric keys in React JS?

Context:- I’m building a React js app that is using crypto js library for encryption. i am using the hard coded keys for the process of encryption.

My question:- (I’m a crypto novice) is there a best practice for generating some-secret-key symmetric encryption? My plan is to generate this key randomly when the website boots for the first time and store it securely.

Please guide me.

react js website is not showing body content in the view source

I am trying to create a website using react js (using react routers , not using next.js). liveitcourses.com is the name of the website which is still in progress. But I am facing a strange issue. On every page of the website whenever I am trying to see the “view source”, the tag body is showing empty. I am afraid if it is not showing the body contents in the view source, search engines will not be able to crawl my pages, hence bad impact on SEO. I just started react a few weeks ago. Is it the normal react js behavior or should I need to correct it? If my understanding is correct then how can I make my website crawlable for search engines. Please suggest. Below body tag is empty while title and other meta tags are present.

<html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Learn IT courses online in interactive and live classes."/><link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"/><title>Best online IT courses based on live classes and interactive programming sessions</title><script defer="defer" src="/static/js/main.80f62ed5.js"></script><link href="/static/css/main.53eb7892.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>

How Can I delete data using Swal on reactJs?

Hello everyone I’m using reactjs as frontend and laravel as backend I want to use swal for delete function somtimes it works even if I ckick on No and sometimes it didn’t work at all.
this is my last attempt:

 <span onClick={() => {
                    new Swal({
                      title: `Are you sure you want to delete ${item.visit_name}?`,
                      text: "You will not be able to recover your data!",
                      type: "warning",
                      showCancelButton: true,
                      confirmButtonColor: "#DD6B55",
                      isConfirmed: <button onClick={()=>deleteOperation(item.visit_name)}/>,
                      closeOnConfirm: false
                    })  }} >
                    <Trash2 size={20} color="red" />
                  </span>

This is how I consume the api :

  async function deleteOperation(id) {
    let result = await fetch(`${API_ENDPOINT}/api/deleteVisitor/` + id, {
      method: "DELETE"

    });
    result = await result.json()

    getData();

  }

thanks in advance for anyone will try to help mee

pass multiple local storage videos to react js popup video player

i created onclick react grid video player using ag-grid. after that passing json data to grid.

after passing json data my ag-grid look like this

Now i passed only one local storage video to react video player(Play button )

import myData from "../video.mp4"
   ....
   ....
    <DialogContent>
        <iframe width="560" height="315" src={myData} allowFullScreen></iframe>
        </DialogContent>

src={myData} is represent video.mp4 in my local storage , Now how to i pass multiple videos to react video player using json file

my json file structure like this :

{
  "users": [
    {
      "id": 1,
      "name": "Hari",
      "email": "[email protected]",
      "phone": "9876543210",
      "dob": "/home/fraction/Music/agGrid-crudOperation/src/video1.mp4"
    },
    {
      "name": "Hari",
      "email": "[email protected]",
      "phone": "9876543210",
      "dob": "/home/fraction/Music/agGrid-crudOperation/src/video2.mp4",
      "id": 5
    }
  ]
}

i tried to pass video url using map method but its didnt work me. how to pass multiple videos through json file in react js

for more code details refer here

Any suggestion and answer are heartly appreciated thanks in advance..