Dates is Undefined, Nan on Safari / IOS

I have the following function that converts Excel Date to normal date but it shows as “Undefined, NaN” on IOS and Safari.
My Code:

export const convertExcelDateToMMMDD = (excelDate) => {
      const SECONDS_IN_DAY = 86400;
      const EPOCH_OFFSET = 25569;
      const excelToUnixTimestamp = (excelDate - EPOCH_OFFSET) * SECONDS_IN_DAY;
      const unixTimestamp =
        excelToUnixTimestamp - new Date().getTimezoneOffset() * 60;
      if (isNaN(unixTimestamp)) return "Invalid date";
      const date = new Date(unixTimestamp * 1000);
      const monthNames = [
        "JAN",
        "FEB",
        "MAR",
        "APR",
        "MAY",
        "JUN",
        "JUL",
        "AUG",
        "SEP",
        "OCT",
        "NOV",
        "DEC",
      ];
      const month = monthNames[date.getMonth()];
      const day = date.getDate();
      return `${month} ${day}`;
};

SS: enter image description here

Why I am getting an error ‘Uncaught ReferenceError: require is not defined at app.js:1:19’ when using puppeteer [duplicate]

My problem is that when I try to run my code using require(‘puppeteer’) then I get an error ‘Uncaught ReferenceError: require is not defined at app.js:1:19’

HTML

<body>
    <form action="">
        <input type="url" name="" id="image_input">
        <button id="image_downloader">Search</button>
    </form>
    <section id="image">
            
    </section>
    <script src="app.js"></script>
</body>

JS

const puppetter = require('puppeteer');

const image_input = document.querySelector('#image_input');
const image_downloader = document.querySelector('#image_downloader');
const section_image = document.querySelector('#image');

let image_link_value;
image_downloader.addEventListener('click',(e)=>{
    e.preventDefault();
    image_link_value = image_input.value;
    const createImage = document.createElement('img');
    section_image.append(createImage);
    createImage.setAttribute('src',`${image_link_value}`);
    puppetter_call();
})

function puppetter_call(){
    const openBrowser = puppetter.launch({headless:false});
    let page;
    openBrowser
        .then(function(browser){
            const pageArrPromise = browser.pages();
            return pageArrPromise;
        })
        .then(function(browserPage){
            page = browserPage[0];
            let gotoPromise = page.goto(`${image_link_value}`);
            return gotoPromise
        })
}

Dates is Undefined, Nan on Safari / IOS – Need Fix ASAP

I have the following function that converts Excel Date to normal date but it shows as “Undefined, NaN” on IOS and Safari.
My Code:
`export const convertExcelDateToMMMDD = (excelDate) => {

  const SECONDS_IN_DAY = 86400;
  const EPOCH_OFFSET = 25569;
  const excelToUnixTimestamp = (excelDate - EPOCH_OFFSET) * SECONDS_IN_DAY;
  const unixTimestamp =
    excelToUnixTimestamp - new Date().getTimezoneOffset() * 60;
  if (isNaN(unixTimestamp)) return "Invalid date";
  const date = new Date(unixTimestamp * 1000);
  const monthNames = [
    "JAN",
    "FEB",
    "MAR",
    "APR",
    "MAY",
    "JUN",
    "JUL",
    "AUG",
    "SEP",
    "OCT",
    "NOV",
    "DEC",
  ];
  const month = monthNames[date.getMonth()];
  const day = date.getDate();
  return `${month} ${day}`;
};`

SS: enter image description here

Why I am getting an error ‘Uncaught ReferenceError: require is not defined at app.js:1:19’ when using puppeteer

My problem is that when I try to run my code using require(‘puppeteer’) then I get an error ‘Uncaught ReferenceError: require is not defined at app.js:1:19’

HTML

<body>
    <form action="">
        <input type="url" name="" id="image_input">
        <button id="image_downloader">Search</button>
    </form>
    <section id="image">
            
    </section>
    <script src="app.js"></script>
</body>

JS

const puppetter = require('puppeteer');

const image_input = document.querySelector('#image_input');
const image_downloader = document.querySelector('#image_downloader');
const section_image = document.querySelector('#image');

let image_link_value;
image_downloader.addEventListener('click',(e)=>{
    e.preventDefault();
    image_link_value = image_input.value;
    const createImage = document.createElement('img');
    section_image.append(createImage);
    createImage.setAttribute('src',`${image_link_value}`);
    puppetter_call();
})

function puppetter_call(){
    const openBrowser = puppetter.launch({headless:false});
    let page;
    openBrowser
        .then(function(browser){
            const pageArrPromise = browser.pages();
            return pageArrPromise;
        })
        .then(function(browserPage){
            page = browserPage[0];
            let gotoPromise = page.goto(`${image_link_value}`);
            return gotoPromise
        })
}

Next.js V13 simply not working and I’m stuck

I started recreate a react app in next.js and everything was going well, until i ran into an error which said:

