Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda