Sobes.tech
Junior — Senior

Fix a React component that receives a random number and tracks scrolling

livecode

Task condition

The task requires fixing several common errors in a React component that asynchronously fetches a random number and displays the current scroll position of the window. The component is written using useState and useEffect hooks, but it contains issues such as using an async function directly inside useEffect, missing the dependency array, and incorrect management of the scroll event handler.

import React, { useState, useEffect } from "react";

// Simulate a server request that returns a random number asynchronously
const getRandomNumber = () => Promise.resolve(Math.random());

const RandomNumberWithScroll = () => {
    const [randomNum, setRandomNum] = useState();
    const [scrollPos, setScrollPos] = useState();

    useEffect(() => {
        const fetchData = async () => {
            setRandomNum(await getRandomNumber());
        };
        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>
    );
};

export default RandomNumberWithScroll;

You need to rewrite the useEffect so that it correctly handles the asynchronous request and properly adds/removes the scroll event listener, as well as include the dependency array if necessary.