Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React keydown useeffect not working on page load

I’m trying to listen for keydown events and this code isnt working on initial page load. If i refresh, then make some code changes, and the page refreshes, it works just fine.

Works when:

  1. Open page
  2. Make a code change (like adding a comment or whatever)
  3. React refreshes
  4. Hit the ‘e’ key
  5. Code works as intended

Does NOT work when:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. Open page
  2. Hit the ‘e’ key
  3. Nothing happens

I think there’s an issue with my useEffect’s or my keyPress function but im not sure

import React, { useEffect, useState, useCallback } from "react";
import { shuffle } from "../utils/shuffle";
import './player.css';

const baseUrl = (id) => `https://www.youtube.com/embed/${id}?autoplay=1`;
const magicKey = 'e';

function Player({ searchTerm }) {
  let [ids, setIds] = useState([]); // youtube video ids
  let [url, setUrl] = useState(baseUrl(0));
  let [count, setCount] = useState(0);

  // Play next video when pressing 'e'
  const keyPress = useCallback((e) => {
    // Reset playlist when ids have all been played
    if (e.key === "e" && count >= ids.length) {
      setCount(0)
    }
    else if (e.key === magicKey) {
      setCount(cCount => cCount + 1)
    }
  },[count]);

  useEffect(() => {
    document.addEventListener("keydown", keyPress);
    return () => document.removeEventListener("keydown", keyPress);
  }, [keyPress]);

  // // fetch new ids from backend based on new searchTerm
  useEffect(() => {
    console.log('api call for new ids: ', searchTerm);
    // TODO sub paw patrol with either text input, or button options
    fetch(`http://localhost:4000/videos?term=${searchTerm}`)
      .then((response) => response.json())
      .then((res) => {
        setIds(shuffle(res.videoIds));
        setCount(0);
      });
  }, [searchTerm]);

  // // when the id's change, set a new url for the iframe to play
  useEffect(() => {
    setUrl(baseUrl(ids[count]));
    let videoFrame = document.getElementById('screen')
    videoFrame.src = url;
  }, [ids, count]);


  return (
      <section id="player">
        <iframe id="screen" title="youtube-player" src={url} allow='autoplay'></iframe>
      </section>
  );
}

export default Player;

Ive tried playying around with the useEffect params and setting the listeners in a sepereate useEffect but havent found the right combo

>Solution :

try adding the array of ids as a dependency of keyPress useCallback to see if it works

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading