Git Product home page Git Product logo

Comments (25)

supersnager avatar supersnager commented on July 29, 2024 1

@yevhen-logosha I have probably found what causes this behavior.

From what I have found the main problem is that onYReachEnd is fired on the first <MessageList /> render even when the content is smaller than component height and there is no scrollbar at all.
This is caused by calling updateScroll method of ReactPerfectScrollbar in the ResizeObserver callback.
This callback is fired the first time when a watched element is inserted into the DOM (The documentation says: "Observation will fire when watched Element is inserted/removed from DOM.").

Now I need to find a way to prevent the updateScroll method from firing when the element is inserted.
I need so time to make a fix. Probably tomorrow will try to deal with this, so please be patient it will definitely be fixed.

One more thing: onYReachEnd is fired three times in your repro because the Modal renders its own content three times.

from chat-ui-kit-react.

supersnager avatar supersnager commented on July 29, 2024

@louisholley It's strange because it should work out of the box exactly as you said.

Please compare your code with this example in the storybook: https://chatscope.io/storybook/react/?path=/docs/components-messagelist--loading-more-state

What are the differences? How can I reproduce it?

from chat-ui-kit-react.

louisholley avatar louisholley commented on July 29, 2024

yeah pretty sure my code is as the example:

<ChatContainer className="chat-body">
  <MessageList
    onYReachStart={loadMore}
    loadingMore={loadingMore}
  >
    {networkStatus === NetworkStatus.loading ? (
      <LoadingMessages />
    ) : (
      groupedMessages.map((messages, i) => (
        <MessageGroup
          direction={sentByMe ? "outgoing" : "incoming"}
          sender={messages[0].user.forenames}
          sentTime={messages[0].createdAt}
        >
          {!sentByMe && (
            <Avatar
              src={messages[0].user.photoUrl}
              name={messages[0].user.forenames}
            />
          )}
          <MessageGroup.Messages>
            {messages.map((message, i) => (
              <Message
                key={i}
                model={{
                  message: message.content,
                }}
              />
            ))}
          </MessageGroup.Messages>
        </MessageGroup>
      ))
    )}
  </MessageList>
</ChatContainer>;

then

 const loadMore = async () => {
    if (loadingMore) return;
    setLoadingMore(true);

    await fetchMore({
      variables: { id, after: data.conversation.messages.after },
    });

    setLoadingMore(false);
  };

it loads 2 or 3 batches before exhibiting the behaviour I described...not sure what to suggest in terms of reproducibility. I'll see if I get the time today to setup a codesandbox or something

from chat-ui-kit-react.

louisholley avatar louisholley commented on July 29, 2024

so i just replaced MessageGroup with a custom component and it is working perfectly...maybe it's from me trying to combine this UI kit with lots of custom code that is the issue. happy for you to close this! thanks :)

from chat-ui-kit-react.

yevhen-logosha avatar yevhen-logosha commented on July 29, 2024

Facing similar business with onYReachStart too.
My chat is in modal.
First thing is that it calls onYReachStart method on initial render(first modal open) even though scroll bar is at the bottom initially.
Second and consequent openings of modal dont fire onYReachStart.
Second thing is When I scroll to top, getting infinite calls of onYReachStart..

const Chat = () => {
...

  const onYReachEnd = () => {
    if (moreMessageLoading) {
      return;
    }

    try {
      loadMoreMessages({
        variables: {
          topicKey,
          afterMessageId: lastLoadedMessageId,
          direction: 'ASC',
          pageSize: 20,
        },
      });
    } catch (error) {
      console.error('Failed to load more: ', { error });
    } 
  };


  const getMessageHistory = () => {
    return messages.map((message) => {
      const isLastUnread = chatMessagesByTopic.getChatMessageByTopic.lastViewedMessageId === message.id;
      const messageDirection = message.ownMessage ? 'outgoing' : 'incoming';
      const messageFooterMessage = moment(message.createdAt).format('MMM DD, YYYY [at] h:mma z');
      return (
        <div as="Message" key={message.id}>
          <StyledMessage
            $isOwnMessage={message.ownMessage}
            model={{
              message: message.messageBody,
              direction: messageDirection,
            }}
          >
            <StyledMessage.Footer sender={messageFooterMessage} />
          </StyledMessage>

          {localUnreadCount && isLastUnread && (
            <ServiceMessage id="unreadCountMsg" $isUnreadCount>
              {localUnreadCount} Unread Messages
            </ServiceMessage>
          )}
        </div>
      );
    });
  };

return (
    <div style={{ position: 'relative', height: '500px' }}>
      <StyledMainContainer>
        <StyledChatContainer>
          <MessageList
            ref={msgListRef}
            autoScrollToBottomOnMount={false}
            autoScrollToBottom={false}
            scrollBehavior="smooth"
            loadingMore={moreMessageLoading}
            onYReachEnd={onYReachEnd}
          >
            {!chatMessagesByTopic ? <ServiceMessage>No Messages Yet</ServiceMessage> : getMessageHistory()}
          </MessageList>
          {chatMessagesByTopic && (
            <StyledMessageInputGroupContainer as={MessageInput}>
              <MessageInput
                ref={inputRef}
                onChange={(msg) => setMsgInputValue(msg)}
                value={msgInputValue}
                sendButton={false}
                attachButton={false}
                onSend={handleSend}
                autoFocus
                style={{
                  flexGrow: 1,
                  borderTop: 0,
                }}
              />
              <StyledButton isTall onClick={() => handleSend(msgInputValue)} disabled={msgInputValue.length === 0}>
                Send
              </StyledButton>
            </StyledMessageInputGroupContainer>
          )}
        </StyledChatContainer>
      </StyledMainContainer>
    </div>
  );
};

