Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
React setState not updating state inside stomp.js callback function

I have a page that connects to a SockJS socket over stomp. But when pass a function that is supposed to change the state to the .subscribe callback it doesn't change the page's state (the rest of the function completes normally) Here is the code:

export default function HomePage() {

    ...some other states...

    const [isIncomingCall, setIsIncomingCall] = useState(false)

    function initSocket() {
        const socket = new SockJS(`${process.env.API_URL}/ws`);
        const stompClient = over(socket);
        stompClient.connect(
            {},
            () => onSocketConnected(stompClient),
            onSocketError
        )
        appContext.setSocket(stompClient)
    }

    function handleIncomingCall(data) {
        const state = JSON.parse(data.body.toLowerCase());
        setIsIncomingCall(state)
    }

    function onSocketConnected(stompClient) {
        const options = {
            accessToken: cookies['logged-in'],
        };

        stompClient.send("/app/connect", {}, JSON.stringify(options));
        stompClient.subscribe(`/user/search/complete`, handleSearchComplete)
        stompClient.subscribe(`/user/search/failed`, handleSearchError)
        stompClient.subscribe(`/user/call/incoming`, handleIncomingCall)
    }

    useEffect(() => {
        if (!appContext.socket && cookies['logged-in']) {
            initSocket()
        }
    }, [])

    return (
        <>
            <AnimatePresence>
                {
                    isIncomingCall && <CallModal
                        onAccept={acceptIncomingCall}
                        onReject={rejectIncomingCall}
                    />
                }
            </AnimatePresence>
            ...other page code...
        </>
    )
}

The initSocket function is called on page render inside the useEffect. I have tried wrapping the callback with a useCallback and binding it to the page and calling setIsIncomingCall inside an arrow function, but it didn't seem to help.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!