can you guys help me solve this issue

export ‘useNavigate’ (imported as ‘useNavigate’) was not found in ‘react-router-dom’ (possible exports: BrowserRouter, HashRouter, Link, MemoryRouter, NavLink, Prompt, Redirect, Route, Router, StaticRouter, Switch, __RouterContext, generatePath, matchPath, withRouter)

ERROR in ./src/Search.js 88:10-21

export ‘useNavigate’ (imported as ‘useNavigate’) was not found in ‘react-router-dom’ (possible exports: BrowserRouter, HashRouter, Link, MemoryRouter, NavLink, Prompt, Redirect, Route, Router, StaticRouter, Switch, __RouterContext, generatePath, matchPath, withRouter)

How to change icon while also doing a changeTheme with onClick in react js?

I have succeded in creating a icon click to change the colorscheme of my website (line 21 and changeTheme), but when I click the icon I would also like it to change from FaRegMoon to FaRegSun and vice versa (i.e when I click it once it should change to FaRegSun and when I click it another time it should change to FaRegMoon

current code:

import React, {useState} from 'react'
import { FaRegMoon, FaRegSun } from "react-icons/fa"
import "./index.sass"

const changeTheme = () => {
    const item = localStorage.getItem("theme")
    let theme;
    if (item === "light") {
        theme = "";
        localStorage.setItem('theme', "")
    } else {
        theme = "light"
        localStorage.setItem('theme', 'light')
    }
    localStorage.setItem('theme', theme)
    document.body.className = localStorage.getItem("theme");
}

const ThemeToggle = () => {
    return (
        <div className='theme-toggle-button'>
            <FaRegMoon size={20} onClick={() => changeTheme() }/>
        </div>
    )
}

export default ThemeToggle;

react-transition-group does not animate

I use React and tranct-transition-group to write carousel components

But I encountered the problem that the animation does not take effect. The code is as follows

Link https://stackblitz.com/edit/react-ts-mi8mwj?file=Carousel.tsx

Carousel.tsx

import React, { FC, Fragment, ReactNode, useMemo, useState } from 'react';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import CarouselItem, { ItemProps } from './CarouselItem';
import './Carousel.scss';

export interface Props {}

const Component: FC<Props> = (props) => {
  const { children } = props;
  const [curIndex, setCurIndex] = useState(1);
  const length = useMemo(() => {
    return Array.from(children as ReactNode[]).length;
  }, [children]);
  const onNext = () => {
    setCurIndex((curIndex + 1 + length) % length);
  };
  const onPrev = () => {
    setCurIndex((curIndex - 1 + length) % length);
  };
  return (
    <Fragment>
      <button onClick={onPrev}>prev</button>
      <button onClick={onNext}>next</button>
      <div className="g-carousel-wrapper">
        <div className="g-carousel-window">
          <TransitionGroup className="item">
            {React.Children.map(children, (child, index) => {
              const childElement = child as FC<ItemProps>;
              if(child.type !== CarouselItem) throw new Error('必须是Item')
              return (
                <CSSTransition classNames="item" timeout={300} key={index}>
                  {React.cloneElement(childElement, {
                    index,
                    style: { display: curIndex !== index && 'none' },
                  })}
                </CSSTransition>
              );
            })}
          </TransitionGroup>
        </div>
      </div>
    </Fragment>
  );
};

type CarouselType = {
  Item: FC<ItemProps>;
} & FC<Props>;

const Carousel: CarouselType = Component as CarouselType;

Carousel.Item = CarouselItem;

export default Carousel;

CarouselItem.tsx

import React, { CSSProperties, FC } from 'react';

export interface ItemProps {
  index?: number;
  style?: CSSProperties;
}

const carouselItem: FC<ItemProps> = (props) => {
  const { children, style } = props;
  return (
    <div className="g-carousel-item" style={style}>
      {children}
    </div>
  );
};

export default carouselItem;

I don’t understand why not only there is no animation effect but also the className of CSSTransition does not exist, it seems that react-transition-group does not take effect thanks

nodejs avoid continuously api call

I have scheduler that calls api urls every minute (totally 3 api urls) the problem is instead of calling 3 urls every minute it calls those 3 urls continuously and so i could end up calling those 3 urls 50 times or more each minute.

My question is how to avoid those extra calls?

My code sample: commented for better understanding

// adding sleep between api calls
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// call for apis every minutes
cron.schedule("* */1 * * * *", () => {
    // total of 3 url addresses (so every minute call 3 urls)
    addresses.forEach(async (address) => {
        await sleep(3000);
        await showTransactionMessage(id, userName, address);
    });
});

// get api data and call message function to send message
async function showTransactionMessage(id, userName, address) {
    await axios.get(address).then(async (response) => {
        if ( response.data.result && Array.isArray( response.data.result ) ) {
            response.data.result.map(async (item) => {
                //start
                const start = async () => {                      
                    await asyncForEach(
                        time = new Date(parseInt(item.timeStamp * 1000)).toLocaleString().split(", ")[1],
                        date = new Date(parseInt(item.timeStamp * 1000)).toISOString().slice(0, 10).split('-').join('/'),
                        timestamp = item.timeStamp,
                        hash = item.hash,
                        from = item.from,
                        to = item.to,
                        value = item.value.toString().slice(0, '-' + item.tokenDecimal),
                        userName,
                    async (response) => {
                        bot.sendMessage(id, response, keyboard);
                    });
                    console.log('Done');
                };
                await sleep(6000); //every 6 seconds send 1 message
                start();
                //end
            });
            console.log('address: ', address); // sample result, below
        } else { 
            console.log('Got issue with response array.');
        }
    }).catch((err) => {
        console.log('error1', err)
    });
};

// send message by api data provided from `showTransactionMessage` fiunction
async function asyncForEach(time, date, timestamp, hash, from, to, value, userName, callback) {
    let response = "";
    response += 'Date: '+date+'n';
    response += 'Time: '+time+'n';
    response += 'TX: '+hash+'n';
    response += 'Receiver: '+to+'n';
    await callback(response);
}

What I end up with code above is

address:  address 1
address:  address 3
address:  address 1
address:  address 2
address:  address 2
address:  address 3
address:  address 1
address:  address 3
address:  address 2
address:  address 1
address:  address 1

Instead of

address:  address 1
address:  address 2
address:  address 3

Any suggestions?

Cant capture eventListener JS on Spring Boot [duplicate]

I cant get eventListener from a jsp page, i need a simple alert when click a button.

jsp code – this only draw a simple 3 buttons:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<!-- Bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Click!</title>
</head>


<body>
    <div class="text-center p-5">
        <button class="btn btn-primary m-3" id="myBtn1">BTN1</button>
        <button class="btn btn-primary m-3" id="myBtn2">BTN2</button>
        <button class="btn btn-primary m-3" id="myBtn3">BTN3</button>
    </div>


<!-- JS -->
<script src="assets/js/sc.js"></script>
<!-- JS Bootstrap -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html> 

In js code put:

let id1 = document.getElementById("myBtn1");
id1.addEventListener("click", window.alert('BTN1'));

when open the navigator:

enter image description here

Show the alert – but i dont push the button !

When page is load show the buttons:

enter image description here

when press BTN1 dont show alert.

My folder extructure :

Directory extructure

The project is very simple i need to use correctly JavaScript on Spring Boot project.

Thanks for you helping !

Good evening, I have an error and I don’t know why. “name with value “[object Object]” must be of type string” must be of type string

This is the variable (GRUPO_PERSONAS_ID)

const GRUPO_PERSONAS_ID = 'my-unique-person-group'
 console.log('-----------------------------------------');
 console.log('Person group');

await client.personGroup.create(GRUPO_PERSONAS_ID, {
            'name': GRUPO_PERSONAS_ID
        })
        .then(() => {

        }) 
        .catch((err) => {
            console.log(err)
            throw err
        })

The previous code is the only one that I use, in fact I do not understand but it generates the following error:
enter image description here

name with value “[object Object]” must be of type string.

export/ import req.body form data from one html file to another through express

I’ve set up an express server.
app.js

The home get request leads to a form page and upon completing and submitting the form, the data is stored in req.body as a JSON. That’s all well and good and I can log the information to console. But the POST html that follows from the submit button isn’t allowing me to import the req.body data collected from the home form html.
form
post html, the data doesn't export, but can be logged in console

As seen in the screenshot, I’ve declared data = req.body, and it works fine when sending plain html through res.send(). All the information can be accessed, however, when I try to import the data in an html file with a <script> tag, sourcing the app.js express server, the data is unidentified. My guess is that something is wrong with how I’m importing.

here's my import

When I res.send(data) Everything is fine.
res.send without html... much less pretty tho :(

Please help. Thanks in advance.
I can send more screenshots of the html files and their outputs on the browser as needed.

Thanks again

CSS header’s height remain constant after calc()

--dis: calc(var(--max-height) - var(--min-height));
/*
  @media large{--min-height:13rem};
  @media small{--min-height:6.5rem};
  --max-height:75vh;
*/

--percent: calc(var(--scroll-ani) / var(--dis));
/* 
  in js: document.body.style = "--scroll-ani:" + document.scrollingElement.scrollTop; 
  This code will correctly output the distance between the top of the visual area and the top of the page
*/

--percent-limited: calc((var(--percent) - 1 - abs(var(--percent) - 1)) / 2 + 1);
/*
  If percent > 1, percent-limited = 1,
  If percent < 1, percent-limited = percent,
  Percent cannot be less than 0.
*/
obj{
  position: fixed;/* header itself will not cause the page height to change*/
  width:100vw;
  height: calc(var(--max-height) - var(--dis) * var(--percent-limited));
}

But height remains unchanged.

–percent-limited work like this:
Graph of y=(x-1-abs(x-1))/2+1
It’s graph of y=(x-1-abs(x-1))/2+1

x will never be less than 0, so range of y will be [0,1]

How to Sort an array with dates (Type ‘string’ is not assignable to type ‘Date’.)

Keep getting error Argument of type ‘string[]’ is not assignable to parameter of type ‘Date[]’.   Type ‘string’ is not assignable to type ‘Date’.

const Date = ['April 1, 2017 10:39 PM', 'April 1, 2017 10:39 PM', 'January 1, 2018 9:39 PM', 'February 11, 2019 9:39 PM', 'April 1, 2019 10:39 PM']

const sDates = Utils.sDates(Date, false)

console.log(sDates)
Function to SortDate

export namespace Utils {
export function sDates(items: Date[], isDescending?: boolean): Date[] {
        let sDateArr: Date[] = [...items];

        if (isDescending) {
            sDateArr.sort(function (dateA: Date, dateB: Date) { return +dateB - +dateA });
        } else {
            sDateArr.sort(function (dateA: Date, dateB: Date) { return +dateA - +dateB});
        }
        return sDateArr;
    }
}

How to return the true in the array back 6 times? [duplicate]

Here I have the console.log grouping the true as a value of 6. How would I get this to loop and log true each time individually?

var bools = [ true, true, false, true, false, true, true, true ];

for (let i = 0; i <= bools.length; i++) {
  if (bools[i] === true) {
    console.log(bools[i]);
  }
}

I tried to change the if statement but it did not work.

Margin not removed even with * selector and !important

I’m building a website using the following template as a base: https://github.com/issaafalkattan/React-Landing-Page-Template

I’m running into a problem when removing the margin in several of the sections. For example (as seen using Chrome’s developer-tools), I’d like to remove the ‘orange’ areas of the Gallery section:

Gallery - inspect element (before * select)

During my troubleshooting, I added

* {
    margin:0 !important;
    padding:0 !important;  
}

to both style.css and bootstrap.css to ‘force’ the margins to go away so I could find the true culprit later, but that only shifted the left margin to the right:
Gallery - inspect element (after * select)

Because of this, I’m assuming React is overriding my CSS; is there a way I can ‘ignore’ React setting the margins for certain components? I’m new to React so apologies if this is a silly question, but I can’t seem to find a fix for my specific problem.

Thank you!

Consuming viacep api using ui material

Good night!
I’m making a delivery record and I wanted to consume a zip code api to automatically fill in the address, city, state and neighborhood fields using the ui material, I’m not able to put the information in the mentioned fields and when I take the auto focus off the zip code field disappear.

const checkZIPCODE = (event) => {
    const zipCode = event.target.value.replace(/D/g, '');
    console.log(zipCode);
    fetch(`https://viacep.com.br/ws/${zipCode}/json/`)
      .then(response => response.json())
      .then(data => {
        console.log(data)
        setCEP('address', data.address)
        setCEP('uf', data.uf)
        setCEP('city', data.city)
        setCEP('district', data.district)
      })
  }
<NumberFormat
        onChange={(event) => setZipCode(event.target.value)}
        value={zipCode}
        onBlur={validateFields}
        error={!error.zipCode.valid}
        helperText={error.zipCode.text}  
        name='zipCode'
        mask={"_"}
        customInput={TextField}
        format={"#####-###"}
        type="text"
        variant="outlined"
        id='zipCode'
        label='ZIPCODE'
        fullWidth
        margin='normal'
        required
      />
      <TextField
        value={address}
        onChange={(event) => setAddress(event.target.value)} 
        onBlur={validateFields}
        error={!error.address.valid}
        helperText={error.address.text}
        placeholder='Rua Barata Ribeiro'
        id='address'
        label='Address'
        type='text'
        name='address'
        variant='outlined'
        margin='normal'
        fullWidth
        required
      />
      <TextField
        style={{ marginRight: 25 }}
        value={number}
        onChange={(event) => setNumber(event.target.value)} 
        onBlur={validateFields}
        error={!error.number.valid}
        helperText={error.number.text}
        placeholder='10'
        id='number'
        label='Number'
        type='number'
        name='number'
        variant='outlined'
        margin='normal'
        required
      />
      <TextField
        value={uf}
        onChange={(event) => setUf(event.target.value)} 
        onBlur={validateFields}
        error={!error.uf.valid}
        helperText={error.uf.text}
        placeholder='RJ'
        id='uf'
        label='Uf'
        type='text'
        name='uf'
        variant='outlined'
        margin='normal'
        required
      />
      <TextField
        style={{ marginRight: 25}}
        value={city}
        onChange={(event) => setCity(event.target.value)} 
        onBlur={validateFields}
        error={!error.city.valid}
        helperText={error.city.text}
        placeholder='Rio de Janeiro'
        id='city'
        label='City'
        type='text'
        name='city'
        variant='outlined'
        margin='normal'
        required
      />
      <TextField 
        value={district}
        onChange={(event) => setDistrict(event.target.value)}
        onBlur={validateFields}
        error={!error.district.valid}
        helperText={error.district.text}
        placeholder='Copacabana'
        id='district'
        label='District'
        type='text'
        name='district'
        variant='outlined'
        margin='normal'
        required
      />

How to assert today’s date or older in Cypress

I am trying to write a function in Cypress, where it loops through all the columns for my start date (#EventStart) and makes sure that the start dates are today’s current date or older. So for instance, I need this test to make sure that it is confirming that all the dates listed are either today’s date (April 4) or earlier (April 3, 2, 1, etc, etc). So far I can get it to confirm today’s date, but how can I add to the function so that it also looks for the days prior to today? Also, the way it is written, it is getting me GMT Time, how can I get it to display CST?

    public assertOldDate () {
    cy.get("#EventStart).each((el) => {
     let oldDate = new Date();
      oldDate.setDate(oldDate.getDate())
      cy.get("el").should("equal", oldDate);
    }
  }

I want to change a variable in html by js but am not sure how to do it

Here is the line i am trying to change.

<a class="weatherwidget-io" href="https://forecast7.com/en/n45d88170d50/dunedin/" data-label_1="DUNEDIN" data-label_2="WEATHER" data-theme="original" >DUNEDIN WEATHER</a>

I am trying to change the “original” data-theme="original" with “dark” when a function is triggered.

Here is my function

function darkmode() {
   
    document.body.classList.toggle("dark-theme")
    document.body.classList.toggle("logo_paw_dark")
    document.getElementsByName("data-theme").innerHTML = "dark";
    
}

I tried getting the element by the name but did not work and neither did with using id