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:
- Open page
- Make a code change (like adding a comment or whatever)
- React refreshes
- Hit the 'e' key
- Code works as intended
Does NOT work when:
- Open page
- Hit the 'e' key
- 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
CodePudding user response:
try adding the array of ids as a dependency of keyPress useCallback to see if it works