FYI not even using freshly fetched messages yet (I mean not rendering them) just want to get them logged.
Closing modal first time also triggers onYReachStart (if scrollbar is at the top at the time of closing)
Similar behaviour is for onYReachEnd.. Must be doing something wrong 🤔

@supersnager any chance you could think of whats wrong with the code above ?

for onYReachEnd added autoScrollToBottomOnMount={false} and autoScrollToBottom={false} still on chat open in modal, it makes api calls until all messages are fetched because scroll bar is at the bottom of the screen

from chat-ui-kit-react.

yevhen-logosha avatar yevhen-logosha commented on July 29, 2024

@louisholley hey mate, what have you used as a custom component instead of MessageGroup ? Getting kinda similar infinite calls to api in onYReactStart/End

from chat-ui-kit-react.

yevhen-logosha avatar yevhen-logosha commented on July 29, 2024

basically soon as chat loads, both onYReachStart and onYReachEnd gets called. Even with autoScrollToBottomOnMount={false} and autoScrollToBottom={false} 😖

from chat-ui-kit-react.

supersnager avatar supersnager commented on July 29, 2024

@yevhen-logosha Can you provide a minimal repro repository, please?

from chat-ui-kit-react.

yevhen-logosha avatar yevhen-logosha commented on July 29, 2024

@supersnager thanks for reply. Here is super simple repo using modal I use elsewhere, https://codesandbox.io/s/unruffled-booth-de3wb
its done in 10 mins so no judging 🙈

Open console please, click open modal and see onYReachEnd called few times, there are like 10msg so no scroll bar even..
close modal, observe onYReachEnd called few times again..
autoScrollToBottomOnMount={false} and autoScrollToBottom={false} applied..

Perhaps its ok behaviour, but how could we make it so we dont call either onYReachEnd or onYReachStart upon first render 🤔
Im also getting double calls of either of those at work, but that beast is tough to make a repo out of lol.

Here is the gist:

  • using apollo graphql, calling query, in useeffect setting result to state,
  • render messages from that state.
  • upon scroll - fetching more data with uselazyquery,
  • adding result to same state
  • all renders well..

just infinite scroll bugs me..
each scroll calls api twice now, then bounces back(good), scroll again - 2 calls and so on, plus upon initial render onYReach both get called..

sorry long, boring and confusing

from chat-ui-kit-react.

supersnager avatar supersnager commented on July 29, 2024

@yevhen-logosha Thanks for repro. I will analyze it and come back to you with my thoughts.

from chat-ui-kit-react.

yevhen-logosha avatar yevhen-logosha commented on July 29, 2024

@supersnager thanks for your time and work mate.

from chat-ui-kit-react.

GhazanfarKhan avatar GhazanfarKhan commented on July 29, 2024

@supersnager onYReachStart={loadChannelMessages}> mine method is also firing multiple times on just rendering. I just move it to bottom inside useEffect

setTimeout(() => {
if (msgListRef.current)
msgListRef.current.scrollToBottom('smooth');
}, 1000);

How to stop it on first render until the user scroll to top manually. Is this related to the above issue?

from chat-ui-kit-react.

supersnager avatar supersnager commented on July 29, 2024

@yevhen-logosha Please try v1.6.1
I have added disableOnYReachWhenNoScroll property to <MessageList />. Set this property to true and let me know if this helped.

@GhazanfarKhan It looks like your problem is related to this issue. onYReachStart also is fired sometimes by default where there is no scrollbar. Please check the mentioned version and come back with your result.

from chat-ui-kit-react.

yevhen-logosha avatar yevhen-logosha commented on July 29, 2024

@supersnager looks good mate. thanks for your work! 🍻

from chat-ui-kit-react.

GhazanfarKhan avatar GhazanfarKhan commented on July 29, 2024

In my case its not working. I manually setup a field and when the message binds and scroll moves to bottom on first load then I made that field false.

from chat-ui-kit-react.

supersnager avatar supersnager commented on July 29, 2024

@GhazanfarKhan I'm not sure what do you mean. Could you please describe it more precisely or prepare some simple repro?

from chat-ui-kit-react.

GhazanfarKhan avatar GhazanfarKhan commented on July 29, 2024

Hi check this sandbox. https://codesandbox.io/s/angry-star-wq9m5 on onYReachStart is called and End called 2 times

from chat-ui-kit-react.

supersnager avatar supersnager commented on July 29, 2024

@GhazanfarKhan Thanks for repro. I will analyze it and come back to you with my thoughts.

from chat-ui-kit-react.

supersnager avatar supersnager commented on July 29, 2024

Note to myself:
resizeObserver is the key for a case when the scrollbar exists.

from chat-ui-kit-react.

rawatmanoj avatar rawatmanoj commented on July 29, 2024

Hi, I am getting the same issue. did anyone find any fix??

from chat-ui-kit-react.

laakal avatar laakal commented on July 29, 2024

We fixed it using lodash debounce.

from chat-ui-kit-react.

supersnager avatar supersnager commented on July 29, 2024

@laakal Could you please explain more?

from chat-ui-kit-react.

ryanalencar avatar ryanalencar commented on July 29, 2024

How did you fix this problem? I'm having the same, API is called two times when the MesageList first renders.

from chat-ui-kit-react.

supersnager avatar supersnager commented on July 29, 2024

@ryanalencar When do you call the API, is it in the onYReachEnd?

from chat-ui-kit-react.

j-krl avatar j-krl commented on July 29, 2024

When I set scrollBehaviour="smooth", the scrollbar always starts at the top on first render. This doesn't happen with the default scrollBehaviour="auto". Can open a separate issue for this.

from chat-ui-kit-react.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.