Skip to content

Instantly share code, notes, and snippets.

@ivansky
Created May 10, 2022 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivansky/6ae0ffcb0b9196bdd7620e75e5cee917 to your computer and use it in GitHub Desktop.
Save ivansky/6ae0ffcb0b9196bdd7620e75e5cee917 to your computer and use it in GitHub Desktop.
Catalog.tsx
import React, { useEffect, useState } from "react";
import { render } from "react-dom";
import generateRandomWord from "random-words";
interface Data {
id: string;
data: string;
}
const DATA_CHUNK = 10;
function fetchData() {
return new Promise<Data[]>((resolve, reject) => {
const data: Data[] = Array.from(Array(DATA_CHUNK).keys(), (index) => {
return { id: index.toString(), data: generateRandomWord() };
});
// Mock some errors during request
return Math.random() > 0.5 ? resolve(data) : reject("Error during request");
});
}
const Catalog = React.memo(() => {
const [count, setCount] = useState<number>(0);
const [record, setRecord] = useState<Record<string, Data>>({});
const handleError = (error: Error) => {
console.error(error.message);
};
useEffect(() => {
fetchData()
.then((res) => {
res.forEach((result) => setRecord({ ...record, [result.id]: result }));
})
.catch((error) => handleError(error));
}, [count, handleError]);
return (
<div className="Catalog">
<ul>
{Object.values(record).map((item) => {
return <li>{item.data}</li>;
})}
</ul>
<hr />
This was {count} time you fetched data
<button onClick={() => setCount(count + 1)}>Fetch more</button>
</div>
);
});
const rootElement = document.getElementById("root");
render(<Catalog />, rootElement, () =>
console.log("Render of <Catalog /> component")
);
@ivansky
Copy link
Author

ivansky commented May 10, 2022

The code that compiles
Possible questions:

  • What we will see on screen?
  • How many times we will read "Render of component" in console
  • What will be the length of record after 3 presses of button?
  • What will be the length of displayed list after 2 presses of a button?
  • Is this code OK? It actually compiles without errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment