ESLint warning event is defined but never used

I’m getting an error with ESLint on this simple bit of code:

var trigger = document.getElementById("hello");
var audio = new Audio('audio/hello.mp3');

window.addEventListener('DOMContentLoaded', (event) => {
    trigger.addEventListener("click", function(event) {
        event.preventDefault();
        audio.play();
    }, false);
});

The error I’m getting is: 'event' is defined but never used.

I’ve read that I can disable this error by adding a comment after the open brace where ‘event’ is used like this: // eslint-disable-line no-unused-vars.

But my question is, is anything actually wrong with this code and should it be fixed or improved on? Rather than covered up by a comment ignoring the warning? Or is there actually nothing wrong with this approach and it’s just ESLint being pedantic?

Is there a way to move children to another parent if they overflow the current parents height?

I use React to write an web application. I have a Container component that serves as a container with fixed height. In this Container I have multiple children with different heights. Is there a way to programmatically copy Container component and move it’s children components that overflow first containers height into copied container. And, if possible, do this recursively ( so we can have multiple copied containers ).

Only example of this that I can think of is page break when you want to print something or write something on a new page in the document but in this case I want to do this on the webpage without any printing.

Here is the code that I currently have:

Container:

const Container = ({ children }) => {
  return <div style={{ height: "500px" }}>{children}</div>;
}

Page:

