0

I am making a chat application with React but for some reason, every console.log in my app gets stuck in a loop and sends an endless amount of logs to the console. I'm a little extra confused because I am doing a video tutorial for this app and have followed everything perfectly so far (since I'm only about ten minutes in).

Here is my app component:

import { ChatEngine } from 'react-chat-engine';

import ChatFeed from './components/ChatFeed';

import './App.css';

const App = () => {
  return (
    <ChatEngine
      height='100vh'
      projectID='70565141-7ecc-48ba-8cf4-684117eff882'
      userName='Jay'
      userSecret='123123'
      renderChatFeed={(chatAppProps) => <ChatFeed {...chatAppProps} />}
    />
  );
};

export default App;

And here is my ChatFeed component:

import MessageForm from './MessageForm';
import MyMessage from './MyMessage';
import TheirMessage from './TheirMessage';

const ChatFeed = (props) => {
  const { chats, activeChat, userName, messages } = props;

  const chat = chats && chats[activeChat];

  const renderMessages = () => {
    const keys = Object.keys(messages);

    console.log(keys);
  };

  renderMessages();

  return <div>Chat feed</div>;
};

export default ChatFeed;

I am assuming this has something to do with my component being rendered and just endlessly logging everytime it renders but I'm not sure how to fix this. It's not causing any issues with the program running but debugging will be pretty difficult and annoying if I can't fix this.

Casey Cling
  • 401
  • 2
  • 5
  • 15
  • Since `ChatEngine` is rendering your `ChatFeed`, that would be a good place to look for the culprit. For example, in the source code I see that it uses a context with a wide variety of states: https://github.com/alamorre/react-chat-engine/blob/master/src/components/Context/index.js – salezica May 10 '21 at 21:17

1 Answers1

3

This is because the component keeps rerendering... You need to put it in useEffect hook.

import { useEffect } from 'react';
import MessageForm from './MessageForm';
import MyMessage from './MyMessage';
import TheirMessage from './TheirMessage';

const ChatFeed = (props) => {
  const { chats, activeChat, userName, messages } = props;

  const chat = chats && chats[activeChat];

  useEffect(() => {
     const renderMessages = () => {
         const keys = Object.keys(messages);

         console.log(keys);
     };

     renderMessages();
  }, [messages]);

  return <div>Chat feed</div>;
};
export default ChatFeed;
Cavdy
  • 598
  • 8
  • 15