Protection java script script leak

I want to add to my script for tampermonkey a system with which i can remotely turn off the script for all users.

I tried to do this by getting data from raf.github.com,then compared the two values ​​(which are stored on the server and which are stored by the client) but nothing worked for me.

How to get openStreetMap to not show city names

I have this app that requires a map and I want to transfer it to using a free map(instead of using Google maps). But I need it to not show city names. I also want it to be easy to implement and work with leaflet.

I’ve tried map-tiler but it is not free for the number of calls I need. What should I do? I don’t really want to self-host the tiles as well. Thank you!

Youtube API for auto-generated channels (topics) doesn’t return valid playlist

I’m trying to retrieve videos related to “Auto-generated” youtube channel.

While it works some time ago (at least in 2023),
recently I been faced issue — there are no more playlists like “Popular”, or “Recent” returned by channels api, only “Uploads”.

But even “Uploads” playlist doesn’t have valid playlistId —
playlistItems api throws error “The playlist identified with the request’s playlistId parameter cannot be found.”

Here’s the sample code:

const YT_KEY = ""; // put your google api key here
const YT_AUTO_CHANNEL_ID = "UCNXJk0T4LRLpWS5XlVSg4uQ";

fetch(`https://youtube.googleapis.com/youtube/v3/channels?part=contentDetails&id=${YT_AUTO_CHANNEL_ID}&key=${YT_KEY}`)
  .then((response) => response.json())
  .then((json) => {
    console.log("Channel's related "Uploads" playlistId", json.items[0]?.contentDetails.relatedPlaylists.uploads);
    if (json.items[0]?.contentDetails.relatedPlaylists.uploads) {
      fetch(`https://youtube.googleapis.com/youtube/v3/playlistItems?part=id%2CcontentDetails%2Csnippet&playlistId=${json.items[0].contentDetails.relatedPlaylists.uploads}&maxResults=50&key=${YT_KEY}`)
        .then((response) => response.json())
        .then((json) => {
          console.log(""Uploads" playlist videos response", json);
        });
    }
  });

What can be solution for that?

“if regex.test” doesn’t works properly on javascript vuejs router

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// ...

const allowedToAnonymous = [
  /^/login$/g,
  /^/signup$/g,
  /^/home$/g,
  /^/emailconfirm/[0-9a-zA-Z]{8}$/g,
  /^/serviceGuide$/g,
  /^/$/g
];

router.beforeEach((to, from) => {
  for (var regex of allowedToAnonymous) {
    console.log(regex);
    console.log(to.path);
    if (regex.test(to.path)) {
      console.log('return');
      return;
    } else {
      console.log(regex.test(to.path));
      console.log('do not return');
    }
  }

  const checkLogin = stores.getters['userStore/checkLogin'];
  if (!checkLogin) return '/login';
});

I wrote the above code in my vuejs project. It redirects to the login page if the specific regular expressions and the current path do not match and you are not logged in. All console.log functions are for debugging. If I test this in web browser, it results like below:

/^/login$/g
/serviceGuide
false
do not return
/^/signup$/g
/serviceGuide
false
do not return
/^/home$/g
/serviceGuide
false
do not return
/^/emailconfirm/[0-9a-zA-Z]{8}$/g
/serviceGuide
false
do not return
/^/serviceGuide$/g
/serviceGuide
true
do not return
/^/$/g
/serviceGuide
false
do not return
/^/login$/g
/login
return

Look near the /^/serviceGuide$/g output. Even though the result of regex.test is true, it seems that it is proceeding in a do not return branch. This does not happen all the time, and it does occur when I repeatedly browse the website 2~4 times.

Why does this happen and what is the solution?

Is there a way to programmatically change screen size for tailwind class

I am building UI-kit with react tailwind.
I know that tailwind can’t find classes that made with template strings. I want to achieve this:

I have a few components in my ui kit and I want them to have same logic (for i.e. button):
Button has variant size:{
sm: “p-1”,
md: “p-2”
}
I want to automatically generate:
{
sm: “md:p-1”,
md: “md:p-2”
}

And etc for all screen sizes.
Finally want to do smth like this:


<Button size="sm" md={size:"md"} />

I think I can’t do this in function because tailwind couldn’t see this classes in runtime.
Maybe there is a library or a way to do this in build time. I’m kinda lost cause I already tried a lot of things. Will be glad to see your answer

