chatengine-io / react-chat-engine

React component for a cheap and easy chat API
138 stars 35 forks source link

Navigating away & returning to page with ChatEngine causes error #159

Open pint-drinker opened 1 year ago

pint-drinker commented 1 year ago

When loading the chat page for the first time, it works just fine. When reloading the page (CMD + R), the chat page works just fine. But if I click over to another url in my app, and then click back to chat, I get an error. Upon refreshing the page, the chat renders fine.

See the gif below: chat-engine-reload-bug

The error is occurring with the getMyLastMessage function buried within the ChatFeed component:

image image

I can probably get around this by using a custom component with a render hook, but I'd like to avoid that. I have investigated this for some time and it seems like it could be another silly react thing or perhaps a websocket thing I am not privy too.

Here is my code that mounts the ChatEngine

import { ChatEngine } from 'react-chat-engine';
import { getSessionUser } from '../utils/session';

const ChatApp = () => {
  const sessionUser = getSessionUser();

  return (
    <ChatEngine
      height={`calc(100vh - 64px)`}
      projectID={process.env.REACT_APP_CHAT_ENGINE_PROJECT_ID}
      userName={sessionUser.chatUsername}
      userSecret={sessionUser.chatUserSecret}
    />
  );
};

export default ChatApp;

I am using react-router to handle the navigation between the pages seen in the gif above. I am NOT running in strict mode.

pint-drinker commented 1 year ago

I have an update on this one...this bug happens when you have the ChatEngineWrapper wrapped around my entire react-router implementation. Only wrapping the elements on the ChatApp page with the wrapper fixed the issue. I do still think it is a bug however, since I think the chat engine wrapper should be robust to accessing state even when the primary ChatEngine component is not mounted, for things like multi-page chat applications. Think LinkedIn or Facebook...you have a dedicated page for chat, but you also can access the chat feature globally from the top right. I know I could probably rewrite my entire application to sit beneath the ChatEngine component, but that seems like a force. Let me know if anyone else has opinions.

This is my react-router code where it works now

{
          path: '/chat',
          element: (
            <ChatEngineWrapper>
              <ChatApp />
            </ChatEngineWrapper>
          ),
          errorElement: <ErrorPage />,
        },

And this is what it was before:

const App = () => (
  <ChakraProvider theme={theme}>
    <QueryClientProvider client={queryClient}>
      <ChatEngineWrapper>
        <Provider store={store}>
          <RouterProvider router={getRouter(store)} />
        </Provider>
      </ChatEngineWrapper>
    </QueryClientProvider>
  </ChakraProvider>
);