D
D
Daniil Sugonyaev2018-09-27 18:10:45
JavaScript
Daniil Sugonyaev, 2018-09-27 18:10:45

How to properly organize communication between components?

There is a product card. It has a lot of small components. For example, "Add to Favorites". The element is the simplest - when clicked, the heart should be painted over, when it is repeated, it should lose color. The question is in the organization of the code. When I click, I change the element through state. If you update it in the parent, then the entire parent component is re-rendered, so I took it out separately, the problem disappeared. But I still need to send data to the server on click. In theory, then should I also make a request to the server in this small component?
This is not consistent with the principle that we should have all requests in the main smart component, and the rest should be simple, without a state and requests. But if everything is done through the main one, there will be much re-rendering. How do you deal with such a situation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-09-27
@coolswood

You can do this:
1. The onClick method is passed from the parent component.
2. The state of the icon is calculated from the received props, but also changes on click, for a more comfortable user experience.
3. Upon returning a response from the server, the entire card is updated. Also, the state of the icons in computeDerivedState is updated, you never know there was an error and the product was not included in the favorites.
4. In case of an error, a pop-up notification can be shown in the lower left corner of the screen. To do this, you can write an action and call it in the catch block of asynchronous actions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question