Warning: 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:

I couldn’t fix it, so i removed everything until it was back to the start and it still didn’t work, so I create a new app and I still get the same error.

I am trying re installing next but still the same.

I am now stuck and would appriciate any suggestions.

(is there a way I can just remove next.js and re install?)

How to export fabricjs canvas to high quality video using captureStream and MediaRecorder

I am exporting a video from fabricjs canvas using the following code. everything is working except the quality is very poor and sometimes pixelated specially when it contains images. but when i run the animation on browser everything is smooth and in a good quality, see example photo. please help. thanks

exported video

browser animation

 var canvasStatic =  document.getElementById('canvas');
     const chunks = []; 
     const stream = canvasStatic.captureStream(30);
     const rec = new MediaRecorder(stream); 
           rec.ondataavailable = e => chunks.push(e.data);
           rec.onstop = e => exportBlob(chunks);
           rec.start();
           setTimeout(()=>rec.stop(), duration); // stop recording in x number of seconds <duration> 



     function exportBlob(blob) {

           /** processing the blob **/
          let blob = new Blob(blob, {type: 'video/mp4'})
            const vid = document.createElement('video');
            vid.src = URL.createObjectURL(blob);
            vid.controls = true;
            vid.autoplay = true;
        
            let a = document.createElement('a');
            a.download = 'title.mp4';
  
          }

I try adding parameter on the capturestream as i believe it is for fps? but dint solve the problem.

Angular – How to change the CSS of an element created by TS

I’m trying to apply some styling to a div that was created with TypeScript’s CreatElement, but the styles are not being applied.

component.ts

export class Component implements OnInit {
 bgAnimation!: any;
 numberOfColorBoxes = 400;

 ngOnInit(): void {
  this.bgAnimation = document.getElementById('bgAnimation');
  for (let i = 0; i < this.numberOfColorBoxes; i++) {
    const colorBox = document.createElement('div');
    colorBox.classList.add('colorBox');
    this.bgAnimation.appendChild(colorBox);
   }
 }
}

component.html

<div class="bgAnimation" id="bgAnimation">
 <div class="backgroundAmim"></div>
</div>

component.scss

.colorBox {
 z-index: 2;
 filter: brightness(1.1);
 transition: 2s ease;
 position: relative;
 margin: 2px;
 background: #1d1d1d;
}

I want to filter the data according to the id tag, but in that data there is an array of objects, how do I fix this?

this is how i filtering the game by id
....computed:{
your text filteredGame(){
your text if(!!!this.genreID){
your text return this.games
your text }
your text return this.games.filter(game => {
your text return game.genres.filter(g => {
your text return this.genreID.includes(g.id);
your text }).length>0;//return only filled arrays
your text });
your text },
‘…..’},

enter image description here

Filter doesn’t work and only console logs the fetched data each time checkbox is checked

Every time I click on a checkbox to render products according to their condition value (New, Used, Out of Box), the fetched products don’t render according to their condition value and the console log shows the array of total products fetched from the backend.

Here is what is in the console log each time I click on the New, Used, Out of Box checkbox :

(2) [{…}, {…}]
0
: 
{_id: '6404c8be7e33a2fdf1dad0d6', title: 'les do this again', description: 'ioooi', price: 73783, image: 'https://storage.googleapis.com/deal_app_bucket/DealImages/4cd5ba94-2f20-4302-aa18-954ad34e2d58.png', …}
1
: 
{_id: '640bd8dc9e9cbf1bd34c958a', title: 'new product ', description: 'jiwndewniw', price: 111, image: 'https://storage.googleapis.com/deal_app_bucket/DealImages/65593976-7ace-4754-9d5f-c0f50ce373c8.png', …}
length
: 
2

One product has a condition value of “Out of Box” and another product has a condition value of “New”. Whenever I click on any checkbox, those two products stay displayed no matter what when one should only display if the New checkbox was clicked as an example.

I have a parent component that fetches the products and passes props down to Accordian.jsx (component that renders the products) and Filter.jsx (component that renders checkboxes)

Here is the parent component :

import React, { useState, useEffect } from 'react'
import Filter from './Filter'
import Accordian from './Accordian'
import { useParams } from 'react-router-dom'
import axios from 'axios'
import { Box, filter } from '@chakra-ui/react'



