Answer the question
In order to leave comments, you need to log in
How to properly render components and show loading in ReactJS when requesting data from a third-party resource?
Greetings!
Let's say we have a parent application that requests products from a third party resource. While there is a request, you need to show the download.
As I see the solution to the current problem at the moment:
1. The parent requests everything itself and sets the status "show or not" of the child component.
2. The child component waits for a status, and based on one of the statuses, it shows the prepared DOM.
In this regard, a couple of questions:
1. How to correctly render the components that should show the requested products if they are not loaded yet?
2. How and where to place the loading indicator correctly?
I want to see the algorithm, what is located where and when it is called. For clarity of the whole process, I wrote an example "as I see it."
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
products: [],
sectionProductsVisible: "hide",
}
}
// при старте, запрашиваем продукты и разрешаем показ секции с продуктами
componentDidMount() {
this.setState({sectionProductsView: "preloader"});
this.get_products()
// если запрос успешен, то добавляем список продуктов в состояние, а так же меняем статус показа секции с продуктами
.then((products) => this.setState({...products, sectionProductsView: "show"}))
.catch(() => this.setState({sectionProductsView: "error"}));
}
// метод получения продуктов
get_products = () => {
// предположим, это продукты, которые мы получаем fetch-ом
const products = [{id: 1, title: "Чистейший колумбийский JS"}];
return new Promise((resolve, reject) => {
setTimeout(() => {
if(products.length) resolve(products);
else reject();
}, 1000); // имитация задержки при получение продуктов
});
};
render() {
const {sectionProductsVisible} = this.state;
return <App_Template visible={sectionProductsVisible}/>;
}
}
// компонент шаблона секции с продуктами
function App_Template(props) {
const {
visible = "hide",
} = props;
switch(visible) {
case "preloader": // получение продуктов, результат получения не известен (показываем загрузку)
return null;
case "show": // если продукты получены успешно
return null;
case "error": // если при получение продуктов произошла ошибка
return null;
case "hide": // по умолчанию, скрыт
default:
return null;
}
}
Answer the question
In order to leave comments, you need to log in
I don't really remember React.JS class, I'm afraid to make a mistake.
So I can just recommend an example with hooks: https://github.com/kentcdodds/react-hooks/blob/mai...
Description here: https://github.com/kentcdodds/react-hooks/blob/mai.. The
React.JS class is deprecated now (used only in legacy component support).
In general, I think you should definitely take the https://epicreact.dev/ course and skip the React.JS class.
There are repositories with * .md materials on github, there are more than enough of them and the blog, and then, everything is not needed.
Be warned, I have no commercial experience developing React.JS.
A little later, if necessary, I will throw off articles from the documentation, which, in my opinion, need to be studied after the Kent Dodds course.
Fragments on Software Design:
https://www.livelib.ru/book/1003548149-refaktoring...
A fundamental rule of thumb is that things that change at the same time are best kept in one place.
We structure programs to make them easier to change;
When planning a change, we want to be able to go to a certain point in the program and make changes at that point.
When I come across code that deals with two different tasks, I look for a way to separate it into separate modules. I try to make this separation because if I need to make changes to the program, I will have to deal with each task separately and not have to keep both of them in my head. If I'm lucky, it might be enough to make changes to just one module without having to remember the details of the other.
modularity, which provides the ability to make many changes to the program, while at the same time understanding only a small part of it. To achieve this modularity, I need to make sure that related software elements are grouped together so that the relationships between them are easy to find and understand.
If I have a good set of data structures that are appropriate for the task, then the code that implements the behavior is simple and understandable. Bad data structures lead to a lot of code whose job is simply to handle bad data. And it's not just complicated code that's hard to understand; it also means that data structures hide what the program does.
a software entity (class, module, method) should, if possible, solve only one task, but do it well.
The fewer ancillary tasks a method, class, or module has, the less chance of accidental changes.
Won't principles and patterns lead me into a world of overengineering: has my design become simpler after making changes? Am I solving a problem that doesn't really exist?
Am I caught in the trap of premature generalization?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question