Update state in component based on custom hook

I am trying to separate some logic from my component into a custom hook. I feel like i’m misunderstanding some fundamentals but I thought my code would work.

Custom hook:

function eventsReducer(events, action) {
    switch (action.type) {
        case 'add': {
            return [
                ...events,
                {
                    date: action.date,
                }
            ]
        }
        case 'delete': {
            return events.filter((t) => t.date !== action.date)
        }
        default:
            throw new Error('No such action');
    }
}

const initEvents = () => {
    const eventsFromStorage = localStorage.getItem('savedEvents')
    const parsedEvents = eventsFromStorage ? JSON.parse(eventsFromStorage) : []
    return parsedEvents
}

const useEvent = () => {
    const [events, dispatchEvent] = useReducer(
        eventsReducer,
        [],
        initEvents
    )

    useEffect(() => {
        const saveEventsToStorage = () => {
            localStorage.setItem('savedEvents', JSON.stringify(events))
        }
        saveEventsToStorage()
    }, [events])

    const getEventByDate = useCallback((date) => {
        return events.filter(
            event =>
                format(new Date(event.date), 'yyyy MM d H') === format(new Date(date), 'yyyy MM d H')
        )
    }, [events])

    return {
        events,
        getEventByDate,
        dispatchEvent,
    }
}

export default useEvent

Here Hour component:

const Hour = ({ dayWithHour }) => {
    const { getEventByDate } = useEvent()

    const hasEvent = !!getEventByDate(dayWithHour).length

    return (
        <Container hasEvent={hasEvent}></Container>
    )
}

And function for adding new event in another component:

    const { dispatchEvent } = useEvent()

    const handleClick = () => {
        const promptData = prompt('Enter event time: YYYY-MM-DD HH:mm:ss')

        if (!promptData) return

        dispatchEvent({
            type: 'add',
            date: new Date(promptData)
        })
    }

I have hook thats store events(useEvent) and i need to update component Hour, when I add new event.

Howto play audio during all vertical slides in reveal.js

I have a reveal presentation with linear navigation on horizontal and vertical slides to share the background for each set of vertical slides. I want to auto-play an audio file as long as the presentation stays in the same horizontal slide even if the vertical slides are changed. But the audio should stop if switched to the next horizontal slide.

With the attribute “data-ignore” it is easy to keep the audio playing on a slide change. But it will also play if switched to the next horizontal slide and the audio for this main slide will be played on top of the previous audio.
Is there an easy way to achieve this behaviour ? Maybe some kind of “data-ignore-vertical” which only ignores slide changes in the vertical direction ?

How to Achieve Default Return Type in TypeScript Function Without Function Overloading?

I have a TypeScript function that creates arrays, and I’m trying to achieve a specific behavior without using function overloading. The function, createArray, accepts two parameters: size (number) and element (optional). If element is not provided, I want the default return type to be number[]. Currently, when calling the function without the element parameter, the return type is inferred as unknown[].

Here is the function in question:

function createArray<T>(size: number, element?: T | ((index: number) => T)): T[] {
  const array = new Array(size);

  for (let index = 0; index < array.length; index++) {
    const component = typeof element === 'function' ? (element as (index: number) => T)(index) : element;
    array[index] = component === undefined ? index : component;
  }

  return array;
}

For example:

  • const a = createArray(1, 's'); should have a return type of string[].

  • const b = createArray(1); should have a return type of number[].

I attempted to modify the function to achieve the desired behavior, but I haven’t found a solution yet. I explored using function overloading, but I want to avoid that approach. I want to find an alternative solution that achieves the same behavior without overloading the function.

How can I add a Colored Highlight/ Rectangle Behind a Word, but with the Orientation and Dimensions of the Highlighted Rectangle Manipulated?

I am trying to make it so the current highlighted orange on the words software engineer is lowered, so that the top edge ends 40% of the way up the text and the bottom of the highlight is extended below the words and extends slightly to the right.

window.addEventListener("DOMContentLoaded", function() {
  const welcomeText = document.getElementById("welcome-text");
  const container = document.querySelector(".welcome-container");
  const welcomeScreen = document.getElementById("welcome-screen");
  const portfolio = document.getElementById("portfolio");
  const characters = welcomeText.textContent.split("");

  welcomeText.textContent = ""; // Clear the original text

  characters.forEach(function(char, index) {
    const span = document.createElement("span");
    span.textContent = char;
    span.style.transitionDelay = index * 0.125 + "s"; // Delay each character's transition
    welcomeText.appendChild(span);
  });

  setTimeout(function() {
    welcomeText.classList.add("animate-color");
    setTimeout(function() {
      welcomeText.classList.add("animate-slide");
      container.style.height = welcomeText.offsetHeight + "px"; // Adjust container height dynamically
      setTimeout(function() {
        welcomeText.style.opacity = "0"; // Set opacity to 0 to fade out the text
        setTimeout(function() {
          welcomeText.textContent = ""; // Clear the text content
          welcomeText.style.opacity = "1"; // Set opacity back to 1
          welcomeText.style.color = "rgb(57, 55, 55)"; // Change color back to the original color
          welcomeScreen.style.zIndex = "-2"; // Hide the welcome screen
          welcomeScreen.style.backgroundColor = "none"; // Hide the welcome screen
          portfolio.style.display = "block"; // Show the hidden content
        }, 600); // Delay for 0.3 seconds to complete the fading effect
      }, 500); // Delay the fading animation for 1 second
    }, characters.length * 0.125 * 1000); // Delay the slide animation until color transition is complete
  }, 0);
});
body {
  background-color: white;
  font-family: 'Dosis', sans-serif;
  margin: 0;
}