const ProductListSubCategory = () => {


  const [filteredProducts, setFilteredProducts] = useState([]);
  const [filters, setFilters] = useState({ isNew: false, isUsed: false,  isOutOfBox : false });


 
 
  const {subCategory} = useParams();
  const {mainCategory} = useParams();

  const [subCategoryLink, setSubCategoryLink] = useState([]);
  const [mainCategoryLink, setMainCategoryLink] = useState([]);

  const [subCategoryProducts, setSubCategoryProducts] = useState([]);

  useEffect(() => {
    const fetchProducts = async () => {
      try {
        const res = await axios.get(`http://localhost:3005/product/category/${subCategory}`);
        const productIds = res.data.products;
        console.log(productIds);
        const productRequests = productIds.map(productId => axios.get(`http://localhost:3005/product/${productId}`));
        console.log(productRequests)
        const productResponses = await Promise.all(productRequests);
        const products = productResponses.map(response => response.data);
        console.log(products);
        setSubCategoryProducts(products);
        setFilteredProducts(products);
      } catch (error) {
        console.error(error);
        console.error(error?.response?.data ?? error.message);
      }
    };
    fetchProducts();
  }, [subCategory]);

  useEffect(() => {
    const fetchSubCategoryById = async () => {
      try {
        const response  = await axios.get(`http://localhost:3005/category/${subCategory}`)
        setSubCategoryLink(response.data)
      } catch (err) {
        console.error(err)
      }
    }
    fetchSubCategoryById();
  },[])

  useEffect(() => {
    const fetchMainCategoryById = async () => {
      try {
        const response  = await axios.get(`http://localhost:3005/category/main-category/${mainCategory}`)
        setMainCategoryLink(response.data)
        console.log(mainCategoryLink)
      } catch (err) {
        console.error(err)
      }
    }
    fetchMainCategoryById();
  },[])


  useEffect(() => {
    // Filter products based on checkbox selection
    const filtered = subCategoryProducts.filter((product) => {
        console.log(product.condition)
      if (filters.isNew && filters.isUsed) {
        console.log('New and Used was chosen')
        return true;
      } else if (filters.isNew) {
        console.log('New was chosen and set to True')
        return product.condition === "New";
      } else if (filters.isUsed) {
        return product.condition === "Used";
      } else if (filters.isOutOfBox) {
        return product.condition === "Out of Box"
      } else {
        return true;
      }
    });
    
    setFilteredProducts(filtered);
  }, [filters, subCategoryProducts]);

  const handleFilterChange = (event) => {
    const { name, checked } = event.target;
    setFilters((prevFilters) => ({ ...prevFilters, [name]: checked }));
  };

  console.log(filteredProducts);


      return (
        <>
        <Box sx={{display:"inline-flex", justifyContent:"center"}}>

           {/* <Filter productCondition={productCondition || []} setProductCondition={handleSetProductCondition} subCategoryProducts={subCategoryProducts}/>  */}
           <Filter filters={filters} handleFilterChange={handleFilterChange}/> 
          {/* <Accordian subCategoryProducts={subCategoryProducts}  productCondition={productCondition || []} subCategoryLink={subCategoryLink} mainCategoryLink={mainCategoryLink}  /> */}
          <Accordian subCategoryProducts={filteredProducts} subCategoryLink={subCategoryLink} mainCategoryLink={mainCategoryLink}    />
        </Box>
        </>
      )
}

export default ProductListSubCategory

Here is Filter.jsx :

