A
A
Andrew2019-10-09 06:24:21
JavaScript
Andrew, 2019-10-09 06:24:21

Why does TypeScript only fire after a page refresh?

There is a page of dialogs and messages, how almost everything looks in the cart, so when you click on the chat, you can click on the star in the header and add it to your favorites (the star appears on the dialog, but nothing happens when you click it, but if you refresh the page, then the asterisk appears, i.e. I call the script, it works and transfers to the database, but does not show it on the screen, why?
Here is the code:


static setStar() {
//
let chat_id = A.dialogs._cache.getActiveChatId();
//
let is_favorite = A.dialogs._cache.getStar(chat_id);
//
let ar_post = {
chat_id: chat_id
};
// if is favorite is zero then
if (is_favorite == 0) {
// update cache
A.dialogs._cache.setStar(chat_id, 1);
//access the chat backend and API class
. call('chats/addToFavorite', ar_post);
// makes the star viewable by removing the hidden class
$('path_dialog_item_star' + chat_id).removeClass('hidden');
}
// if the value of is favorite is equal to one then
if (is_favorite == 1) {
// update cache to 0 if equal to 1
A.dialogs._cache.setStar(chat_id, 0);
// call the api to remove the favorite star
API.call('chats/doRemoveFromFavorite', ar_post);
// makes the star invisible by adding a hidden class
$('path_dialog_item_star' + chat_id).addClass('hidden');
}
}

this function is written in the HTML in the header like this:


And it is also written in dialog_item.ejs that the asterisk would be displayed on the dialog itself

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ermolaev, 2019-10-20
@ermolaevalexey

Well, firstly, typescript has nothing to do with it at all, since it compiles to Js.
Secondly, the value of the is_favoutite variable is not overwritten anywhere in the code, but is taken at the beginning from a certain “cache”. Thirdly, you perform an asynchronous operation - a request to the backend to change data, but at the same time you do not even try to process the result of this request in any way - add some kind of callback, wrap it in a promise, use async / await, which are also promises, but under the hood.
With such operations, the answer does not come immediately, but after some time, therefore, according to the classics, callbacks are added to the methods that perform asynchronous operations - functions that can accept the result and process it.
I advise you to read about the event loop, promises, and generally about asynchrony in js. Well, or for starters, at least it’s better to know the api of the tool you use, namely jquery and the ajax method, at least.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question