How to run a function that logs an updaing state, every 2 seconds? [duplicate]

I have a video component in my React project. I receive the current time and the status(paused or playing) of the playing video. And I want to run a function every 2 seconds as long as the video is being played. This function logs an updating state.

When I run the code below, the logFunction runs every 2 seconds but it logs the initial state, not the updated state. I also tried adding currentTime to the dependencies of the useEffect. But this time it logs every time that currentTime changes, not every 2 seconds.

Note: When the video is being played status is true, otherwise it’s false.

CourseVide.jsx :

const CourseVideo = () => {
  const { videoDetails } = useVideoPlayer();
  const { currentTime, status } = videoDetails;

    const logFunction = () => {
      console.log('Current Time:', currentTime);
    };

    useEffect(() => {
      let intervalId;
      if (status) {
        intervalId = setInterval(logFunction, 2000);
      }
      return () => {
        clearInterval(intervalId);
      };
    }, [status]);


  return (
    <video
        className="video"
        ref={videoRef}
        width="300"
        height="300"
        controls
        controlsList="nodownload noplaybackrate"
        src={videos[selectedVideo-1].src}
        type="video/mp4"
      />
  );
};

export default CourseVideo;

bxSlider:bug when carousel too fast

Description:

scrolling back and forth on through the carousel too fast will sometimes break the carousel and cause the first and last item in the carousel to not have the scroll stop in the correct spot.

my code:

var bx1 = $('.featured-products').bxSlider({
      slideWidth: windowsize,
      minSlides: 1,
      maxSlides: 1,
      moveSlides: 1,
      slideMargin: 5,
      autoHover: true,
      pause: 4000,
      speed: 500,
      auto: false,
      touchEnabled: true,
      infiniteLoop: false,
      hideControlOnEnd: true
});

question:
enter image description here

View the bx-slider document, modify the width of the slidewidth, set specific numbers, and obtain the current size.

angular RouterReuseStrategy is not working for router with params

I have two components called A,B. I need form data of component B when re-routed back from component A. So, I have implemented RouterReuseStrategy. But, it works fine only for router without params but failed to retrieve the form data for router with params.

router-strategy.ts

import {RouteReuseStrategy,ActivatedRouteSnapshot,DetachedRouteHandle,} from '@angular/router';

export class CustomRouteReuseStrategy implements RouteReuseStrategy {
  private routeLeftFrom: string | undefined;
  private handlers: { [key: string]: DetachedRouteHandle } = {};

  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    this.routeLeftFrom = route.routeConfig!.path;
    return route.data['shouldReuseRoute'] || false;
  }

  store(route: ActivatedRouteSnapshot, handler: DetachedRouteHandle): void {
    console.log('[router-reuse] storing handler');
    if (handler) {
      this.handlers[this.getUrl(route)] = handler;
    }
  }

  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    var wasRoutePreviouslyDetached =
      !!this.handlers[route.url.join('/') || route.parent!.url.join('/')];
    if (wasRoutePreviouslyDetached) {
      var reuseRouteFromVerified =
        route.data['reuseRoutesFrom'].indexOf(this.routeLeftFrom) > -1;

      if (reuseRouteFromVerified) {
        return true;
      }
    }
    return false;
  }

  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
    if (!route.routeConfig || route.routeConfig.loadChildren) {
      return null;
    }

    return this.handlers[this.getUrl(route)];
  }

  shouldReuseRoute(future: ActivatedRouteSnapshot,current: ActivatedRouteSnapshot): boolean {
    let reUseUrl = false;

    if (future.routeConfig) {
      if (future.routeConfig.data) {
        reUseUrl = future.routeConfig.data['reuse'];
      }
    }
    const defaultReuse = future.routeConfig === current.routeConfig;

    return reUseUrl || defaultReuse;
  }

  getUrl(route: ActivatedRouteSnapshot): string {
    if (route.routeConfig) {
      const url = route.routeConfig.path;
      console.log('[router-reuse] returning url', url);

      return url as string;
    }

    throw new Error('Route configuration is missing for the provided route.');
  }
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {
  MatButtonModule,
  MatCheckboxModule,
  MatInputModule,
  MatSelectModule,
  MatDatepickerModule,
  MatNativeDateModule,
} from '@angular/material';
import { PageAComponent } from './page-a/page-a.component';
import { PageBComponent } from './page-b/page-b.component';
import { PageCComponent } from './page-c/page-c.component';
import { RouteReuseStrategy, RouterModule, Routes } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { CustomRouteReuseStrategy } from './router-strategy';