const Filter = ({filters, handleFilterChange }) => {
  <Checkbox
        value="New"
        mr={3}
        Checked={filters.isNew}
        onChange={handleFilterChange}
      >
        New
      </Checkbox>
      <Checkbox
        value="Used"
        mr={3}
        Checked={filters.isUsed}
        onChange={handleFilterChange}
      >
        Used
      </Checkbox>
      <Checkbox
        value="Out of Box"
        Checked={filters.isOutOfBox}
        onChange={handleFilterChange}
      >
        Out of Box
      </Checkbox>

Here is Accordian.jsx :

const Accordian = ({subCategoryProducts, subCategoryLink, mainCategoryLink} ) => {
   {subCategoryProducts.map((product) => (
        <GridItem key={product._id}>
          <Card 
            id={product._id}
            image={product.image}
            title={product.title}
            price={product.price}
            description={product.description}
            location={product.location}
            condition={product.condition}
            category={product.category}
            seller={product.seller}
          />
        </GridItem>
      ))}

Any help from an experienced React or Javascript programmer on why the products don’t render according to the condition value that is chosen from the checkbox and why the console log shows the two products each time a checkbox is clicked would be much appreciated. Thank you.

Simply display a local PDF file in a React web-app

I am making a portfolio website for myself as a React webapp. I would like to have a Resume page on the website which would simply display my Resume. When I had originally made a HTML version of my website I could achieve this with iframe.

When I’ve tried this in React the iframe display a copy of the current display page instead of my pdf. Is there a simple way to just display a pdf saved locally in the webapp?

How to change the classes of multiple divs each after a time period in React

I’ve just learned React and I’m a making a Simon game as a first practice app. I’m having trouble getting the divs to “light up” one after another, after a time period.

In the code below, in my Cube component, I am attempting to iterate through a test array (computerMoves), and for each move to “light up” one of the divs by adding the class “on” (increase in brightness) for a second.

The desired result is to see side1 lighten for 1 second and then turn off, then the same for side 2, then the same for side 3. The result I am getting is I am only seeing this happen for side 3.

Where am I going wrong?

import { useEffect, useState } from "react";
import "../CSS/Cube.css";

export default function Cube({ computerTurn }) {
  const [computerMoves, setComputerMoves] = useState([1, 2, 3]);
  const [side1Class, setSide1Class] = useState("side1");
  const [side2Class, setSide2Class] = useState("side2");
  const [side3Class, setSide3Class] = useState("side3");

  useEffect(() => {   
    // When it's the computer's turn, flash the cube colors according to computerMoves
    if (computerTurn === true) {
      computerMoves.forEach((move) => {
        let seconds = 1;
        let timer;

        // Flash side according to move
        if (move === 1) {
          setSide1Class("side1 on");
          timer = setTimeout(() => setSide1Class("side1"), seconds * 1000);
        } else if (move === 2) {
          setSide2Class("side2 on");
          timer = setTimeout(() => setSide2Class("side2"), seconds * 1000);
        } else if (move === 3) {
          setSide3Class("side3 on");
          timer = setTimeout(() => setSide3Class("side3"), seconds * 1000);
        }
        return () => clearTimeout(timer);
      });
    }
  }, [computerTurn]);

  return (
    <div className="cube">
      <div className={side1Class}></div>
      <div className={side2Class}></div>
      <div className={side3Class}></div>
    </div>
  );
}

Map() returns array items multiple times – React

I’m new in react and I’m trying to get a json that contains an array of objects (sent by an API REST)

This is the json I’m getting from the API

{
"data": [
    {
        "id_pelicula": 1,
        "Nombre_pelicula": "Nocturnal Animals",
        "anio_estreno": "2016",
        "url_poster": "https://cdn.abicart.com/shop/16575/art75/h2859/177222859-origpic-9d7682.jpg"
    },
    {
        "id_pelicula": 2,
        "Nombre_pelicula": "Prisoners",
        "anio_estreno": "2013",
        "url_poster": "https://m.media-amazon.com/images/M/MV5BMTg0NTIzMjQ1NV5BMl5BanBnXkFtZTcwNDc3MzM5OQ@@._V1_.jpg"
    }
]

}

This is the code of my component:

import { Link } from 'react-router-dom';
import axios  from 'axios';
import { useCallback, useEffect, useState } from "react";

export const PeliCard = () => {

    const [peliculas, setPeliculas] = useState([]);

    useEffect(() => {
        axios.get('http://localhost:8080/getPeliculas')
            .then(response => {
                console.log(response.data)
                setPeliculas(response.data.data)
        })
    }, [])

    return (
        <div className="col animate__animated animate__fadeIn">               
                                <div className="col-4">
                                     { peliculas.map((pelicula, index) => (
                                    <img key={index} src={ pelicula.url_poster } className="card-img" />
                                    ))}
                                </div>
        </div>
    )
}


When I run the app, it shows the elements of the array multiple times, when it only should show 2 elements.

enter image description here

How could I solve it? thanks in advance

Redux: A state mutation was detected between dispatches

I was trying to implement the authentication part of my project, but at the login page, it always shows this error when I click the sign in button:


Uncaught Error: Invariant failed: A state mutation was detected between dispatches, in the path 'auth.access'.  This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)
   at invariant (immutableStateInvariantMiddleware.ts:25:1)
   at immutableStateInvariantMiddleware.ts:256:1
   at Object.measureTime (utils.ts:10:1)
   at Object.dispatch (immutableStateInvariantMiddleware.ts:249:1)
   at dispatch (<anonymous>:1:55003)
   at onClickLogIn (LogInPage.js:50:1)
   at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
   at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
   at invokeGuardedCallback (react-dom.development.js:4277:1)
   at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)

As it suggested, I tried to debug in the onClickLogIn() function but failed to find the reason. I am using @reduxjs/toolkit, so I was thinking that it helped me manage the immutations within the reducer. However, even after I changed the code in reducer to make it explicitly change everything in an immutable way, the same error appeared again and again. Could anyone help me take a look into the reason? thanks a lot! Here is a snippet of my code:
store.js

import {configureStore} from "@reduxjs/toolkit";
import authReducer from './authSlice';
import requestReducer from './requestSlice';
import {getAccessToken, getRefreshToken, setAccessToken, setRefreshToken} from "../utils/token";
import * as apiCalls from '../api/apiCalls'
let preloadedState = {
    auth: {
        access: '',
        refresh: '',
        loggedIn: false,
    },
    request: {
        entities: [],
    }
};

const refreshToken = getRefreshToken();
if (refreshToken !== '')    {
    apiCalls.refresh({'refresh': refreshToken}).then(resp => {
        setAccessToken(resp.data.access);
        setRefreshToken(resp.data.refresh);
        preloadedState.auth.access = getAccessToken();
        preloadedState.auth.refresh = getRefreshToken();
        preloadedState.auth.loggedIn = true;
        apiCalls.setAuthHeader(resp.data.access);
        console.log('detect previous logged in: ', preloadedState);
    }).catch(err => {
        console.log('no auth / expired token in localstorage');
    });
}
const store = configureStore({
    reducer: {
        auth: authReducer,
        request:requestReducer,
    },
    preloadedState: preloadedState
});

