Basically I think my question is why is it that why can't i access allUserMessages from my state within useEffect with nothing in its dependency array? More details below. Thank you.
I am trying to push to an array in my state with useeffect like componentDidMount for incoming websockets data. But when messages come in it seems to push the most recent message but doesnt keep the rest of the array because in my chat log im only getting the most recent message sent instead of a log of all the messages. When I take out the empty dependencies array in my useeffect function, it can push to the array and has the full chat log, but it seems to receive the message recursively with each message in my array so by the 5th or 6th message the app becomes very slow It console logs the same message a bunch of times and increases with each message. Please have a look at my code if you wouldn't mind and let me know if you have any ideas. I really aprpreciate it.
const socket = io.connect()
const Community = () => {
const [userMessage, setUserMessage] = useState("");
const [allUserMessages, setUserMessages] = useState([])
const [showMentions, setShowMentions] = useState(false)
const [activeUsersForMentions, setActiveUsersForMentions] = useState([])
const [mentionIDs, setMentionIDs] = useState([])
const [userID, setUserID] = useState()
useEffect(()=>{
socket.on("incomingMessage", (data) => {
console.log(data);
socket.emit("joinRoom", {roomid: 'lounge'})
console.log('joining room');
//get the current list of all messages on the channel
//push the new message with the info from data
let isUserMentioned = false;
if(typeof data.mentions.find(x=>x === userID) != 'undefined'){
isUserMentioned = true;
}
console.log(allUserMessages);
//set state again with modified array to include the new message
setUserMessages([...allUserMessages, {first_name: data.first_name,
last_name: data.last_name,
avatar: data.avatar,
message: data.message,
account_type:data.account_type,
isMentioned: isUserMentioned}])
})
},[])