/* Welcome Screen */

#welcome-screen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background-color: black;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 3;
}

.welcome-container {
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

#welcome-text {
  font-size: 86px;
  color: rgb(57, 55, 55);
  position: relative;
  opacity: 1;
  transition: opacity 0.3s linear;
}

.animate-color span {
  transition: color 0.3s linear;
  color: white;
}

.animate-slide {
  animation: slide-animation 1s 0.5s forwards;
  animation-fill-mode: both;
}

@keyframes slide-animation {
  0% {
    transform: translateY(0);
  }
  99% {
    transform: translateY(-100%);
  }
  100% {
    transform: translateY(-100%);
  }
}

.hidden {
  display: none;
}


/* Portfolio */

#portfolio {
  position: relative;
  background-color: white;
  color: black;
  width: 100%;
  height: 100%;
}


/* Header */

header {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  background-color: black;
  color: white;
  padding: 20px;
  font-size: 1.25rem;
  height: auto;
}

header p {
  margin-top: 0;
}

header ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
  display: flex;
  justify-content: space-evenly;
  width: 100%;
}

header ul li {
  margin: 0 10px;
}

.underline {
  position: relative;
}

.underline::after {
  content: '';
  position: absolute;
  bottom: -6px;
  left: 0;
  width: 100%;
  height: 4px;
  background-color: rgb(255, 98, 0);
  border-radius: 6px;
}


/* Page Hero */

.page-hero {
  background-color: black;
  height: 825px;
  color: white;
  display: flex;
  align-items: center;
  overflow-x: hidden;
  flex-wrap: wrap;
}

#writing-container {
  margin-left: 200px;
  margin-bottom: 175px;
}

#ph-p-container {
  width: 40%;
}

#ph-h1-container {
  width: 50%;
  position: relative;
  overflow: visible;
}

#ph-h1-container h1 {
  font-size: 70px;
  margin-bottom: 33px;
  position: relative;
  z-index: 1;
  display: inline-block;
}

#ph-h1-container h1 .highlight {
  background-color: rgb(255, 98, 0);
}

#page-hero-svgs {
  height: 50px;
  display: flex;
  align-items: center;
  margin-left: 20px;
  margin-bottom: 33px;
}

.svg-icon {
  width: 50px;
  height: 50px;
  margin-right: 20px;
  filter: invert(1) grayscale(100%);
}
<link rel="preconnect" href="https://fonts.googleapis.com" preload>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin preload>
<link rel='preload' href="https://fonts.googleapis.com/css2?family=Dosis:wght@400;700&display=swap" as='style'>
<!-- Welcome Screen -->

<div id="welcome-screen">
  <div class="welcome-container">
    <h1 id="welcome-text">Welcome</h1>
  </div>
</div>

<!-- Portfolio -->

<div id="portfolio">

  <!-- Header -->

  <div class="header">
    <header>
      <p>Jake Matthews</p>
      <ul>
        <li class="underline">About</li>
        <li class="underline">Projects</li>
        <li class="underline">Future Plans</li>
        <li class="underline">Contact</li>
      </ul>
    </header>
  </div>

  <!-- Page Hero -->

  <div class="page-hero">
    <div id="writing-container">
      <div id="ph-h1-container">
        <h1>Hi, I'm Jake | <span class="highlight">Software Engineer</span></h1>
      </div>
      <div id="page-hero-svgs">
        <img src="./images/github-svg.svg" alt="" id="github" class="svg-icon">
        <img src="./images/linkedin-svg.svg" alt="" id="linkedin" class="svg-icon">
        <img src="./images/email-svg.svg" alt="" id="email" class="svg-icon">
      </div>
      <div id="ph-p-container">
        <p>I am passionate about creating beautiful, immersive & interactive websites – whilst implementing the latest, most powerful/ capable libraries and frameworks. I have a thirst for pushing my capability ceiling. I am also passionate about forex trading
          – I have had live funded accounts provided by proprietary trading companies after passing evaluation tests.
        </p>
      </div>
    </div>
  </div>

  <!-- Rest of Site -->

  <div id="rest-of-site">
    <h1>Test</h1>
  </div>

</div>

https://codepen.io/jake-matthews/pen/NWEqNaW

Thank you in advance.

React JS Application Freezes during onChanged for input

