Junior — Senior
Detect and fix defects in a React component
livecode
Task condition
Find and fix the errors in the code snippet below. Pay attention to state management, event handling, and working with the data array.
import React, { useState, useEffect } from "react";
function getRandomInt(min, max) {
let rand = min + Math.random() * (max - min);
return Math.round(rand);
}
// simulate server request – returns a number asynchronously
const fetchRandomNumber = () => Promise.resolve(getRandomInt(9000, 11000));
const dataList = [];
export const randomList = () => {
const [count, setCount] = useState(0);
const [scrollPos, setScrollPos] = useState(0);
useEffect(() => {
const loadData = async () => {
setCount(await fetchRandomNumber());
const onScroll = () => setScrollPos(window.scrollY);
window.addEventListener("scroll", onScroll);
for (let i = 0; i < count; i++) {
dataList.push(getRandomInt(0, 20));
}
};
loadData();
return () => {
const onScroll = () => setScrollPos(window.scrollY);
window.removeEventListener("scroll", onScroll);
};
}, []);
return (
<div>
<div>Number of directories: {count}</div>
<div>Scroll: {scrollPos}</div>
<div>Received values list</div>
<div style={{ height: 400, overflowY: "hidden" }}>
{dataList.map((el, index) => (
<div key={index}>
<div>Directory {index}</div>
<div>{el}</div>
</div>
))}
</div>
</div>
);
};