Tried twind, but can’t really use it cause of deps conflicts

How can I use React Context API effciently

I’m making React web application and beginner. As I used Context API, I had a problem.

Here’s my code.

import React, { createContext, useState, useEffect } from "react";

export const RoleContext = createContext({
  optionRole: "",
  setOptionRole: () => {},
  accessToken: "",
  setAccessToken: () => {},
  passwordChecked: false,
  setPasswordChecked: () => {},
});

export const RoleProvider = ({ children }) => {
  const [optionRole, setOptionRole] = useState(() => {
    return localStorage.getItem("optionRole") || "";
  });
  const [accessToken, setAccessToken] = useState("");
  const [passwordChecked, setPasswordChecked] = useState(false);

  useEffect(() => {
    
    const refreshAccessToken = async () => {
      try {
        const response = await fetch("/auth/token", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${accessToken}`,
          },
        });

        if (!response.ok) {
          throw new Error("Failed to refresh access token");
        }

        const data = await response.json();
        setAccessToken(data.accessToken);
      } catch (error) {
        
        console.error("Failed to refresh access token:", error);
        
        // logout();
      }
    };

        if (!accessToken) {
      refreshAccessToken();
    }
  }, [accessToken]);

  useEffect(() => {
        localStorage.setItem("optionRole", optionRole);
  }, [optionRole]); 

  const roleCtx = {
    optionRole,
    setOptionRole,
    accessToken,
    setAccessToken,
    passwordChecked,
    setPasswordChecked,
  };

  return (
    <RoleContext.Provider value={roleCtx}>{children}</RoleContext.Provider>
  );
};

The context name is RoleContext. It means that the component will deal with role. But I want another Context API. If I make another Context API. The code would be messy. For example, I want to make MathContext. I may use it this way. And supposing that I want to Context API more, the more I want to make, the more the code is complicate.

<SubjectProvider>
 <MathProvider>
  <RoleProvider>
   <App/>
  </RoleProvider>
 <MathProvider>
</SubjectProvider>

Is there any good way to use Context API?? Thank you for reading my question 🙂

I made lots of Context.

Could not find an option named “flavor”

Since Flutter 3.16, we now can read flavor passed through flutter run --flavor
on Flutter Web

https://github.com/flutter/flutter/pull/134179

I tested it and it works. However, when I run in flutter build web --flavor banana I get Could not find an option named "flavor"

My question is: Is this pull request really just implement in Flutter Web development mode but not in the built release or I am missing something ? It’s hard to believe, because what’s the point of adding a feature that can’t be deployed in production ?

When trying to draw 30,000 markers on a Google map, the page freezes

I have a project on next.js 14.
When I click on the button, I open a modal window where I draw a Google map on which there should be 30,000 markers of the delivery service.
If I draw 500, everything works very quickly, up to 3000 more or less quickly, but when I try to draw all 30,000, the page freezes.

Libraries used:
vis.gl/react-google-map
googlemaps/markerclusterer

The code and guide are taken from the Google Maps documentation and adapted to my needs.
Here are the lines of code:

MapModal component:

'use client';

import { useEffect, useState } from 'react';
import { APIProvider, Map } from '@vis.gl/react-google-maps';

import { Markers } from '@/app/ui/components/order/main/stepNumberTwo';

function transformData(dataArray) {
  return dataArray.map(item => {
    return {
      key: item.name,
      location: {
        lat: item.location.latitude,
        lng: item.location.longitude,
      },
    };
  });
}

export function MapModal() {
  const [markers, setMarkers] = useState([]);

  const url = 'https://api.inpost.pl/v1/points';

  const centerMap = { lat: 50.8459754, lng: 16.4913201 };

  useEffect(() => {
    (async () => {
      try {
        const response = await fetch(`${url}?per_page=500`, {
          method: 'GET',
          headers: {
            Authorization: `Bearer ${process.env.NEXT_PUBLIC_INPOST_API_TOKEN}`,
            'Content-Type': 'application/json',
          },
        });

        const data = await response.json();

        const fetchPromises = [];
        for (let i = 1; i <= data.total_pages; i++) {
          fetchPromises.push(
            fetch(
              `${url}?page=${i}&per_page=500&fields=name,type,location,address`,
              {
                method: 'GET',
                headers: {
                  Authorization: `Bearer ${process.env.NEXT_PUBLIC_INPOST_API_TOKEN}`,
                  'Content-Type': 'application/json',
                },
              }
            ).then(response => {
              if (!response.ok) {
                throw new Error(
                  `Failed to fetch page ${i}: ${response.statusText}`
                );
              }
              return response.json();
            })
          );
        }

        const results = await Promise.all(fetchPromises);

        let formatResults = [];
        results.map(item => {
          return formatResults.push(...item.items);
        });

        setMarkers(formatResults);
      } catch (error) {
        console.log(error);
      }
    })();
  }, []);

  return (
    <div className="flex-center fixed inset-0 z-50 bg-black/25">
      <div className="flex h-[80%] w-[80%] bg-white">
        <div className="h-full w-[30%] bg-slate-300"></div>
        <div className="h-full w-[70%]">
          <APIProvider apiKey={process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY}>
            <Map
              mapId={process.env.NEXT_PUBLIC_GOOGLE_MAP_ID}
              defaultZoom={14}
              defaultCenter={centerMap}
              disableDefaultUI={true}
            >
              {markers && <Markers points={transformData(markers)} />}
            </Map>
          </APIProvider>
        </div>
      </div>
    </div>
  );
}

Markers component:

'use client';

import { useEffect, useState, useRef } from 'react';
import { MarkerClusterer, GridAlgorithm } from '@googlemaps/markerclusterer';
import { AdvancedMarker, useMap } from '@vis.gl/react-google-maps';

import { DefaultMarker } from '@/public/icons';

export function Markers({ points }) {
  const map = useMap();
  const [markers, setMarkers] = useState({});
  const clusterer = useRef(null);

  useEffect(() => {
    const gridOptions = {
      gridSize: 60,
      maxDistance: 10000,
    };

    if (!map) return;
    if (!clusterer.current) {
      clusterer.current = new MarkerClusterer({
        map,
        algorithm: new GridAlgorithm(gridOptions),
      });
    }
  }, [map]);

  useEffect(() => {
    clusterer.current?.clearMarkers();
    clusterer.current?.addMarkers(Object.values(markers));
  }, [markers]);

  const setMarkerRef = (marker, key) => {
    if (marker && markers[key]) return;
    if (!marker && !markers[key]) return;

    setMarkers(prev => {
      if (marker) {
        return { ...prev, [key]: marker };
      } else {
        const newMarkers = { ...prev };
        delete newMarkers[key];
        return newMarkers;
      }
    });
  };

  return (
    <>
      {points.map(point => (
        <AdvancedMarker
          key={point.key}
          position={point.location}
          ref={marker => setMarkerRef(marker, point.key)}
        >
          <div className="flex-center size-10 fill-accent-400">
            <DefaultMarker />
          </div>
        </AdvancedMarker>
      ))}
    </>
  );
}

I would be grateful for any advice.

How to use custom domain with Auth0 React SDK

I set up a custom domain, login.mydomain.com, in the Auth0 dashboard, and the status is marked as ready. I have integrated Auth0 authentication into my app using the Auth0 React SDK. Authentication works perfectly on localhost with the Auth0 default domain. However, when I switch to using the custom domain, authentication fails. When I enter login.mydomain.com in a browser, it redirects me to mydomain.com instead of the Auth0 login page. Here is my code:

 export const Auth0ProviderWithNavigate = ({ children }) => {
    const navigate = useNavigate();
  
    // const domain = process.env.REACT_APP_AUTH0_DOMAIN;
    const domain = 'login.mydomain.com'
    const clientId = process.env.REACT_APP_AUTH0_CLIENT_ID;
    // const organizationId = "org_DqLZEX65aFU4ftgv";
    // const redirectUri = "http://localhost:3000";

    const onRedirectCallback = () => {
        navigate('/');
    };

    return (
        <Auth0Provider
            domain={domain}
            clientId={clientId}
            authorizationParams={{
                redirect_uri: window.location.origin,
                // organization: organizationId 
            }}
            onRedirectCallback={onRedirectCallback}
        > 
            {children}
        </Auth0Provider>
    )
}

export default function LoginButton() {

  const { loginWithRedirect } = useAuth0();
  const [email, setEmail] = useState('');

  const handleLogin = async () => {
    try {
      console.log("handleing login")
      const domain = email.split('@')[1];
      const orgId = orgMap[domain]

      await loginWithRedirect({
        authorizationParams: {
          organization: orgId,
          // redirect_uri: window.location.origin,
          login_hint: email
        },
      });
    } catch(error){
      console.error("login error", error)
    }
  }
  return (
    <div>
      <input 
        type="email"
        placeholder="Enter your email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <button onClick={handleLogin}>Log In</button>
    </div>
  )
}

function App() { const { isLoading, isAuthenticated } = useAuth0();  
   
  return (
   <div>
      {!isAuthenticated && <LoginButton />}
)}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    < BrowserRouter >
      <Auth0ProviderWithNavigate>
        <App />
      </Auth0ProviderWithNavigate>
    </ BrowserRouter >
);

  • I lookup in the DNS record and found records for login.mydomain.com
  • I replaced the domain value to login.mydomain.com

Optimal way to validate data of an object in JS

I have a set of data that looks as below

var data = {
    a:{
        a_meta_data_1:"1",
        a_meta_data_2:"2",
        children:{
            b:{
                b_meta_data_1:"1",
                b_meta_data_2:"03052024",
                children:{
                    c:{
                        c_meta_data_1:"1",
                        c_meta_data_2:"5",
                    }
                }
            }
        }
    }
}

Each field has unique requirements that need to be, like a_meta_data_1 should be a length of 5,b_meta_data_2 should be date in the format ‘DDMMYYYY’ and so on…

To write a function to validate all records (can be around 2000+), what would be the best way to approach it?

One way I am trying is to define rules as below, and while looping through the data, check if for each metadata of each object (whether parent or child)

var a_validation=   {
    a_meta_data_1:function(data){
        if(data.length <= 3){
            return false
        }
        return true
    },
    a_meta_data_2:function(data){
        if(data != 'YY'){
            return false
        }
        return true
    }
}

var b_validation =  {
    b_meta_data_1:(# a function as above),
    b_meta_data_2:(# a function as above)
}

var c_validation = {
    c_meta_data_1:(# a function as above),
    c_meta_data_2:(# a function as above)
}

Is there a better way to approach this problem? Any issues that I should be weary of when creating a function structure like this?

Server is started successfully but getapi is not loading in nodesjs

I am working on an Express.js application and encountered an issue with routing. Here is what I have done so far:

Controller:

exports.dummyLink = (req, res) => {
  res.send("this is your dummy page");
};

Routes:

const express = require("express");
const router = express.Router();

// Import controller
const { dummyLink } = require("../controllers/LikeController");

router.get("/dummyroute", dummyLink);

module.exports = router;

index.js:

const express = require("express");
const app = express();
require("dotenv").config();

const PORT = process.env.PORT || 4000;

// Middleware
app.use(express.json());

// Routes
const blog = require("./routes/blog");

// Mount URL
app.use("/api/v1", blog);

// DB fetch
const connectWithDB = require("./config/database");
connectWithDB();

// Start server
app.listen(PORT, () => {
  console.log(`App is started at ${PORT}`);
});

app.get("/", (req, res) => {
  res.send("This is homepage for blog");
});

When I start the server, it starts successfully, and the homepage loads correctly. However, when I try to access the dummyLink API using the URL http://localhost:3000/api/v1/dummyroute, I get the error:

Cannot GET /api/v1/dummyroute

What could be causing this issue, and how can I resolve it?

Node Media Server Problems

I’m trying to setup a livestreaming website and I’m encountering problems when trying to host node media server on my Ubuntu 20.04 VPS. Basically whenever the user starts the livestream it works when a viewer immediately connects to it but after it creates the index04.ts file in the media folder it just stops working completely with this error:

video append of 1308809b failed for segment #7 in playlist 0-https://example.com/live/testing/index.m3u8

(I intentionally made it example.com for this only, It’s normally my actual domain.)

And it console logs this

VIDEOJS: ERROR: (CODE:3 MEDIA_ERR_DECODE) video append of 1308809b failed for segment #7 in playlist 0-https://example.com/live/testing/index.m3u8 bt
(anonymous) @ video.min.js:12
video.min.js:12 VIDEOJS: ERROR: (CODE:3 MEDIA_ERR_DECODE) audio append of 3448b failed for segment #7 in playlist 0-https://example.com/live/testing/index.m3u8 bt
(anonymous) @ video.min.js:12
video.min.js:12 VIDEOJS: ERROR: (CODE:4 MEDIA_ERR_SRC_NOT_SUPPORTED) The media could not be loaded, either because the server or network failed or because the format is not supported

Could anyone help me with this please? Everything works completely fine on a localhost environment which is why I’m incredibly confused.

My Code, server.js:

const NodeMediaServer = require('node-media-server');

const httpConfig = {
  port: 80,
  allow_origin: '*',
  mediaroot: './media',
};

const rtmpConfig = {
  port: 1935,
  chunk_size: 128000,
  gop_cache: true,
  ping: 10,
  ping_timeout: 60,
};

const transformationConfig = {
  ffmpeg: '/usr/bin/ffmpeg',
  tasks: [
    {
      app: 'live',
      hls: true,
      hlsFlags: '[hls_time=4:hls_list_size=10:hls_flags=delete_segments]',
      hlsKeep: false,
      hlsPath: './media',
    },
  ],
  MediaRoot: './media',
};

const config = {
  http: httpConfig,
  rtmp: rtmpConfig,
  trans: transformationConfig,
};

const nms = new NodeMediaServer(config);

nms.on('prePublish', (id, StreamPath, args) => {
  if (process.env.NODE_ENV !== 'production') {
    console.log('prePublish:', id, StreamPath, args);
  }
});

nms.on('postPublish', (id, StreamPath, args) => {
  if (process.env.NODE_ENV !== 'production') {
    console.log('postPublish:', id, StreamPath, args);
  }
});

nms.on('donePublish', (id, StreamPath, args) => {
  if (process.env.NODE_ENV !== 'production') {
    console.log('donePublish:', id, StreamPath, args);
  }
});

nms.on('prePlay', (id, StreamPath, args) => {
  if (process.env.NODE_ENV !== 'production') {
    console.log('prePlay:', id, StreamPath, args);
  }
});

nms.on('postPlay', (id, StreamPath, args) => {
  if (process.env.NODE_ENV !== 'production') {
    console.log('postPlay:', id, StreamPath, args);
  }
});

nms.on('donePlay', (id, StreamPath, args) => {
  if (process.env.NODE_ENV !== 'production') {
    console.log('donePlay:', id, StreamPath, args);
  }
});


process.on('uncaughtException', (err) => {
  console.error('Uncaught Exception:', err);
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});

nms.run();

index.html:

<head>
  <link href="https://vjs.zencdn.net/7.20.2/video-js.css" rel="stylesheet">
</head>
<body>
  <h1>Live Stream</h1>
  <video id="videoPlayer" class="video-js vjs-default-skin" controls autoplay width="640" height="360">
    <source src="https://example.com/live/testing/index.m3u8" type="application/x-mpegURL">
  </video>
  
  <script>
    document.addEventListener("DOMContentLoaded", () => {
      var player = videojs('videoPlayer', {
        techOrder: ['html5', 'flash'],
        sources: [{
          src: 'https://example.com/live/testing/index.m3u8',
          type: 'application/x-mpegURL'
        }]
      });
    });
  </script>

I have tried to reset the VPS, Tried opening the ports using sudo ufw allow. There’s no guides online on how to fix this.

(My VPS has 4vCPU Cores, 6GB RAM & 400GB SSD so I have doubts that system requirements are the problem)

different predictions on same data, TenserflowJS

I have saved a TFJS model to a document in cloud firestore, if I run this code straight from the browser:

      const jsonObject = JSON.parse(TFModeljson);
      loadedModel = await tf.loadLayersModel(tf.io.fromMemory(jsonObject));
      const inputTensor = tf.tensor2d(numericValues, [1, numericValues.length]);
      loadedModel.predict(inputTensor).data().then(prediction => {
         //same predictions based on the same data
      }

It works fine but when I try to run it in a Firebase cloud function like this:

const TFModel = JSON.parse(TFModeljson);
const model = await tf.loadLayersModel(tf.io.fromMemory(TFModel));
            
let type;
            
for (let i = 0; i < looplength; i++) {
    const row = data[i];    
    console.log(row);
    const tensor = tf.tensor2d([row]);
                
    const prediction = model.predict(tensor).dataSync(); 
    console.log('Prediction:', prediction);
}

I get different predictions every time and its not even close, (last runs I got back 1060.4051513671875, 949.4125366210938, 1934.115966796875, -1049.058837890625)
In both pieces of code TFModeljson is the data from Firestore. If I send 3 rows to the cloud function with the same rows I do get 3 times the same prediction back, but when I rerun this function I get another prediction again. Does anyone know what’s wrong with my code?

React table with lazy loading that display the whole table height initially

I am using react-table v8 and I would like to enhance our tables performance as our cells are a little bit complex and we receive thousands of data. Therefore, I think it’s time to switch from client side handeling of data to the server side.

So I have some requirements to implement the Lazy Loading:

  • First, it has to be lazy loading not pagination as we don’t have the concept of pages in our App
  • We need to fetch data as the user scrolls down
  • The table height should be initially displayed without a ‘load more’ button or loading text.
  • The user should be able to navigate freely in the table using the mouse or keyboard. For example, pressing the ‘End’ button should scroll to the latest data. (not the displayed row)

Example

I haven’t found a good example that explains how to achieve this.

Any help would be appreciated.

I have many questions such as :

Should I use the infinite query of the react query ? As it is shown in the docs in this example of react table lazy loading ? As you see, there is no next page concept in my use case since it is a huge long table and the user can scroll freely using the scrollbar.

What if the user scrolls to the end of the page? How do I tell React Table which rows should be displayed initially and which ones should be displayed at the end?

Should I use the pagination options of React Table, or I implement something else myself?

As I have many feature to implement later such as the selection, the sorting, the filter … I need to implement this feature the right way.

Any ideas?

How to create video feed like Tik Tok?

How do I make the video start playing itself when the video is swiped?
When the user just opens the feed feed so that the video starts playing immediately, when there is a swipe to another video, then the new video starts playing, and the old one stops?
Also, the user can pause the video himself when clicking on it

The option that I have now does not work well, autoplay does not occur and when only the 3rd time the video starts, nothing happens with swipes. If you start the video and swap it to another one, the old one will continue to play, and the new one on which the user is located will not play.

export const Feed = () => {
    const { data } = useGetVideoQuery();
    const [activeVideoIndex, setActiveVideoIndex] = useState(0);

    const activateVideo = (index: number) => {
        setActiveVideoIndex(index);
    };

    console.log(data);

    return (
        <div className={styles.feed}>
            {data?.data.map((video, index) => {

                return (
                    <div key={video.video_id} className={styles.video}>
                        <div className={styles.video_wrapper}>
                            <Video
                                video={video}
                                isActive={activeVideoIndex === index}
                                onActivate={() => activateVideo(index)}
                            />
                            <Aside video={video} />
                        </div>

                        <Footer video={video} />
                    </div>
                );
            })}
        </div>
    );
};
type Props = {
    video: DataVideo;
    isActive: boolean;
    onActivate: () => void;
};

export const Video = ({ video, isActive, onActivate }: Props) => {
    const videoRef = useRef<HTMLVideoElement>(null);

    const [isPlaying, setPlaying] = useState(isActive);

    const handleClick = () => {
        const newPlayingState = !isPlaying;
        setPlaying(newPlayingState);

        if (videoRef.current) {
            newPlayingState ? videoRef.current.play() : videoRef.current.pause();
        }
    };

    useEffect(() => {
        if (isActive) {
            setPlaying(true);
            videoRef.current?.play(); 
        } else {
            setPlaying(false);
            videoRef.current?.pause(); 
        }
    }, [isActive]);

    useEffect(() => {
        if (videoRef.current) {
            isPlaying ? videoRef.current.play() : videoRef.current.pause();
        }
    }, [isPlaying]);

    return (
        <div
            className={classNames(styles.video_item, isPlaying ? styles.playing : '')}
            onClick={() => handleClick()}
            onMouseEnter={onActivate}
        >
            <video
                ref={videoRef}
                className={styles.video}
                autoPlay={isActive}
                loop={true}
                src={video.play}
                playsInline={true}
                width='100%'
                height='auto'
                controls={false}
                controlsList='nofullscreen nodownload noremoteplayback'
                preload='auto'
                poster={video.cover}
            />

            {!isPlaying && (
                <div
                    className={styles.video_item__controls}
                    onClick={() => handleClick()}
                >
                    <img
                        src='/public/controls/play.svg'
                        alt='pause'
                        className={styles.control}
                    />
                </div>
            )}
        </div>
    );
};

I tried to play with states, but nothing works, then one works, then the other falls off