Junior — Senior
Detect and fix bugs in a React component
livecode
Task condition
This fragment of the React application contains several syntactic and logical errors. They need to be identified and fixed so that the application displays correctly and responds properly to scrolling.
import React, { useState, useEffect, StrictMode } from 'react';
import { createRoot } from "react-dom/client";
const fetchRandomNumber = () =>
Math.random() < 0.5
? Promise.resolve(Math.random())
: Promise.reject(new Error('Request error.'));
const App = () => {
const [randomNum, setRandomNum] = useState();
const [scrollPos, setScrollPos] = useState();
useEffect(() => {
const fetchData = async () => {
try {
const num = await fetchRandomNumber();
setRandomNum(num);
} catch (error) {
console.error(error);
}
};
fetchData();
const handleScroll = () => setScrollPos(window.scrollY);
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
return (
<div>
<div> Number: {randomNum} </div>
<div> Scroll: {scrollPos} </div>
</div>
);
};
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<StrictMode>
<App />
</StrictMode>
);