My ReactJs Application has been freezing whenever I type into an input field. It was initially working smoothly, but then this issue occurred yesterday. I have changed onChange to on submit, but that also does not help. I could type one character, and the application will freeze. I deleted the built pages, like profile update, profile delete, profile verification, admin update, and admin delete, which require the user to type into an input field and leave the login page. However, that also does not help. I will provide the frontend code for login. Please let me know if seeing the other page’s code requiring input will help investigate further. Any help is appreciated!

import React, { useState, useEffect } from 'react';
import './Login.css';
//Components
import Header from '../../Components/Header/Header';
import Footer from '../../Components/Footer/Footer';
//Entry Checks
import checkUsername from '../../Functions/EntryCheck/checkUsername';
import checkPassword from '../../Functions/EntryCheck/checkPassword';
//Functions
import CheckLogin from '../../Functions/VerificationCheck/checkLogin';
//Repositories
import Axios from 'axios';
import { useNavigate, useLocation } from 'react-router-dom';

const Login = () => {
    const navigate = useNavigate();
    const location = useLocation();
    const userLoggedIn = CheckLogin();
    const [isLoading, setIsLoading] = useState(false);
    const [username, setUsername] = useState(null);
    const [password, setPassword] = useState(null);
    const [statusMessage, setStatusMessage] = useState(null);


    useEffect(()=> {
        if (userLoggedIn) {
            navigate('/');
        }    
    }, [userLoggedIn]);

    const login = async () => {
        if (username === null || password === null){
            return setStatusMessage("Username and password must be provided!");
        }
        else if(checkUsername(username) === false || checkPassword(password) === false){
            return setStatusMessage("Account Does Not Exist or Password Is Incorrect!");
        }
        else {
            setIsLoading(true);
        }

        const url = 'http://localhost:3001/user/*****';

        await Axios.post(url, {
        username: username,
        password: password,
        }).then((response) => {
            setIsLoading(false);
            if (response.data.loggedIn){
                sessionStorage.setItem('catchingSoulsLoggedin', true);
                sessionStorage.setItem('catchingSoulsUsername', response.data.username);
                if (location.state == null) {
                    navigate('/');
                }
                else if (location.state.previousUrl != location.pathname){
                    navigate(location.state);
                }
            } else {
                setStatusMessage(response.data.message);
            }
        });
    }

    return (
        <>
            <Header/>
            <div className='page_container'>
                <div className='login_form'>
                    <h1>Catching Souls</h1>
                    <input name='username' placeholder='Username' required="true" autoComplete="off" value={username} onChange={(e) => {setUsername(e.target.value) }} />
                    <input name='password' placeholder='Password' type='password' required="true" autoComplete="off" value={password} onChange={(e) => {setPassword(e.target.value) }} />
                    {isLoading && <button className='loginButton' disabled>Loading...</button>}
                    {!isLoading && <button className='loginButton' type='submit' onClick={login}>Login</button>}
                    {isLoading ? <></> : <h2><a href='/Register'>Register?</a> or <a href='/ForgotPassword'>Reset Password?</a></h2>}
                </div>
                {isLoading ? <></> : <h2>{statusMessage}</h2>}
            </div>
            <Footer/>
        </>
    );
}

export default Login;

UPDATE
Adding code for verification page:

import React, { useState, useEffect } from 'react';
import './AdminToolsVerification.css';
//Components
import Header from '../../Components/Header/Header';
import Footer from '../../Components/Footer/Footer';
//Functions
import GetUserProps from '../../Functions/VerificationCheck/getUserProps';
//Entry Checks
import checkPassword from '../../Functions/EntryCheck/checkPassword'
//Repositories
import Axios from 'axios';
import { useNavigate, useParams } from 'react-router-dom';

