Junior — Senior
Detect and fix bugs in a React component
livecode
Task condition
Find and fix the errors in the React component below, which uses hooks useState and useEffect. Pay attention to the correctness of the asynchronous effect and proper management of window scroll events.
import React, { useState, useEffect } from "react";
// Simulated server request
const fetchCall = () => Promise.resolve(Math.random());
const NumberAndScrollX = () => {
const [number, setNumber] = useState(0);
const [scroll, setScroll] = useState(0);
useEffect(async () => {
setNumber(await fetchCall());
}, []); // Empty dependency array to run effect only on mount
useEffect(() => {
const handleScroll = () => setScroll(window.scrollY);
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []); // Cleanup effect on unmount
return (
<div>
<div>Number: {number}</div>
<div>ScrollY: {scroll}</div>
</div>
);
};
export default NumberAndScrollX;