const updateAuth = (state) => {
    const access = state.auth.access;
    const refresh = state.auth.refresh;
    setAccessToken(access);
    setRefreshToken(refresh);
    apiCalls.setAuthHeader(access);
    console.log('detect change in auth.')
}

console.log(store.getState());
store.subscribe(() => {
    updateAuth(store.getState());
});

export default store;

authSlice.js

import {createSlice} from "@reduxjs/toolkit";
import * as apiCalls from '../api/apiCalls'

const authSlice = createSlice({
    name: 'auth',
    initialState: null,
    reducers: {
        assignToken(state, action) {
            return {
                loggedIn: true,
                access: action.payload.access,
                refresh: action.payload.refresh,
            };
        },
        logOutUser(state, action) {
            return {
                loggedIn: false,
                access: '',
                refresh: '',
            };
        },
    }
});

export const {
    assignToken,
    logOutUser,
} = authSlice.actions

export default authSlice.reducer;

export function handleLogin(confidential) {
    return async function handleLoginThunk(dispatch, getState) {
        return apiCalls.getToken(confidential).then((response) => {
                console.log('log in: ', response);
                dispatch(assignToken({...response.data}));
            }
        ).catch((err) => {
            return Promise.reject(err.message);
        });
    }
};

export function handleRefresh(refresh) {
    return async function handleRefreshThunk(dispatch, getState) {
        apiCalls.refresh({'refresh': refresh}).then((response) => {
                console.log('refresh token:', ...response);
                dispatch(assignToken(...response.data));
            }
        ).catch((err) => {
        });
    }
};

export function handleLogOut() {
    return async function handleLogOutThunk(dispatch, getState) {
        const refreshToken = getState().auth.refresh;
        console.log('logout: ', refreshToken);
        dispatch(logOutUser());
        apiCalls.logout({refresh_token: refreshToken})
            .then((response) => {
            }).catch(error => {
        });
    }
};

LoginPage.js

import * as React from 'react';
import Avatar from '@mui/material/Avatar';
import Button from '@mui/material/Button';
import CssBaseline from '@mui/material/CssBaseline';
import TextField from '@mui/material/TextField';
import Link from '@mui/material/Link';
import Paper from '@mui/material/Paper';
import Box from '@mui/material/Box';
import Grid from '@mui/material/Grid';
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import Typography from '@mui/material/Typography';
import {useDispatch, useSelector} from "react-redux"
import {createTheme, ThemeProvider} from '@mui/material/styles';
import {useEffect, useState} from "react";
import * as apiCalls from "../api/apiCalls";
import {clearErrorMessage, handleLogin, handleLogOut, handleRefresh, logInUser} from "../redux/authSlice";
import Copyright from "../components/Copyright";
import axios from "axios";
import {useNavigate} from "react-router-dom";
import {Alert} from "@mui/material";
import {getRefreshToken} from "../utils/token";

const theme = createTheme();


export default function SignInSide() {
    const navigate = useNavigate();
    const [apiCallPending, setApiCallPending] = useState(false);
    const [apiError, setApiError] = useState('');
    const [role, setRole] = useState('Staff');
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const loggedIn = useSelector(state => state.loggedIn);
    const errMsg = useSelector(state => state.message);
    const dispatch = useDispatch();
    const nextRole = () => {
        return role === 'Staff' ? 'Patient' : 'Staff';
    };
    // useEffect(() => {
    //     if (loggedIn)
    //         navigate('/dashboard', {state: {from: '/login'}});
    // });
    const onClickChangeRole = () => {
        setRole(nextRole());
    }
    const onClickLogIn = (event) => {
        event.preventDefault();
        setApiCallPending(true);
        const data = {username: username, password: password};
        dispatch(handleLogin(data)).then(response => {
            console.log('Log In Successfully: ', response);
            navigate('/dashboard', {state: {from: '/login'}});
        }).catch(err => {
        });
    };





    return (
        <ThemeProvider theme={theme}>
            <Grid container component="main" sx={{height: '100vh'}}>
                <CssBaseline/>
                <Grid
                    item
                    xs={false}
                    sm={4}
                    md={7}
                    sx={{
                        backgroundImage: 'url(https://images.unsplash.com/photo-1594824476967-48c8b964273f?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MjF8fGRvY3RvcnxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=400&q=60)',
                        backgroundRepeat: 'no-repeat',
                        backgroundColor: (t) =>
                            t.palette.mode === 'light' ? t.palette.grey[50] : t.palette.grey[900],
                        backgroundSize: 'cover',
                        backgroundPosition: 'center',
                    }}
                />
                <Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square>
                    <Box
                        sx={{
                            my: 8,
                            mx: 4,
                            display: 'flex',
                            flexDirection: 'column',
                            alignItems: 'center',
                        }}
                    >
                        <Avatar sx={{m: 1, bgcolor: 'secondary.main'}}>
                            <LockOutlinedIcon/>
                        </Avatar>
                        <Typography component="h1" variant="h5">
                            {role} Sign in
                        </Typography>
                        <Box component="form" noValidate sx={{mt: 1}}>
                            <TextField
                                margin="normal"
                                required
                                fullWidth
                                id="username"
                                label="Username"
                                name="username"
                                value={username}
                                autoComplete="username"
                                autoFocus
                                onChange={(event) => {
                                    setUsername(event.target.value)
                                }}
                            />
                            {role === 'Staff' && <TextField
                                margin="normal"
                                required
                                fullWidth
                                name="password"
                                label="Password"
                                type="password"
                                id="password"
                                value={password}
                                onChange={(event) => {
                                    setPassword(event.target.value)
                                }}
                                autoComplete="current-password"
                            />}
                            {/*<FormControlLabel*/}
                            {/*    control={<Checkbox value="remember" color="primary"/>}*/}
                            {/*    label="Remember me"*/}
                            {/*/>*/}

                            {apiError !== '' && <Alert severity="error">{apiError}</Alert>}
                            <Button
                                type="submit"
                                fullWidth
                                variant="contained"
                                onClick={onClickLogIn}
                                sx={{mt: 3, mb: 2}}
                            >
                                Sign In
                            </Button>
                            <Button
                                onClick={onClickChangeRole}
                                fullWidth
                                variant="contained"
                                sx={{mb: 2}}
                            >
                                {`${nextRole()} Log In`}
                            </Button>
                            <Grid container>
                                <Grid item xs>
                                    <Link href="#" variant="body2">
                                        Forgot password?
                                    </Link>
                                </Grid>
                                <Grid item>
                                    <Link href="#" variant="body2">
                                        {"Don't have an account? Sign Up"}
                                    </Link>
                                </Grid>
                            </Grid>
                            <Copyright sx={{mt: 5}}/>
                        </Box>
                    </Box>
                </Grid>
            </Grid>
        </ThemeProvider>
    );
}

Videos causing GET requests every 4 seconds and TB of bandwidth being used

I recently developed a completely custom javascript video player and noticed in my server logs a spike in bandwidth of 20-80 GB/min over the course of 3 hours on one day (about 4 TB total usage) and due to one user watching videos at 720p (5 Mbps) and 1080p (8 Mbps). I had a similar spike of 10-40 GB/min for over an hour for another user on a separate day (about 0.7 TB total usage) due to watching the same videos.

The logs show GET requests for the videos approximately every 4 seconds. I of course cannot duplicate this even with deleting my cache completely. I’ve read that browsers request ranges of data and these entries might correspond to that, however not at 20 GB / minute.

This behavior seems to only appears consistently on a Mac, but I’m not positive.

I don’t believe it is code related, and since I can’t duplicate, I’m assuming it browser related. Any known issues with browsers or anything I can do to deal with this to prevent TB of bandwidth being used?

Sample Log Data

100.123.115.102 - - [10/Feb/2023:12:42:26 -0800] "GET /mp4/videeo.mp4 HTTP/2.0" 206 4204431394 "https://www.example.com/video.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15"
100.123.115.102 - - [10/Feb/2023:12:42:30 -0800] "GET /mp4/videeo.mp4 HTTP/2.0" 206 4201941026 "https://www.example.com/video.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15"
100.123.115.102 - - [10/Feb/2023:12:42:34 -0800] "GET /mp4/videeo.mp4 HTTP/2.0" 206 4198991906 "https://www.example.com/video.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15"
100.123.115.102 - - [10/Feb/2023:12:42:38 -0800] "GET /mp4/videeo.mp4 HTTP/2.0" 206 4196763682 "https://www.example.com/video.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15"
100.123.115.102 - - [10/Feb/2023:12:42:42 -0800] "GET /mp4/videeo.mp4 HTTP/2.0" 206 4193880098 "https://www.example.com/video.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15"
100.123.115.102 - - [10/Feb/2023:12:42:45 -0800] "GET /mp4/videeo.mp4 HTTP/2.0" 206 4191258658 "https://www.example.com/video.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15"
100.123.115.102 - - [10/Feb/2023:12:42:49 -0800] "GET /mp4/videeo.mp4 HTTP/2.0" 206 4188899362 "https://www.example.com/video.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15"
100.123.115.102 - - [10/Feb/2023:12:42:54 -0800] "GET /mp4/videeo.mp4 HTTP/2.0" 206 4186015778 "https://www.example.com/video.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15"

Why does the arrow in that slider doesnt work?

I made a Slider for my Website and one of the arrows is completely cracked. I have no idea why.
See here:

Why???

I have no idea what to do because i dont even know where to search for that problem. Is it a CSS or JS problem?