return (
   <Container> 
       <div style={{ height: 250, width: "100%", border: "2px solid black" }}></div>
       <div style={{ height: 250, width: "100%", border: "2px solid black" }}>
         {/* Elements below should be moved to a new container */}
         <div style={{ height: 200, width: "100%", border: "2px solid black" }}></div>
       </div>
       <div style={{ height: 200, width: "100%", border: "2px solid black" }}></div>
   </Container>
)```

React-query, Infinite query loading the same data again on fetchNextPage()

I have a paginated API and I am using reactInfiniteQuery to pull the data, i have followed the documentation but when trying to fetch the next page the first page is loading again and renderd to the DOM

The react query function(from docs)

const {
    data: Articles,
    error,
    fetchNextPage,
    hasNextPage,
    isFetching,
    isFetchingNextPage,
    status,
} = useInfiniteQuery(['get-posts'], getAllPosts, {
    getNextPageParam: (article, pages) => {
        return article.current_page + 1
    }

})

getAllPosts function

export const getAllPosts = async ({ pageParams = 1 }) => {
    let response = await axiosInstance.get(`all-posts?page=${pageParams}`)
    return response?.data
}

how i’m rendering the data(from docs)

{Articles?.pages?.map(page =>
    page?.data?.map((article, i) => {
       return (
             <>
             ...
             </>
       )
    })
 )}

Data structure

for some reason when fetchNextPage is evoked the same pageParam is fetched

React native loop remove times based on length between last time end and next time start

Sorry in advance, possibly been looking at it for t long. I have a test application which shows a horizontal list of dates and times for a selected date for booking appointment slots but can’t seem to exclude the times that would overlap into other appointment times.

Example or what should happen

A typical appointment length for this selected service is 1hr and 30mins, I have 4 appointments already booked so my app should show the following available appointment times to select from
[12:00, 16:30, 16:45, 17:00]

What is being displayed which is wrong

[12:00, 12:15, 12:30, 12:45, 13:00, 13:15, 13:30, 16:30, 16:45, 17:00]

In this case, if the user was able to select 12:30 then it would overlap into another appointment time so I would need to exclude [12:15, 12:30 etc…]

Data

availableTimes:
[’09:00′, 09:15 … 16:45, 17:00] – So opening and closing from 09:00 until 17:00

existingBooks for the selected day (2022-01-07):

[stDateTime: ‘2023-01-07 09:00’, enDateTime: ‘2023-01-07 10:30’]
[stDateTime: ‘2023-01-07 10:30’, enDateTime: ‘2023-01-07 12:00’]
FREE SLOT BETWEEN 12:00 and 13:30 so available time to show should be 12:00
[stDateTime: ‘2023-01-07 13:30’, enDateTime: ‘2023-01-07 15:00’]
[stDateTime: ‘2023-01-07 15:00’, enDateTime: ‘2023-01-07 16:30’]

I actually think it’s a problem somewhere in the loop but not sure how to alter the arrays or data.

const updateAvailableTimes = (
            bookings: Array<{stDate: string; enDate: string}>,
            availables: Array<string>,
            currDate: string,
        ) => {
            const newAvailables = [];
            const serviceLengthInMinutes = 90; // 1hr and 30 minutes // Get the actual service length from state or passed param
            for (const ava of availables) {
                const curr = moment(`${currDate} ${ava}`, 'YYYY-MM-DD HH:mm');
                let isBooked = false;
                for (const booking of bookings) {
                    const st = moment(booking.stDate, 'YYYY-MM-DD HH:mm');
                    const en = moment(booking.enDate, 'YYYY-MM-DD HH:mm');

                    if (!curr.isSameOrAfter(st) || !curr.isSameOrAfter(en) && !curr.isBetween(st, en) || curr.isBefore(en)) {
                        if(!curr.isBefore(st) && !curr.isAfter(en)){
                            console.log('Booked Slot: ' + moment(en, 'HH:mm').format('HH:mm'));
                            newAvailables.push('');
                            isBooked = true;
                            break;
                        }
                    }
                }
                if (!isBooked) {
                    console.log('Available Slot: ' + moment(ava, 'HH:mm').format('HH:mm'))
                    newAvailables.push(ava);
                }
            }
            return newAvailables;
        };

Add a JS class called Employee and create methods to sort employees by different parameters and to filter by age

This code is what I got and it totally confuses me what next I can do. If someone can help me then that would be great.

class Employee{
    
}
let employeeList = [
    {
       "id":1,
      "name": "sundar",
      "salary":700000
    },
    {
       "id":2,
      "name": "om",
      "salary":600000
    },
    {
       "id":3,
      "name": "rahul",
      "salary":500000
    },
    {
       "id":4,
      "name": "Ramu",
      "salary":400000 
    }
  ]

redirect event with javascript

I’m doing a project and I don’t understand the front end well.
I have this html page:

<form class="form-group" action="/create" method="post" enctype="multipart/form-data">

            <div class="title">
                <h1>Cadastre seu produto</h1>
            </div>

            <div class="single-input">
                <input class="form-control" placeholder="nome do produto" type="text" id="nome_produto" name="nome_produto">
            </div>

            <div class="single-input">
                <input class="form-control" placeholder="quantidade em estoque" type="number" id="quantidade" name="quantidade">
            </div>

            <div class="single-input">
                <input class="form-control" placeholder="preco do produto" type="number" id="preco_produto" name="preco_produto">
            </div>
            <button onclick="loadPage()" id="button" type="submit" class="btn btn btn-danger">ENVIAR</button>
        </form>       

I want that when I click on the SUBMIT button, I am redirected to another page, I want to do this using Javascript.

I tried to do this:

<script type="text/javascript">
function loadPage(){
    window.location("http://localhost:8080/list")
}

but it’s not working, every time I click on the button I’m redirected to a blank page
Any solution ?

How to perform a DNS lookup on multiple array elements?

I’m working on project that generate domain name, but before sending the result I want to verify the domain name generated is available using the built it nodejs dns library. The problem I’m facing is that the program returns before the callback is executed.

This is what I tried. The function returns an empty array when it ought to return an array of available domain names

const domainVerify = (generatedNames)=>{
  var validDomains = []
  for (var i in generatedNames){
      dns.lookup(i, (err, value)=>{
          if(!err) validDomains.push(i)
      })
  }
  return validDomains
}


const generatedNames = ["google.com", "abdefg.com"]
console.log(domainVerify(generatedNames))

Local Storage values not found first time. After reload its work

import {useEffect} from 'react';
import {useRouter} from 'next/router';

const AuthGurd=props=>{
   const {children,fallback} = props;
   const auth = useAuth();
   const router=useRouter();
   useEffect(()=>{
    if(!router.isReady){
     return
    }
    if(auth.user===null && !window.localStorage.getItem('userData')){
        if(router.asPath !=='/'){
            router.replace({
            pathname:'/login',
            query:{returnUrl:router.asPath}
            })
        }else{
           router.replace('/login')
        }}
    },[router.route])
    if(auth.loading || auth.user===null){
        return fallback //loader
    }
    return <>{children}</>
}
export default AuthGurd;

I am trying to use authentication in my project. when running project first-time localstroage not found its return fallback which is loader. Then I have to refresh the page then return to login page.

How To Control The Firing Of Async Functions Called From A Different File?

I have asynce functions in an index file that are helped by other async functions in a helpers file. This uses the library Web3 which you can learn about here: https://web3js.readthedocs.io/en/v1.8.1/web3-eth-contract.html?highlight=.methods#id28

The difficulty I’m having is that when I call an async function from my helpers it returns that following error:

const reserves = await _pairContract.methods.getReserves().call()
                                         ^

TypeError: Cannot read properties of undefined (reading 'methods')
    at getReserves (/Users/Me/trading_bot_V2/helpers/helpers.js:54:42)
    at calculatePrice (/Users/Me/trading_bot_V2/helpers/helpers.js:59:40)
    at checkPrice (/Users/Me/trading_bot_V2/bot.js:110:30)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Subscription.callback (/Users/Me/trading_bot_V2/bot.js:45:41)

I should also note that these async functions require information from the previous one in order to work properly. I THINK the reason it isn’t working is that _pairContract hasn’t populated before getReserves() fires. Does that sound correct?

Here’s the relevant code for index:

arbAgainst.forEach(() => {
   const checkPrice = async (exchange, token0, token1) => {
      const uPrice = await calculatePrice(uniPair)
      const sPrice = await calculatePrice(sPair)

      return priceDifference;
   }

   const determineProfitability = async (_routerPath, _token0Contract, _token0, _token1, exchange) => {
      if (_routerPath[0]._address == uRouter._address) {
      reserves = await getReserves(sPair)
      exchangeToBuy = 'Uniswap'
      exchangeToSell = 'Sushiswap'

      } else {
      reserves = await getReserves(uPair)
      exchangeToBuy = 'Sushiswap'
      exchangeToSell = 'Uniswap'
   }
})

And here’s the relevant code for helpers:

async function getPairAddress(_V2Factory, _token0, _token1) {
    const pairAddress = await _V2Factory.methods.getPair(_token0, _token1).call()
    return pairAddress
}

async function getPairContract(_V2Factory, _token0, _token1) {
    const pairAddress = await getPairAddress(_V2Factory, _token0, _token1)
    const pairContract = new web3.eth.Contract(IUniswapV2Pair.abi, pairAddress)
    return pairContract
}

async function getReserves(_pairContract) {
    const reserves = await _pairContract.methods.getReserves().call()
    return [reserve0, reserve1]
}

async function calculatePrice(_pairContract) {
    const [reserve0, reserve1] = await getReserves(_pairContract)
    return Big(reserve0).div(Big(reserve1)).toString()
}

So, is my hypothesis correct or is there something I’m missing?

How can i get access username without getting errors? ERROR TypeError: null is not an object (evaluating ‘userdata.user’)

Can anyone give me a better way to access the username of the user who is logged in? I first try to access the user by going into my sendcity function then I wrote username: userdata.user.username but this was only working when i give the username a string like username: "Wow" then I again give username: userdata.user.username then it was working and if I directly do username: userdata.user.username after logging in my app and entering home page then it’s giving me this error ERROR TypeError: null is not an object (evaluating ‘userdata.user’) i think its an AsyncStorage login problem Can anyone can give me a better way to get access to the username of the user who logged in? well, I tried to do this const username = userdata.user.username; but it was also getting that same error

import { StyleSheet, Text, View, StatusBar } from 'react-native'
import React, { useEffect, useState } from 'react'
import { containerFull } from '../../CommonCss/pagecss'
import { formHead } from '../../CommonCss/formcss'
import Bottomnavbar from '../../Components/Bottomnavbar'
import TopNavbar from '../../Components/TopNavbar'
import FollowersRandomPost from '../../Components/FollowersRandomPost'
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as Location from 'expo-location';

const Mainpage = ({ navigation }) => {

    const [userdata, setUserdata] = React.useState(null)
    const [location, setLocation] = useState(null);
    const [errorMsg, setErrorMsg] = useState(null);
    const [city, setCity] = useState(null);

    useEffect(() => {
        AsyncStorage.getItem('user')
            .then(data => {
                // console.log('async userdata ', data)
                setUserdata(JSON.parse(data))
            })
            .catch(err => alert(err))
    }, [])

    console.log('userdata ', userdata)

    // const username = userdata.user.username;


    useEffect(() => {
        (async () => {
            let { status } = await Location.requestForegroundPermissionsAsync();
            if (status !== 'granted') {
                setErrorMsg('Permission to access location was denied');
            }

            let location = await Location.getCurrentPositionAsync({});
            setLocation(location);

            let city = await Location.reverseGeocodeAsync(location.coords);
            setCity(city[0].city);
        })();
    }, []);

    const sendCity = () => {
        setCity(city);
        fetch('http://10.0.2.2:3000/updateCity', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                city: city,
                username: userdata.user.username
            }),
        })
        .then((response) => response.json())
        .then((data) => {
            console.log('Success:', data);
        })
        .catch((error) => {
            console.error('Error:', error);
        });
    };
    
    
    useEffect(() => {
        sendCity();
    }, [])
    
    return (
        <View style={styles.container}>
            <StatusBar />
            <TopNavbar navigation={navigation} page={"MainPage"} />
            <Bottomnavbar navigation={navigation} page={"MainPage"} />
            <FollowersRandomPost />
        </View>
    )
}

export default Mainpage

const styles = StyleSheet.create({
    container: {
        width: '100%',
        height: '100%',
        backgroundColor: 'black',
        paddingVertical: 50,
    }
})

Following function must return true if given sequence is valid. Why this function doesn’t return true for “||” sequence?

Function must return true for “()” sequence and false for “[)” sequence, so it does. But why this function doesn’t return true for “||” sequence? Could you help, please?

I wrote this code, but nothing works 🙁

function check(s) {
  const brackets = {
    ")": "(",
    "]": "[",
    "}": "{",
    "|": "|",
  };
  const st = [];
  for (let i = 0; i < s.length; i++) {
    if (isClosedBracket(s[i])) {
      if (brackets[s[i]].toString() !== st.pop()) {
        return false;
      }
    } else {
      st.push(s[i]);
    }
  }
  return st.length === 0;
}
//if bracket is in this array, function returns true, so bracket is closing
function isClosedBracket(ch) {
  return [")", "]", "}", "|"].indexOf(ch) > -1;
}

get all the characters between () regex js

I have the following string and I want to get all the characters between the parentheses.

const str = "(123-456) is trying out a mention with (789-321)"

I want to create an array that looks like the following:

const arr = ['123-456', '789-321']

I have the following code but it’s not working as expected.

const removeBrackets = str.match(/((.*))/) ?? []

React form value does not pass to the database

I have tried to pass current time to the mongo dB using mongoose in react. Although current time is visible on textbox, the value does not pass to the database. If I hardcode the value, it properly pass to the database. How to fix it?

const[orderTime,setOrderTime] = useState("");

function generateTime(){
  var time = new Date();
  return time.toLocaleTimeString();
}

<input type="text" className="form-control" id="OrderTime" placeholder="Order Time" value={generateTime()} onChange={(event)=>{
        
        setOrderTime(event.target.value);
    }}/>