#Answer endrits079
1 messages · Page 1 of 1 (latest)
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
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 here I asked on redit this question https://www.reddit.com/r/nextjs/comments/ovfsrh/how_do_i_properly_use_laravel_echo_with_nextjs/
2 votes and 1 comment so far on Reddit
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))
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 🤦 🤣
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
just wanna clarify doing something like
setloading(() => {
setLoadingMsg("");
return false;
}
doesn't do any harm, does it?
Thats what I am wondering too, didn't see any unexpected behaviour