Sobes.tech
Junior — Senior

Detecting and fixing bugs in a React component

livecode

Task condition

In this task, you need to analyze the provided React component fragment and fix any syntactic and logical errors so that the application correctly displays the list of users, a counter, and a timer.

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

const Button = ({ onClick, title, className }) => (
  <div
    className={className}
    style={{ border: "1px solid black", width: "150px", cursor: "pointer" }}
    onClick={onClick}
  >
    {title}
  </div>
);

const User = ({ age }) => <div>{age}</div>;

export default function App() {
  const [clickCount, setClickCount] = useState(0);
  const [userList, setUserList] = useState([]);
  const [timer, setTimer] = useState(15);

  const addUser = () => {
    setClickCount(clickCount + 1);
    setUserList([
      ...userList,
      {
        id: 1 + Math.floor(Math.random() * 10),
        age: Math.round(20 + Math.random() * 40),
      },
    ]);
  };

  const resetAll = () => {
    setClickCount(0);
    setUserList([]);
  };

  useEffect(() => {
    if (timer <= 0) return;
    const id = setTimeout(() => setTimer(prev => prev - 0.1), 100);
    return () => clearTimeout(id);
  }, [timer]);

  const totalAge = userList.reduce((sum, user) => sum + user.age, 0);

  if (timer <= 0) {
    return (
      <div>
        <div>Count: {clickCount}</div>
        <div>Age sum: {Math.round(totalAge)}</div>
        {userList.map(user => (
          <User key={user.id} age={user.age} />
        ))}
      </div>
    );
  }

  return (
    <div>
      <div>Remain time: {timer.toFixed(1)} seconds</div>
      <Button onClick={addUser} title="Add random user" />
      <div>Count: {clickCount}</div>
      <div>Age sum: {Math.round(totalAge)}</div>
      {userList.map(user => (
        <User key={user.id} age={user.age} />
      ))}
      {clickCount > 0 && (
        <Button onClick={resetAll} title="Remove all" className="remove-button" />
      )}
    </div>
  );
}