export let browserRefresh = false;

const appRoutes: Routes = [
  { path: 'a', component: PageAComponent },
  // {
  //   path: 'b',
  //   component: PageBComponent,
  //   data: {
  //     shouldReuseRoute: true,
  //     reuseRoutesFrom: ['a'],
  //   },
  // },
  {
    path: 'b/:userID',
    component: PageBComponent,
    data: {
      shouldReuseRoute: true,
      reuseRoutesFrom: ['a'],
    },
  },
];

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    BrowserAnimationsModule,
    ReactiveFormsModule,
    MatButtonModule,
    MatCheckboxModule,
    MatInputModule,
    MatSelectModule,
    MatDatepickerModule,
    MatNativeDateModule,
    RouterModule.forRoot(appRoutes),
    HttpClientModule,
  ],
  declarations: [AppComponent, PageAComponent, PageBComponent, PageCComponent],
  bootstrap: [AppComponent],
  providers: [
    {
      provide: RouteReuseStrategy,
      useClass: CustomRouteReuseStrategy,
    },
  ],
})
export class AppModule {}

Attaching Stackblitz for ref.

Solution I am looking for: Need form data(in component B) after re-route from component A.The route should be with params.

Drop down menu not showing when hovering on an element

I have wanted to make a menu appear upon hovering on #navigation-region
shown below are the html css and javascript

the javascript just is for adding the active class on the #navigation-region
and on the CSS the added there that a part for the active class that will show the menu that is previously hidden

<div> 
 <div class="support-section" class="nav-secondary__support-link">
                <ul class="nav__support-links">
                    <li id="support-phone-usa" class="support-phone">
                        <a href="tel:asdasdas" ><img src="h" alt="Phone Icon">aasdasd6</a>
                    </li>
                    <li id="support-phone-int" class="support-phone">
                        <a href="asdasdasd" >Iasdasdasd</a>
                    </li >
                    <li id="navigation-region" class="">
                        <a href="#" onclick="return false;">Region: USA/Intl
                            <span><img src="" alt="icon arrow" id="arrow"></span>
                        </a>
                    </li>
                        <ul class="nav-secondary__dropdown nav-secondary__dropdown-region">
                            <li class="nav-secondary__dropdown-link nav-secondary__dropdown-title">Select your preferred<span>country / region:</span></li>
                            <span class="nav-secondary__hr"></span>
                            <li class="link nav-secondary__dropdown-link-region">
                                <a href="asdasdasd" lang="en-US"><picture><source srcset="/asdasdasd" media="(min-width: 768px)"></picture>USA + International</a>
                            </li>
                            <li class="link nav-secondary__dropdown-link-region">
                                <a href="asdasdasd/" lang="en-CA"></picture>Canada</a>
                            </li>
                            <span class="nav-secondary__hr-end"></span>
                            <li class="nav-secondary__dropdown-link nav-secondary__dropdown-copy" style="font-style: normal;text-transform: none;font-size: 14px;">Experience local shipping options and optimized product inventory for your region.</li>
                        </ul>
                    </li>