const AdminToolsVerification = () => {
    const navigate = useNavigate();
    const {AccountUsername} = useParams();
    const [foundAdminAccount, setFoundAdminAccount] = useState(false);
    const [loggedInUserData, setLoggedInUserData] = useState(GetUserProps(true, AccountUsername));
    const [password, setPassword] = useState(null);
    const [confirmPassword, setConfirmPassword] = useState(null);
    const [statusMessage, setStatusMessage] = useState(null);
    const [isLoading, setIsLoading] = useState(false);
    const [firstName, setFirstName] = useState(null);
    const [lastName, setLastName] = useState(null);


    useEffect(() => {
        setIsLoading(true);
        locateUnverifiedAccount();
        setIsLoading(false);
    }, []);

    const locateUnverifiedAccount = async () => {
        const url = 'http://localhost:3001/admin/****************';

        await Axios.post(url, {AccountUsername : {AccountUsername}})
        .then((response) => {
            setFoundAdminAccount(response.data.foundAdminAccount);
            if (response.data.foundAdminAccount){
                loggedInUserData.then(res => setFirstName(res.data[0].accountFirstName))
                loggedInUserData.then(res => setLastName(res.data[0].accountLastName));
            }
        })
        .catch((error) => {
            console.log(error);
        })
    }

    const submitForm = () => {
        if (password == null || confirmPassword == null){
            return setStatusMessage("All fields with "*" be filled in!");
        }
        else if (password !== confirmPassword){
            return setStatusMessage("Password and confirm password does not match!");
        }
        else if (checkPassword(password) == false){
            return setStatusMessage("Password Is Not Acceptable");
        }

        setIsLoading(true);
        const url = 'http://localhost:3001/admin/**********';
                
        Axios.post(url, {
            AccountUsername : {AccountUsername},
            password : password,
        })
        .then((response) => {
            if (response.data.message){
                setIsLoading(false);
                setStatusMessage(response.data.message);
            }
            else {
                navigate('/Login');
            }
        })
        .catch((error) => {
            setIsLoading(false);
            console(error);
        });
    };

    return (
        <>
            <Header/>
            <div className='page_container'>
                <div className='adminToolsVerification_form'>
                    {foundAdminAccount ?
                        <>
                            <h1>Hello {firstName} {lastName},</h1>
                            <p>Please enter a password to verify your account.</p>
                            <input className='password' placeholder='Enter A Password' type='password' required autoComplete="off" onChange={(e) => {setPassword(e.target.value); }} />
                            <input className='confirmPassword' placeholder='Confirm Password' type='password' required autoComplete="off" onChange={(e) => {setConfirmPassword(e.target.value); }} />
                            {isLoading && <button className='registerButton' disabled>Loading...</button>}
                            {!isLoading && <button className='registerButton' type='submit' onClick={submitForm}>Register</button>}
                        </>
                        :
                        <>
                            <h1 style={{color: 'crimson'}}>Not Verified!</h1>
                            <p>Your account is already verified <br/> or <br/> You are not a registered admin.</p>
                            <p>Contact an admin by emailing <a href="mailto:[email protected]">[email protected]</a></p>
                        </>
                    }
                </div>
                {isLoading ? <></> : <h2>{statusMessage}</h2>}
            </div>
            <Footer/> 
        </>
    );
}

export default AdminToolsVerification;

Clone and copy the header section of a site

I plan to copy and use the entire header of this site in a project:
kinsta

Using the Inspect Element. I copy the entire section inside the <header></header> as HTML in my project file.

I will also add all the style and script files of this site to my project page. But unfortunately, none of the parts work properly.
Is it possible to send me the codes of this header in the form of HTML, CSS and JS separately?

Or can you send me a similar example that has good responsiveness on CodePen.io site?

RemoveEventLisenter not working after clicking ‘Add New Task’ button

How to remove event Listener from items (Task1,Task2) after clicking ‘Add new Task’ button ?

I want to remove hidingAndShowing function which is hiding nodeElements which are not the currentTarget because after adding new Task (Add New Task Btn) the nodeList to which hidingAndShowing function is refering to has changed therefore all initial added EventListeners need to be removed and added again.
This is the code -> https://codepen.io/Tukoruzi/pen/QWJbyeX

In other words after ‘Task N’ has been added and opened I want it to close after either ‘Task1’ or ‘Task2’ has been clicked and opened.

const addNewTask = document.querySelector('.new-task-js');
addNewTask.addEventListener('click', () => {
  const accordion = document.querySelector('.accordion');
  accordion.insertAdjacentHTML('beforeend', newTask);

  // remove existing EventListeners because nodeList has changed
  const acc = document.querySelectorAll(".accordion-item-trigger");
  // NOT WORKING!!
  nodeList.forEach(item => {
    item.removeEventListener("click", hidingAndShowing);
  });
 // Add hideShowTarget to newly added Task (by addAdjacentHTML);
  const mostRecentTask = accordion.lastChild.querySelector('.accordion-item-trigger');
 mostRecentTask.addEventListener('click', function(e) {                 hideShowTarget(e); 
  });
 // Handle New Node List anew
 const newNodeList = Array.from(acc);
 newNodeList.forEach(item => {
  item.addEventListener("click", function(e) {
  e.stopPropagation();
  hidingAndShowing(item,newNodeList);
  });
 });
});

Cannot read propety ‘toLowerCase’ of undefined

This is a plugin of rpg maker mv. I think the error is in this part but im not sure.
I use rpg maker mz on this plugin, but i think that the error is not that i use rpg maker mz. I think the error is in the code.
The plugin works perfectly, but when I open the scene this error appears.

I tried to search information online, but the plugin is currently lost.
And the creator seems to be unavailable.

