Scrolling to previous height after api fetch flickers screen

  Kiến thức lập trình

I have a chat application where the scrolling position should be in the previous (before loadMore) height. Since I have to scroll AFTER the rendering completion, I have wrapped scrolling around setTimeout to clear the callstack first.
This causes little screen flickering.

const chatbox = document.getElementById('callbox-scroll');
function onLoadMore() {
    const height = chatbox.scrollHeight;

    if (clientID && channelID) {
        fetchMore({
            variables: {
                first: LIMIT,
                clientId: +clientID,
                channelId: +channelID,
                after: pageInfo.endCursor,
            },
        }).then(() => scrollToLastMessage(height));
    }
}
export function scrollToLastMessage(height: number) {
    setTimeout(() => {
        const top = chatbox?.scrollHeight - height;
        chatbox?.scrollTo({ top });
    }, 0);
}

Is there any better way to do this? Specially to avoid screen flickering.

LEAVE A COMMENT