Here is the JS, HTML and CSS Code:

HTML:

<li class="l-section section">
              <div class="work">
                <h2>Contact me</h2>
                <div class="work--lockup">
                  <ul class="slider">
                    <li class="slider--item slider--item-left">
                      <a href="mailto:mail">
                        <div class="slider--item-image">
                          <img src="assets/img/work-victory.jpg" alt="E-Mail">
                        </div>
                        <p class="slider--item-title">E-Mail</p>
                        <p class="slider--item-description">Send me an E-Mail and I would love to help you.</p>
                      </a>
                    </li>
                    <li class="slider--item slider--item-center">
                      <a href="#0">
                        <div class="slider--item-image">
                          <img src="assets/img/work-metiew-smith.jpg" alt="Fiverr">
                        </div>
                        <p class="slider--item-title">Fiverr</p>
                        <p class="slider--item-description">Book me directly on Fiverr and get you Website done in a few days.</p>
                      </a>
                    </li>
                    <li class="slider--item slider--item-right">
                      <a href="#0">
                        <div class="slider--item-image">
                          <img src="assets/img/work-alex-nowak.jpg" alt="Shop">
                        </div>
                        <p class="slider--item-title">Shop</p>
                        <p class="slider--item-description">Check out my premium Templates and exclusive services.</p>
                      </a>
                    </li>
                  </ul>
                  <div class="slider--prev">
                    <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
                      viewBox="0 0 150 118" style="enable-background:new 0 0 150 118;" xml:space="preserve">
                    <g transform="translate(0.000000,118.000000) scale(0.100000,-0.100000)">
                      <path d="M561,1169C525,1155,10,640,3,612c-3-13,1-36,8-52c8-15,134-145,281-289C527,41,562,10,590,10c22,0,41,9,61,29
                        c55,55,49,64-163,278L296,510h575c564,0,576,0,597,20c46,43,37,109-18,137c-19,10-159,13-590,13l-565,1l182,180
                        c101,99,187,188,193,199c16,30,12,57-12,84C631,1174,595,1183,561,1169z"/>
                    </g>
                    </svg>
                  </div>
                  <div class="slider--next">
                    <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 150 118" style="enable-background:new 0 0 150 118;" xml:space="preserve">
                    <g transform="translate(0.000000,118.000000) scale(0.100000,-0.100000)">
                      <path d="M870,1167c-34-17-55-57-46-90c3-15,81-100,194-211l187-185l-565-1c-8BQAzQwVETtFWGmAFZjAwNSYA7M4EczfocpPa2kZ6AiC1tVQuAhJTRjLG5Nkk4QqFWHxiKBdi6RuUFjC5zMhvhUyK7tatMA-20,39-29,61-29c28,0,63,30,298,262c147,144,272,271,279,282c30,51,23,60-219,304C947,1180,926,1196,870,1167z"/>
                    </g>
                    </svg>                    
                  </div>
                </div>
              </div>
            </li>

CSS:

.work {
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    width: 960px;
    max-width: 80%;
    height: 100%;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
    -webkit-box-pack: center;
    -webkit-justify-content: center;
    -ms-flex-pack: center;
    justify-content: center;
    margin: 0 auto
}

@media (max-width: 1180px) {
    .work {
        max-width: 100%
    }
}

.work h2 {
    margin: 0 0 20px 0;
    font-size: 30px;
    text-align: center
}

.work--lockup {
    position: relative
}

.work--lockup .slider {
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    width: 80%;
    margin: 0 auto;
    padding: 0;
    list-style: none
}

.work--lockup .slider--item {
    position: absolute;
    display: none;
    text-align: center
}

.work--lockup .slider--item a {
    text-decoration: none;
    color: #858585
}

.work--lockup .slider--item-title {
    margin-top: 10px;
    font-size: 12px;
    font-weight: 700;
    text-transform: uppercase
}

.work--lockup .slider--item-description {
    display: none;
    max-width: 250px;
    margin: 0 auto
}

.work--lockup .slider--item-image {
    width: 150px;
    height: 150px;
    margin: 0 auto;
    border-radius: 50%;
    overflow: hidden
}

.work--lockup .slider--item-image img {
    width: 100%
}

.work--lockup .slider--item-left {
    top: 50%;
    left: 0;
    -webkit-transform: translateY(-50%);
    transform: translateY(-50%);
    display: block
}

.work--lockup .slider--item-right {
    top: 50%;
    right: 0;
    -webkit-transform: translateY(-50%);
    transform: translateY(-50%);
    display: block
}

.work--lockup .slider--item-center {
    position: relative;
    top: 30px;
    left: 50%;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
    display: block
}

.work--lockup .slider--item-center a {
    color: #fff
}

.work--lockup .slider--item-center .slider--item-title {
    margin-top: 25px;
    font-size: 16px
}

.work--lockup .slider--item-center .slider--item-description {
    display: block
}

