Git Product home page Git Product logo

Comments (1)

OvidijusParsiunas avatar OvidijusParsiunas commented on August 12, 2024

Hi @subhashnaidu.
If you are controlling state inside a React component and that state changes -> the HTML will always be re-rendered -> and along with it the Deep Chat component. This is a standard React convention.

Having looked at your code, you can limit the infinite re-render loop by adding a if (!message.isHistory) in the onMessage event code to make sure updateChatHistory is only called when new messages are added and not when they are populated from history. However this will still cause a re-render because you are using setChatHistory inside it.

I don't really understand why you are using sessionStorage as Deep Chat stores the message history inside it during a session anyway, so using the chatHistory state seems rather redundant to me.

Point is, history should not be stored in React component state as it will always cause a re-render

If you need some more long-term storage, I would advise you to use localStorage instead. I have created the following boilerplate example using some of your code to help you get started, you can then change it to your liking as needed:

import { MessageContent } from 'deep-chat/dist/types/messages';
import {DeepChat} from 'deep-chat';
import dynamic from 'next/dynamic';
import {useRef} from 'react';

export default function Home() {
  const chatContainerRef = useRef<HTMLDivElement>(null);

  const DeepChat = dynamic(() => import('deep-chat-react').then((mod) => mod.DeepChat), {
    ssr: false,
  });

  const getChatHistory = (): MessageContent[] => {
    const storedHistory = localStorage.getItem('messages');
    if (storedHistory) {
      return JSON.parse(storedHistory);
    } else return [];
  };

  const updateChatHistory = () => {
    if (!chatContainerRef.current) return;
    const deepChatElement = chatContainerRef.current.children[0] as DeepChat;
    localStorage.setItem('messages', JSON.stringify(deepChatElement.getMessages()));
  };

  return (
    <div ref={chatContainerRef}>
      <DeepChat
        demo={true}
        history={getChatHistory()}
        onMessage={({isHistory}) => {
          if (!isHistory) updateChatHistory();
        }}
      ></DeepChat>
    </div>
  );
}

You can ofcourse store each message individually, here is another simplified example that does this:

import {MessageContent} from 'deep-chat/dist/types/messages';
import dynamic from 'next/dynamic';

export default function Home() {
  const DeepChat = dynamic(() => import('deep-chat-react').then((mod) => mod.DeepChat), {
    ssr: false,
  });

  const getChatHistory = (): MessageContent[] => {
    const storedHistory = localStorage.getItem('messages');
    if (storedHistory) {
      return JSON.parse(storedHistory);
    } else return [];
  };

  const updateChatHistory = (message: MessageContent) => {
    const history = getChatHistory();
    history.push(message);
    localStorage.setItem('messages', JSON.stringify(history));
  };

  return (
    <DeepChat
      demo={true}
      history={getChatHistory()}
      onMessage={({message, isHistory}) => {
        if (!isHistory) updateChatHistory(message);
      }}
    ></DeepChat>
  );
}

I hope this helps you in your endeavour.

I will close this issue because it is very related to the following issue, so if you have any further queries in regards to the issue of controlling state, I would advise you to comment there, however if you have any specific questions in regards to the code above, you can comment here. Thanks!

#154

from deep-chat.

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.