//---------------------------------------------------------------------------------------------
// Scene_Quest
//---------------------------------------------------------------------------------------------
function Scene_Quest() {
this.initialize.apply(this, arguments);
};

    Scene_Quest.prototype = Object.create(Scene_MenuBase.prototype);
    Scene_Quest.prototype.constructor = Scene_Quest;    
    
    Scene_Quest.prototype.initialize = function() {
        Scene_MenuBase.prototype.initialize.call(this);
    };
    
    Scene_Quest.prototype.create = function() {
        Scene_MenuBase.prototype.create.call(this);
        this.qFilters = ["all", "progress", "completed", "failed"];
        this.createQuestWindow();
    };
    
    Scene_Quest.prototype.createQuestWindow = function() {
        this.oldIndex = 0;
        this.questWindow = new Window_Quests();
        this.questWindow.setHandler("cat", this.handleCategory.bind(this));
        this.questWindow.setHandler("quest", this.handleQuest.bind(this));
        this.questWindow.setHandler("cancel", this.popScene.bind(this));
        this.addWindow(this.questWindow);
        this.questInfo = new Window_QuestInfo();
        this.questInfo.setHandler("cancel", this.cancelInfo.bind(this));
        this.addWindow(this.questInfo);
        this.questFilter = new Window_QuestFilter();
        this.addWindow(this.questFilter);
    };
    
    Scene_Quest.prototype.update = function() {
        var index = this.questWindow.index();
        if (this.oldIndex != index) {
            var q = this.questWindow._list[index];
            if (q.symbol === "quest")
                this.questInfo.setQuest(q.ext);
            else 
                this.questInfo.setQuest(-1);
            this.oldIndex = index;
        }
        this.questFilter.filterIndex = this.questWindow.filterIndex;
        this.questFilter.refresh();
        Scene_Base.prototype.update.call(this);
    };
    
    Scene_Quest.prototype.cancelInfo = function() {
        this.questWindow.activate();
        this.questInfo.deactivate();
    }
    
    Scene_Quest.prototype.handleQuest = function() {
        this.questWindow.deactivate();
        this.questInfo.activate();
    };
    
    Scene_Quest.prototype.handleCategory = function() {
        var catIndex = this.questWindow.currentExt();
        this.questWindow.toggle(catIndex);
        this.questWindow.refresh();
        this.questWindow.activate();
    };
    
    // This is used to open up the Quest Log from the menu
    // Used in conjunction with Yanfly's Menu plugin
    Scene_Menu.prototype.commandQuest = function() {
        SceneManager.push(Scene_Quest);
    };

calling an API inside an interceptor lead to an infinite loop of interceptor calls

When I call an API inside an interceptor, it results in an infinite loop of interceptor calls.
Please find code below and help is apreciable.

  axios.interceptors.request.use(async (request) => {
    debugger;
    const result = await axios("https://jsonplaceholder.typicode.com/users/1");
    if (result) {
      console.log(result);
    } else {
      console.error("some error");
    }
    return request;
  });

How do I pass these Javascript tests for my word guess game?

I am new to Javascript and for my assignment, I am supposed to create a word guess game and pass these tests. I did the initial setup for the game and those tests are checked off, but I have other tests that I can’t seem to pass. I tried to debug it as much as I could, like preventing user from entering numbers, repeated incorrect letters aren’t being recorded repeatedly, correctly guessed letters aren’t being recorded as incorrect letters if already used. I am not sure what I am not thinking of or not seeing that is preventing me from passing the following tests:

Playing against the word “banana” and winning ( count b as correct, count “I” as incorrect, solve the word should increase wins and set the game)

Playing against “javascript” and winning (previous word should display “banana”, count 3 incorrect guesses, solving the word should increase wins and reset game)

Play against “mango” and losing (display previous word “javascript”, count 3 incorrect guesses, count a mix of 4 correct and 7 incorrect guesses). This is what I have as of now:

var words = [
  'bananas',
  'grapes',
  'carousel',
  'milkshake',
  'javascript',
  'limousine',
  'chocolate',
  'programming',
  'meatloaf',
  'ukulele',
  'mango'
]

// Make variables for elements using getElementById

let correctGuesses = []
let incorrectGuesses = []
let guessedLetters = []

var maxGuesses = 10
var wins = 0
var losses = 0

var wordToGuess = document.getElementById('word-to-guess')
var remainingGuess = document.getElementById('remaining-guesses')
var incorrectLetters = document.getElementById('incorrect-letters')
var previousWord = document.getElementById('previous-word')
var wins = document.getElementById('wins')
var loss = document.getElementById('losses')

remainingGuess.textContent = maxGuesses

var currentWord = words[Math.floor(Math.random() * words.length)];      
var tempCurrentWord = currentWord
var hiddenWord = Array(currentWord.length + 1).join('_');

wordToGuess.textContent = hiddenWord