<div>
.support-section {
            display: flex;
            justify-content: flex-end;

            .nav__support-links {
                display: flex;
                list-style: none;
                align-items: center;
                gap: 20px;

                .nav-secondary__support-link-active .nav-secondary__dropdown-region {
                    opacity: 1;
                    visibility: visible;
                    display: block;
                    
                }
            }

            .nav-secondary__dropdown-region {
                visibility: hidden;
                opacity: 0;
                display: none;

                ::before {
                    content: "";
                    position: absolute;
                    top: -8px;
                    right: -3px;
                    width: 0;
                    height: 0;
                    border-left: 8px solid transparent;
                    border-right: 8px solid transparent;
                }
            }             
    }
if (navigationRegion) {
  navigationRegion.addEventListener("click", function (event) {

  const linkElem = event.target.closest('a');

  if (linkElem) {
    const parentElem = linkElem.parentElement;


    if (parentElem.classList.contains('nav-secondary__support-link-active')) {
      return false;
    }

    linkElem.parentElement.classList.add('nav-secondary__support-link-active');
    linkElem.setAttribute('aria-expanded', 'true');
  }
  });


  navigationRegion.onmouseover = function () {


    if (!navigationRegion.classList.contains('nav-secondary__support-link-active')) {
      navigationRegion.children[0].setAttribute('aria-expanded', 'true')
      navigationRegion.classList.add('nav-secondary__support-link-active');
      return false;
    }
  }

  navigationRegion.onmouseout = function () {
    if (navigationRegion.classList.contains('nav-secondary__support-link-active')) {
      navigationRegion.children[0].setAttribute('aria-expanded', 'false')
      navigationRegion.classList.remove('nav-secondary__support-link-active');
      return false;
    }
  }
}

The Javascript is working and adding the new class but I think the issue is with the styles.
When I hover over the #navigation-region the class is being added but the menu still does not show

how can i get the import path of a react element in bun?

I’m trying to hydrate a react SSR element but I need to know it’s import path so I can add it to the rendered HTML and then dynamically import it in my client-side code.

example.tsx:

import Home from '../pages/Home'

const element = <Home name="joe" />

// i need something like this:
const path = element.meta.path

How do I get the import path of element?

I’m looking for a result like ../pages/Home.tsx

Next.js attempts to parse MDX files as plain JavaScript

I’m building a website using Next.js with (local) MDX files for content. Whenever I add a .MDX file to my source tree and try to navigate to it, Next.js throws a parsing error either after ‘#’ signs (# Heading), the front-matter, or JSX content. It simply attempts to interpret the file as plain JavaScript and fails.

I’m using Next.js version 14.0.4 and have installed the following dependencies:
@next/mdx @mdx-js/loader @mdx-js/react @types/mdx gray-matter

"@mdx-js/loader": "^3.0.0",
"@mdx-js/react": "^3.0.0",
"@next/mdx": "^14.0.4",
"@types/mdx": "^2.0.10",
"gray-matter": "^4.0.3",

Here’s my next.config.js:

/** @type {import('next').NextConfig} */
const nextConfig = {
    pageExtensions: ['js', 'jsx', 'mdx', 'ts', 'tsx'],
    reactStrictMode: true,
}

module.exports = nextConfig

This is the file I’m trying to parse:

---
Title: Test Post
---

# This is just a test post

Hello!

The error messages I get look like this:

Module parse failed: Assigning to rvalue (1:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

I’ve installed the MDX loader as per the Next.js docs. I have also tried the following next.config.js, but the errors remained:

/** @type {import('next').NextConfig} */
const nextConfig = {
    pageExtensions: ['js', 'jsx', 'mdx', 'ts', 'tsx'],
    webpack: (config, {defaultLoaders}) => {
        config.module.rules.push({
            test: '/.mdx$/',
            use: [
                defaultLoaders.babel, {
                    loader: '@mdx-js/loader'
                }
            ]
        });
        return config;
    }
}

module.exports = nextConfig

Block Arrangment by React / Typescript

We have a sheet with a size of 20 inch x 40 inch and three types of blocks with the corresponding sizes and quantities:

  • 5 inch x 7 inch – 50 pieces,
  • 3 inch x 4.5 inch – 70 pieces
  • 9 inch x 2 inch – 50 pieces

You need to make an algorithm that will arrange these blocks in the sheet as ergonomically as possible (so that as much space as possible is used) and will give the smallest possible number of sheets.
Make app to show it by React and Typescript.

Please guys heeelllppp!

Trying, but nothing worked(

import React, { useState, useEffect } from 'react';

interface Block {
  width: number;
  height: number;
  quantity: number;
}

const Sheet = { width: 20, height: 40 };

const Blocks: Block[] = [
  { width: 5, height: 7, quantity: 50 },
  { width: 3, height: 4.5, quantity: 70 },
  { width: 9, height: 2, quantity: 50 },
];

const calculateLayout = () => {
  const sortedBlocks = [...Blocks].sort((a, b) => b.width - a.width); // Sort blocks by width in descending order
  const layout: any[] = [];

  for (const block of sortedBlocks) {
    for (let i = 0; i < block.quantity; i++) {
      const placed = placeBlock(layout, block);
      if (!placed) {
        layout.push({ block, x: 0, y: layout.reduce((acc, val) => Math.max(acc, val.y + val.block.height), 0) });
      }
    }
  }

  return layout;
};

const placeBlock = (layout: any[], block: Block) => {
  for (let x = 0; x <= Sheet.width - block.width; x++) {
    for (let y = 0; y <= Sheet.height - block.height; y++) {
      const canPlace = !layout.some((item) => {
        return (
          x < item.x + item.block.width &&
          x + block.width > item.x &&
          y < item.y + item.block.height &&
          y + block.height > item.y
        );
      });

      if (canPlace) {
        layout.push({ block, x, y });
        return true;
      }
    }
  }
  return false;
};

const renderSheet = (layout: any) => {
  return (
    <div style={{ width: `${Sheet.width} inch`, height: `${Sheet.height} inch`, position: 'relative' }}>
      {layout.map((item: any, index: number) => (
        <div
          key={index}
          style={{
            position: 'absolute',
            width: `${item.block.width} inch`,
            height: `${item.block.height} inch`,
            left: `${item.x} inch`,
            top: `${item.y} inch`,
            border: '1px solid black',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
          }}
        >
          {item.block.width} x {item.block.height}
        </div>
      ))}
    </div>
  );
};

const App: React.FC = () => {
  const [layout, setLayout] = useState<any[]>([]);

  useEffect(() => {
    const newLayout = calculateLayout();
    setLayout(newLayout);
  }, []);

  return (
    <div style={{ textAlign: 'center', marginTop: '20px' }}>
      <h1>Block Layout</h1>
      {layout.length > 0 ? (
        renderSheet(layout)
      ) : (
        <p>Calculating layout...</p>
      )}
    </div>
  );
};

export default App;```

Need advice on Career switch from SAP analyst to Frontend development [closed]

Working as a SAP analyst (HR and Finance ERP tool) at a service based firm with 1YOE. Work includes implementation and configuration work, with little to no technical work. It really sucks.

I am more intrested in Frontend / UI development roles and want to pursue my career into it. I have sound knowledge and personal project experience in ReactJS and NextJS.

Is it possible to make career transition from SAP analyst to frontend development and Is this the right decision to make transition now?

Please share your experience or someone’s experience you might know on career switch.

i can send cookies in node js but i can not get in next js

i have this code in backEnd nodejs i set token to cookeis and send to front next js but i can not give in frontEnd i set sameSite to none secure to true but i can not give token in cookies i don’t have any error

const signToken = id => {
  return jwt.sign({ id: id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN
  });
};

const createSendToken = (user, statusCode, res) => {
  const token = signToken(user._id);

  const cookieOptions = {
    expires: new Date(
      Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000
    ),
    // secure: true,
    sameSite: 'None',
    secure: true,
  };
  if (process.env.NODE_ENV === 'production') cookieOptions.secure = true;

  res.cookie('jwt', token, cookieOptions);

  // remove the password from the output
  user.password = undefined;

  res.status(statusCode).json({
    status: 'success',
    token,
    data: {
      user: user
    }
  });
};

exports.signup = catchAsync(async (req, res, next) => {
  console.log(req.body);

  const newUser = await User.create({
    name: req.body.name,
    email: req.body.email,
    phoneNumber: req.body.phoneNumber,
    password: req.body.password,
    passwordConfirm: req.body.passwordConfirm
  });

  createSendToken(newUser, 201, res);
});

and send cookie
but in the next js i can not get and resend back cookie

  async function onSubmit(event) {
    event.preventDefault();
    setIsLoading(true);
    setError(null);

    const formData = new FormData(event.target);
    const json = Object.fromEntries(formData.entries());

    try {
      const response = await axios.post(
        "http://127.0.0.1:4000/api/user/login",
        json,
        {
          withCredentials: true,
        }
      );
      console.log("response", response);
      // if (!response.ok) {
      //   throw new Error("Failed to submit the data. Please try again.");
      // }

      const data = response;
      console.log("data", data);
      // router.push("/");
    } catch (error) {
      setError(error);
      
      // res.status(error.response.status).json({ message: error.message });
    } finally {
      setIsLoading(false);
     
    }
  }

i set cors and set this

 sameSite: 'None',
    secure: true,
    httpOnly: true

i set // httpOnly: true but not working

Node.js & node-postgres in Express.js: Pool vs PoolClient?

I have an API in Express.js that make multiple query. I’m a bit confused about difference between Pool and PoolClient. For example:

With Pool:

import express from 'express'
import { Pool } from 'pg'

const app = express()
const pool = new Pool()

app.get('/list', async (req, res) => {
  const result1 = await pool.query('SELECT * FROM test WHERE id = 1')
  const result2 = await pool.query('SELECT * FROM test WHERE id = 2')
  const result3 = await pool.query('SELECT * FROM test WHERE id = 3')
  res.send({result1, result2, result3 })
})

With PoolClient:

import express from 'express'
import { Pool } from 'pg'

const app = express()
const pool = new Pool()

app.get('/list', async (req, res) => {
  const client = await pool.connect()
  const result1 = await client.query('SELECT * FROM test WHERE id = 1');
  const result2 = await client.query('SELECT * FROM test WHERE id = 2');
  const result3 = await client.query('SELECT * FROM test WHERE id = 3');
  client.release()
  res.send({result1, result2, result3 })
})

With PoolClient the each query is a bit faster and the API response in less time.

what is the correct approach?

JavaScript filter array with other nested array using key

Hi stuck at one point I have two set of arrays (topicsList & hierarchyList)

let topicsList = [{
    "topicId": 1,
    "topicName": "Introduction",
  },
  {
    "topicId": 2,
    "topicName": "How to Guide",
  },
  {
    "topicId": 3,
    "topicName": "Support",
  },
  {
    "topicId": 6,
    "topicName": "Lamborghini",
  },
  {
    "topicId": 7,
    "topicName": "Mercedes Benz",
  },
  {
    "topicId": 10,
    "topicName": "Skoda",
  }
]

let hierarchyList = [{
    "topicId": 1,
    "topicName": "Introduction",
  },
  {
    "topicId": 2,
    "topicName": "How to Guide",
    "children": [{
      "topicId": 6,
      "topicName": "Lamborghini",
      "children": [{
        "topicId": 10,
        "topicName": "Skoda",
      }]
    }]
  },
  {
    "topicId": 3,
    "topicName": "Support"
  }
]

topicIds = new Set(hierarchyList.map(({ topicId }) => topicId));

topicsList = topicsList.filter(({ topicId }) => !topicIds.has(topicId));

console.log(topicsList);

I am filtering out the TopicsList based on the topicId present in hierarchyList, but hierarchyList now also has this nested childrens and it can be n levels deep

I also need to check now if this topicId is also present in nested childrens array if it does I need to do the same filter it out from Topic List. I’m not sure how can i achieve this behaviour

Expected O/P

TopicList = [{
  "topicId": 7,
  "topicName": "Mercedes Benz",
}]

How can I add a URL at the beginning of a specific object item called through the API in React Native?

I am trying to add the URL at the start of data[{“products_picture:”…”}] element so that it will display the picture of the product in the application. I can fetch all the information from the API and display it on the app.

Here is the API response of products:

"data": [
        {
            "id": "213",
            "products_id": "213",
            "products_picture": "uploads/p/p/example_1.jpg",
            "products_name": "placeholder",
        },
        {
            "id": "123",
            "products_id": "123",
            "products_picture": "uploads/p/p/example_2.jpg",
            "products_name": "placeholder3452",
        }
        ]

Below is my code to fetch without my attempts to add the link to products_picture:

const [products, setProducts] = useState([]);

const requestOptions = {
    method: "GET",
    headers: myHeaders,
    redirect: "follow",
  };

const siteUrl = "https://somewebsite.com/";

useEffect(() => {
    const getProducts = () => {
      fetch(
        "http://apitest.dogusyapimarket.com.tr/api/v2/products",
        requestOptions
      )
        .then((response) => response.json())
        .then((result) => {
          setProducts(result.data);
        })
        .catch((error) => console.log("error", error));
    };

    getProducts();
  }, []);

I attempted to call result.data outside of the useEffect, but it didn’t work, as it was expected. Inside the useEffect, I tried to access the element using result.data.products_picture and concatenate the siteUrl at the beginning of it. However, it resulted in a log of https://somewebsite.com/undefined.

Unable to get data from Express server to React

I am trying to fetch data from express to react using fetch API. The express server is reading data from a postgresql server and should send that data to the React application.

Front-end (React) code –

const query = 'select * from "LabResults"';

const executeQuery = async () => {
        console.log('Running execute query')
        try {
            const response = await fetch(`/api/execute-query?query=${encodeURIComponent(query)}`);
            const result = await response.json();
            console.log('Printing result fetched from DB ', response);
        } catch (error) {
            console.error('Error executing query:', error);
        }
    };

Backend (Express) code –

app.get(api_endpoint, async (req, res) => {
    try {
        // console.log(req);
        // const { query } = req.query;
        const query = 'SELECT * FROM "LabResults"';
        if (!query) {
            return res.status(400).json({ error: 'Query parameter is required.' });
        }
        const result = await pool.query(query);
        console.log(result.rows)
        const data = { message: 'Hello from the server!' };
        res.send(data);
    } 
    catch (error) {
      console.error('Error executing query 1:', error);
      res.status(500).json({ error: 'Internal Server Error' });
    }
});

app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}/${api_endpoint}`);
});

