Home > OS >  The array doesnt print its values in React
The array doesnt print its values in React

Time:09-27

I am trying to make a socket io simple chat app and the connection works fine. The problems comes with the const renderChat. The console.log is read and correctly printed (with the value in the textbox) also if I put a static text it is also displayed on the frontend, however, for some reason it doesn't print

{msg.data["message"]}

which has to print each value in an array. Also I am almost certain that the array is emptied every time and the useEffect doesn't work properly but I can't really test that yet. Would be glad if I get solution to both problems!

import './App.css';
import io from 'socket.io-client'
import { useEffect, useState } from 'react'
import React from 'react';
import ReactDOM from "react-dom/client";


const socket = io.connect("http://localhost:3001");

function App() {
  const [message, setMessage] = useState("");
  const [chat, setChat] = useState([]);
  const sendMessage = () => {
    socket.emit("send_message", { message });
  };

  const renderChat = () => {
    return (
      chat.forEach(msg => {
        <h3>{msg.data["message"]}</h3>
        console.log(msg.data)
      })
    )
  }

  useEffect(() => {
    socket.on("receive_message", (data) => {
      setChat([...chat, { data }])
    });
  }, [socket])
  return (
    <div className="App">
      <input placeholder="Message..." onChange={(event) => {
        setMessage(event.target.value);}}
        />
      <button onClick={sendMessage}>Send Message</button>
      <h1>Message:</h1>
      {renderChat()}
    </div>
  );
}

export default App;

CodePudding user response:

Please use map instead of forEach

    const renderChat = () => {
    return (
      chat.map(msg => {
        <h3>{msg.data["message"]}</h3>
        console.log(msg.data)
      })
    )
  }

CodePudding user response:

Use map instead of forEach

map actually returns an array of the returned results.

forEach on the other hand does not return anything.

const renderChat = () => {
    return (
      chat.map(msg => {
        <h3>{msg.data["message"]}</h3>
        console.log(msg.data)
      })
    )
  }

CodePudding user response:

modify your renderChat function to use map instead and the console log message should be before the return statement of the map function

const renderChat = () => {
    return (
        chat.map(msg => {
            console.log(msg.data)
            return (
                <h3>{msg.data["message"]}</h3>
            )
        })
    )
}
  • Related