document.onkeyup = function(e)                  // Have program register key presses
{
  var key = e.key.toLowerCase()   // filtering keypresses
  console.log(currentWord)

  var letterRegex = /^[a-z]$/;

  if (!letterRegex.test(key) || guessedLetters.includes(key)) {
    return;
  };

  guessedLetters.push(key)

  if (currentWord.includes(key)) {                      
    correctGuesses.push(key);
    let hiddenWordLetters = hiddenWord.split('')
    let currentWordLetters = currentWord.split('')

     for (let i = 0; i < currentWord.length; i++) {
       if (currentWord[i] === key) {
         //currentWordLetters[i] = '_';
         hiddenWordLetters[i] = key;
       }
     }    

    hiddenWord = hiddenWordLetters.join('')
    currentWord = currentWordLetters.join('')

    wordToGuess.textContent = hiddenWord

    if (tempCurrentWord === hiddenWord) {
      wins.innerText++
      reset()
    }

  } else {

    incorrectGuesses.push(key)
    incorrectLetters.textContent = incorrectGuesses.join(', ');
    remainingGuess.textContent--;

    if (remainingGuess.textContent == 0) {
      loss.innerText++; 
      reset()
    }
  }
  
function reset() {
  previousWord.innerText = tempCurrentWord;
  currentWord = words[Math.floor(Math.random() * words.length)];
  tempCurrentWord = currentWord
  hiddenWord = Array(currentWord.length + 1).join('_');
  wordToGuess.innerText = hiddenWord
  remainingGuess.textContent = maxGuesses;
  incorrectGuesses = [];
  guessedLetters = [];
  incorrectLetters.textContent = "";
}

}

How to handle swiper slides to jump and increase and decrease the width of the sliders while scrolling

I used Swiper 9.3.2 in my project.
I want the swiper-slide to have a specific width of 400px when the showCase section is not yet reached, but when the user scrolls and gets the showCase section, the showCase--slider class will take the entire page and the swiper-slide will have its correct width. to take.

All this scenario works correctly, but it has one drawback, when the user is scrolling within the showCase section, the width of the swiper-slides is continuously shifted, creating an inappropriate user experience.

Can you guide me on how to solve this problem?
What is wrong with my work?
Thanks in advance for your guidance.

// Swiper ShowCase
var swiperShowCase = new Swiper(".SwiperShowCase", {
  slidesPerView: 'auto',
  spaceBetween: 15,
  loop: true,

});
// Swiper ShowCase

const target = document.getElementById("showCase");
const widthSlide = document.querySelectorAll('.showCase--slider .swiper-slide');
for (let i = 0; i < widthSlide.length; i++) {
  widthSlide[i].setAttribute("style", "width:430px")
}

window.onscroll = function() {
  const scrollPosition =
    window.pageYOffset ||
    document.documentElement.scrollTop ||
    document.body.scrollTop ||
    0;
  if (scrollPosition >= target.offsetTop) {
    target.classList.add("active");
    swiperShowCase.params.slidesPerView = 3;
    swiperShowCase.update();

    const widthSlide = document.querySelectorAll('.showCase--slider .swiper-slide');
    for (let i = 0; i < widthSlide.length; i++) {
      widthSlide[i].setAttribute("style", "width: fit-content !important")
    }
  }

};
.sectionTop {
  height: 800px;
  width: 100%;
  border: 3px solid green;
  margin-bottom: 5rem;
}

.sectionBottom {
  height: 800px;
  width: 100%;
  border: 3px solid yello;
  margin-bottom: 5rem;
}

.showCase {
  border-bottom: 1px solid rgba(17, 17, 17, 0.1);
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.showCase--content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  height: 1000px;
  border: 1px solid red;
}

.showCase--content::after {
  position: absolute;
  content: "";
  width: 1px;
  height: 100%;
  bottom: 0;
  left: 0;
  background-color: rgba(17, 17, 17, 0.1);
}

.showCase--content::before {
  position: absolute;
  content: "";
  width: 1px;
  height: 100%;
  bottom: 0;
  left: 50%;
  background-color: rgba(17, 17, 17, 0.1);
}

.showCase--content .title {
  width: 35%;
  margin-inline-start: 14px;
}

.showCase--slider {
  width: 50%;
  height: 100%;
  position: relative;
  color: black;
}

.showCase .showCase--slider .swiper {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  margin-right: 0;
  margin-left: auto;
}

.showCase .swiper-slide {
  width: 400px !important;
  padding: 1.5rem;
  border-radius: 16px;
  background-color: rgba(255, 255, 255, 0.7);
  border: 1px solid blue;
}

.showCase .swiper-slide>div {
  position: relative;
  overflow: hidden;
}

.showCase .swiper-slide>div>img.indicatorImage {
  height: 300px;
  width: 100%;
  object-fit: cover;
  -webkit-transform: scale(1.05);
  transform: scale(1.05);
  -webkit-filter: grayscale(100%);
  filter: grayscale(100%);
  transition: all 0.5s;
}

.showCase .swiper-slide>div:hover img.indicatorImage {
  -webkit-filter: grayscale(0);
  filter: grayscale(0);
  -webkit-transform: scale(1);
  transform: scale(1);
}

.showCase .swiper-slide>p {
  font-size: var(--txt18);
  line-height: var(--line-height140);
  color: var(--third-color);
}


/* showCase animation */

@keyframes fadeIn-top {
  0% {
    opacity: 1;
  }
  100% {
    transform: translateY(-500%);
    opacity: 0;
  }
}

@-webkit-keyframes fadeIn-top {
  0% {
    opacity: 1;
  }
  100% {
    transform: translateY(-500%);
    opacity: 0;
  }
}

