#Answer endrits079

1 messages · Page 1 of 1 (latest)

fair leaf
#

What are you trying to achieve? Some specific behaviour with useEffect?

#

Without much context, I'd say create an object that holds these values instead

smoky geode
# fair leaf What are you trying to achieve? Some specific behaviour with useEffect?

I am using laravel echo and inside useEffect on mount I subscribe to channels and I listen for events on mount
`useEffect(()=>{
Echo.channel("chat").listen("new.message",data=>{

})
},[])`
the state1 is supposed to hold all messages and before I was using only state1 and inside the callback I was saying setState1(state1.concat(data)), where data held the new message
but because we are on mount the state1 is always the intial value adding state1 to array of dependencies in useEffect would cause to subscribe everytime to channel and we want to avoid that so I was using a new state (state2) to store the new message and then I was using another useEffect where I checked when state2 changed added the new message to state1 and then set it again to empty and I am doing it the way I shared the code

fair leaf
#

oh thanks, there's actual code there, that makes it easier haha let me see

#

Can you share the complete code block?

#

Doesn't seem you really need newMessage - I think you're just delaying when your state gets updated there

#

Maybe your first example would work, with one change

useEffect(()=>{
Echo.channel("chat").listen("new.message",(data)=>{
setState(state.concat(data)) // here data is the new message that is sent

})

Change the setState call to

setState(currentState => currentState.concat(data))

smoky geode
#

yeah, now I see the answer had redit open from last night and didn't see the update, I was using the callback in the new message but not in the messages state, oh gosh I feel dumb 🤦 🤣

fair leaf
#

oh shit, there's a reply there, wasted a few mins reading all that then 😂

#

I guess my last tip would be, avoid calling a variable state it's confusing specially if you have multiple setState hehe ignore me if that's just your example variable

smoky geode
#

yeah I do messages, setMessages just for example

#

thanks a lot

lusty roost
#

just wanna clarify doing something like

setloading(() => {
  setLoadingMsg("");
  return false;
}

doesn't do any harm, does it?

smoky geode