Sobes.tech
Junior — Senior

Debugging and refining a React application

livecode

Task condition

  1. Implement a request for the current date from the server using the fetchDate function declared in the api.ts file, and display the received value in the component. The interaction with the server is already implemented in api.ts, and you can study the returned data structure.
  2. Track changes in the browser window size and display the current width of the client window. Keep in mind that the application may run on mobile devices.
  3. Add a simple counter: a button that, when clicked, increases the counter value, and the current value is displayed next to the button.
  4. All interface elements should be centered on the screen.
import { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { fetchDate } from "./api";
import "./styles/styles.css";

/**
  * Component for displaying server time and screen height
 */
const App = () => {
    const [count, setCount] = useState(0);
    // Date
    const [date, setDate] = useState < string > ();
    const [clientWidth, setClientWidth] = useState < number > ();

    // @ts-ignore
    useEffect(async () => {
    setDate(await fetchDate());

    window.addEventListener("resize", () =>
        setClientWidth(document.body.clientWidth),
    )
  });

return (
    <div className = "App" >
        <div key="title">Server date: {date} </div>
        <div key="width">Client width: {clientWidth}px</div>
        <Counter
            value={count}
            onClick={() => {
                setCount(count + 1);
            }}
        />
    </div>
   );
};

/* 
* Component that displays the number of clicks on the button */

function Counter(props: any) {
    console.log("CONNTER rendered [ ]");
    /**
    * Percentage was a bit much...
    * Decided to memoize this callback.
    * PLEASE DO NOT REMOVE THE MEMOIZATION!
    */
    const memoizedOnClick = useCallback(() => {
        props.onClick();
    },
    []);
    return (
        <div>
            <button onClick={memoizedOnClick}>+</button>&nbsp;
            {props.value || 0}
        </div>
    );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);