.showCase.active .showCase--content .title {
  width: 0;
  animation: fadeIn-top 3s forwards;
}

.showCase.active .showCase--content .showCase--slider {
  width: 100%;
  transition: width 2s;
}
<link href="https://cdn.jsdelivr.net/npm/swiper@9/swiper-bundle.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/swiper@9/swiper-bundle.min.js"></script>

<section class="section1"></section>

<section class="showCase" id="showCase">
  <div class="showCase--content">
    <div class="title">
      <h3> Showcases</h3>
    </div>

    <div class="showCase--slider">
      <div class="swiper SwiperShowCase">
        <div class="swiper-wrapper">
          <div class="swiper-slide">
            1
            <div>
              <img src="http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/nebula_brown.png" alt="" class="indicatorImage" />
            </div>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
            </p>
          </div>
          <div class="swiper-slide">
            2
            <div>
              <img src="http://codeskulptor-demos.commondatastorage.googleapis.com/GalaxyInvaders/back05.jpg" alt="" class="indicatorImage" />
            </div>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
            </p>
          </div>
          <div class="swiper-slide">
            3
            <div>
              <img src="http://codeskulptor-demos.commondatastorage.googleapis.com/GalaxyInvaders/back04.jpg" alt="" class="indicatorImage" />
            </div>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
            </p>
          </div>
          <div class="swiper-slide">
            4
            <div>
              <img src="http://codeskulptor-demos.commondatastorage.googleapis.com/GalaxyInvaders/back07.jpg" alt="" class="indicatorImage" />
            </div>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
            </p>
          </div>
          <div class="swiper-slide">
            5
            <div>
              <img src="http://codeskulptor-demos.commondatastorage.googleapis.com/GalaxyInvaders/back02.jpg" alt="" class="indicatorImage" />
            </div>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
            </p>
          </div>
        </div>
        <div class="swiper-pagination"></div>
      </div>
    </div>
  </div>
</section>

<section class="section2"></section>

So i created a voting Dapp using solidity and js and If i click the vote button i keep getting this error

enter image description here

I was expecting sucessful vote.
Here’s the link to my smart contract code
https://polygonscan.com/address/0x7742a518d5db7de7b37eb0590645cebf575a6ffe#code

https://vscode.dev/github/gravity8/PowerArk/blob/main ; this is my js code link

This is just to passs the minimum chracterssssss

I would really appreciate if you could help me. If you have corrections please do

How to return value from an async function [duplicate]

I’m currently into learing JS and working on a demo project.

In this project I am working with the spotify API.

My current Step is to retrieve an API access token by providing an id and a secret.

My issue here is, that im unable to return the resolved value of the promise.

I’m able to console.log the desired values without any issues, but if i try to return it and write the value into a variable for example I’m just getting an unresolved promise.

const getAccessToken = async() => {
    const clientId = ""
    const clientSecret = ""

    const response = await fetch('https://accounts.spotify.com/api/token', {
        method: 'POST',
        body: 'grant_type=client_credentials&client_id=' + clientId + '&client_secret=' + clientSecret,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    });
    try {
        if (response.ok) {
            const fulfilledValue = await response.json();
            return fulfilledValue;
        }
    }
    catch (error) {
        throw (error)
    }
};

const token = getAccessToken()
    .then((data) => {
        data.access_token
        })

console.log(token)

I have already read into a dozen of threads like async/await implicitly returns promise? but I jsut can’t figure out the solution.

  • Tried native way with promises, as well as async/wait
  • wrapped everything into a parent function

Exchange Rates Display

Why is the exchange rate always displaying N/A in the following code after a currency pair is chosen, and how best to fix it?

I expect the exchange rate value to display the calculated valued when a pair is chosen.

What di I do get it it fixed to display the rates properly?

Is there any library I can use to do a better conversion?