I am facing the following 2 challenges –

  1. Ideally I want to send the query from React app to Express server, hence I am passing it encoded to fetch. However, server responds with invalid query error. What is the right way to pass the query?
  2. Since I was stuck on 1, I assumed a valid query is being sent to the server by hardcoding the query in the express server itself. I am able to poll the DB and get the data which prints correctly on console (it’s an array of objects if it matters as I am printing all the rows). Then I have to return this to the React app, I send it to React using res.send(data). I had tried res.json(data) and res.send(JSON.stringify(data)) before but none of these is working. In the React app, I get the error shown in the below image – it is happening due to the line const result = await response.json(); but I don’t understand what is going wrong.

Note: Since I was unable to send the actual rows back to the React app, I thought of mocking that data too (const data = { message: 'Hello from the server!' };), but even that is not working and gives the same error.

enter image description here

How can I create an editor like Canva, in which we can resize and reposition an image within a container, and image outside the container looks faded

I am developing an editor in ReactJs in which i need to show an image inside a container, and if user want he/she can enter the edit mode and reize or reposition that image within that container only, the image should not move outside the boundaries of the container as well. Exactly like how canva is doing. Here is an example from canva.

This is the default mode of the editor:

Edit mode by double clicking

Please help.

I’ve tried but its not working as expected, so i need a proper direction how should i approach this.