.work--lockup .slider--item-center .slider--item-image {
    width: 300px;
    height: 300px
}

.work--lockup .slider--next,
.work--lockup .slider--prev {
    position: absolute;
    top: 160px;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    width: 50px;
    height: 50px;
    -webkit-box-align: center;
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
    -webkit-box-pack: center;
    -webkit-justify-content: center;
    -ms-flex-pack: center;
    justify-content: center;
    background-color: #282828;
    border-radius: 50%;
    cursor: pointer
}

.work--lockup .slider--next svg,
.work--lockup .slider--prev svg {
    width: 20px;
    fill: #fff
}

.work--lockup .slider--next {
    right: 0
}

.work--lockup .slider--prev {
    left: 0
}

@media (max-width: 900px) {
    .work--lockup .slider--item-image {
        width: 120px;
        height: 120px
    }

    .work--lockup .slider--item-center .slider--item-image {
        width: 240px;
        height: 240px
    }

    .work--lockup .slider--next,
    .work--lockup .slider--prev {
        top: 130px
    }
}

@media (max-width: 767px) {
    .work--lockup .slider {
        width: 75%
    }

    .work--lockup .slider--item-image {
        width: 90px;
        height: 90px
    }

    .work--lockup .slider--item-center .slider--item-image {
        width: 190px;
        height: 190px
    }

    .work--lockup .slider--next,
    .work--lockup .slider--prev {
        top: 105px
    }
}

@media (max-width: 600px) {
    .work--lockup .slider {
        width: auto
    }

    .work--lockup .slider--item-left,
    .work--lockup .slider--item-right {
        display: none
    }
}

JS:

  function workSlider() {

    $('.slider--prev, .slider--next').click(function() {

      var $this = $(this),
          curLeft = $('.slider').find('.slider--item-left'),
          curLeftPos = $('.slider').children().index(curLeft),
          curCenter = $('.slider').find('.slider--item-center'),
          curCenterPos = $('.slider').children().index(curCenter),
          curRight = $('.slider').find('.slider--item-right'),
          curRightPos = $('.slider').children().index(curRight),
          totalWorks = $('.slider').children().length,
          $left = $('.slider--item-left'),
          $center = $('.slider--item-center'),
          $right = $('.slider--item-right'),
          $item = $('.slider--item');

      $('.slider').animate({ opacity : 0 }, 400);

      setTimeout(function(){

      if ($this.hasClass('slider--next')) {
        if (curLeftPos < totalWorks - 1 && curCenterPos < totalWorks - 1 && curRightPos < totalWorks - 1) {
          $left.removeClass('slider--item-left').next().addClass('slider--item-left');
          $center.removeClass('slider--item-center').next().addClass('slider--item-center');
          $right.removeClass('slider--item-right').next().addClass('slider--item-right');
        }
        else {
          if (curLeftPos === totalWorks - 1) {
            $item.removeClass('slider--item-left').first().addClass('slider--item-left');
            $center.removeClass('slider--item-center').next().addClass('slider--item-center');
            $right.removeClass('slider--item-right').next().addClass('slider--item-right');
          }
          else if (curCenterPos === totalWorks - 1) {
            $left.removeClass('slider--item-left').next().addClass('slider--item-left');
            $item.removeClass('slider--item-center').first().addClass('slider--item-center');
            $right.removeClass('slider--item-right').next().addClass('slider--item-right');
          }
          else {
            $left.removeClass('slider--item-left').next().addClass('slider--item-left');
            $center.removeClass('slider--item-center').next().addClass('slider--item-center');
            $item.removeClass('slider--item-right').first().addClass('slider--item-right');
          }
        }
      }
      else {
        if (curLeftPos !== 0 && curCenterPos !== 0 && curRightPos !== 0) {
          $left.removeClass('slider--item-left').prev().addClass('slider--item-left');
          $center.removeClass('slider--item-center').prev().addClass('slider--item-center');
          $right.removeClass('slider--item-right').prev().addClass('slider--item-right');
        }
        else {
          if (curLeftPos === 0) {
            $item.removeClass('slider--item-left').last().addClass('slider--item-left');
            $center.removeClass('slider--item-center').prev().addClass('slider--item-center');
            $right.removeClass('slider--item-right').prev().addClass('slider--item-right');
          }
          else if (curCenterPos === 0) {
            $left.removeClass('slider--item-left').prev().addClass('slider--item-left');
            $item.removeClass('slider--item-center').last().addClass('slider--item-center');
            $right.removeClass('slider--item-right').prev().addClass('slider--item-right');
          }
          else {
            $left.removeClass('slider--item-left').prev().addClass('slider--item-left');
            $center.removeClass('slider--item-center').prev().addClass('slider--item-center');
            $item.removeClass('slider--item-right').last().addClass('slider--item-right');
          }
        }
      }

    }, 400);

    $('.slider').animate({ opacity : 1 }, 400);

    });

  }

I haven’t try anything cause I have no clue why this happens.