{% extends "app/base.html" %}
{% block content %}
<head>
    <title>Cross-Border Payment App</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f2f2f2;
            padding: 20px;
        }
    
        form {
            width: 80%;
            padding: 20px;
            background-color: #ffffff;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
    
        h1 {
            text-align: center;
            color: #333333;
            cursor: pointer; /* Add cursor style to indicate it's clickable */
        }
    
        h1:hover {
            text-decoration: underline; /* Add underline effect on hover */
        }
    
        label {
            font-weight: bold;
        }
    
        input[type="text"],
        select {
            width: 100%;
            padding: 10px;
            border: 3px solid #ccc;
            border-radius: 4px;
            margin-bottom: 10px;
        }
    
        input[type="submit"] {
            width: 100%;
            padding: 10px 20px;
            background-color: #4CAF50;
            color: #ffffff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
    
        input[type="submit"]:hover {
            background-color: #45a049;
        }
    
        .exchange-rate {
            font-size: 14px;
            font-style: italic;
            color: #999999;
            margin-top: 5px;
        }
    
        select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            margin-bottom: 10px;
        }

        email {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            margin-bottom: 10px;
        }
    
        .bank-options {
            border: 1px solid #ccc;
            border-radius: 4px;
            max-height: 100px;
            overflow-y: auto;
            padding: 5px;
        }
    
        .bank-option {
            cursor: pointer;
            padding: 5px;
        }
    
        .bank-option:hover {
            background-color: #f2f2f2;
        }
    
        .bank-option.disabled {
            color: #999999;
            cursor: not-allowed;
        }
    </style>    
    
  </head>
    <body>
        <h1>Glocal Payments</h1>
        <form method="post" action="{% url 'glocal' %}" onsubmit="return validatePaymentAmount()">
            {% csrf_token %}
        
            <div class="form-field">
                <label for="sender_name">Sender's Name:</label>
                <input type="text" name="sender_name" id="sender_name">
            </div>
        
            <div class="form-field">
                <label for="sender_account_number">Sender's Account Number:</label>
                <input type="text" name="sender_account_number" id="sender_account_number">
            </div>
        
            <div class="form-field">
                <label for="sender_country">Sender's Country:</label>
                <select name="sender_country" id="sender_country">
                    <option value="">Select Country</option>
                    <option value="USA">USA</option>
                    <option value="Nigeria">Nigeria</option>
                </select>
            </div>
        
            <div class="form-field">
                <label for="sender_bank">Sender's Bank:</label>
                <input type="text" name="sender_bank" id="sender_bank">
            </div>
        
            <div class="form-field">
                <label for="recipient_name">Recipient's Name:</label>
                <input type="text" name="recipient_name" id="recipient_name">
            </div>
        
            <div class="form-field">
                <label for="recipient_account_number">Recipient's Account Number:</label>
                <input type="text" name="recipient_account_number" id="recipient_account_number">
            </div>
        
            <div class="form-field">
                <label for="recipient_country">Recipient's Country:</label>
                <select name="recipient_country" id="recipient_country">
                    <option value="">Select Country</option>
                    <option value="USA">USA</option>
                    <option value="Nigeria">Nigeria</option>
                </select>
            </div>
        
            <div class="form-field">
                <label for="recipient_bank">Recipient's Bank:</label>
                <input type="text" name="recipient_bank" id="recipient_bank">
            </div>
        
            <div class="form-field">
                <label for="sender_currency">Sender's Currency:</label>
                <select name="sender_currency" id="sender_currency" onchange="calculateExchangeRate()">
                    <option value="">Select Currency</option>
                    <option value="USD-NGN">NGN</option>
                    <option value="NGN-USD">USD</option>
                    <!-- Add other sender currencies here -->
                </select>
            </div>
        
            <div class="form-field">
                <label for="recipient_currency">Recipient's Currency:</label>
                <select name="recipient_currency" id="recipient_currency" onchange="calculateExchangeRate()">
                    <option value="">Select Currency</option>
                    <option value="NGN-USD">USD</option>
                    <option value="USD-NGN">NGN</option>
                    <!-- Add other recipient currencies here -->
                </select>
            </div>
        
            <div class="form-field">
                <label for="amount">Amount:</label>
                <input type="text" name="amount" id="amount">
            </div>

            <div class="form-field">
                <label for="exchange_rate">Exchange Rate:</label>
                <span id="exchange_rate" class="exchange-rate"></span>
            </div>
        
            <div class="form-field">
                <label for="email">Email:</label>
                <input type="email" name="email" id="email">
            </div>
        
            <div class="form-field">
                <label for="narration">Narration/Purpose:</label>
                <input type="text" name="narration" id="narration">
            </div>
        
            <div class="form-field">
                <input type="submit" value="Make Payment">
            </div>
        </form>   
        {% block scripts %}  
        <script>
            function calculateExchangeRate() {
    var senderCurrency = document.getElementById("sender_currency").value;
    var recipientCurrency = document.getElementById("recipient_currency").value;

    // Define the exchange rates
    var exchangeRates = {
      "USD-NGN": 770.00,  // Exchange rate from USD to NGN
      "NGN-USD": 1 / 770.00,  // Exchange rate from NGN to USD
      // Add other currency pairs and their respective exchange rates here
    };

    var currencyPair = senderCurrency + "-" + recipientCurrency;
    var exchangeRate = exchangeRates[currencyPair];

    // Display the exchange rate or "N/A"
    var exchangeRateField = document.getElementById("exchange_rate");
    if (exchangeRateField) {
      if (exchangeRate !== undefined) {
        exchangeRateField.textContent = "Exchange Rate: " + exchangeRate.toFixed(4);
      } else {
        exchangeRateField.textContent = "N/A";
      }
    }
  }

  // Call the calculateExchangeRate function initially and on currency selection change
  document.getElementById("sender_currency").addEventListener("change", calculateExchangeRate);
  document.getElementById("recipient_currency").addEventListener("change", calculateExchangeRate);

  calculateExchangeRate(); // Call it initially to display the exchange rate for the selected currency pair
        </script>
        {% endblock %}
    </body>
{% endblock %}