'useState is undefined on component unmount

When the component is unmounted connectionId.stop(); produces TypeError: Cannot read properties of undefined (reading 'stop'), though connection.stop(); stops the connection. I suspect that when the component unmounts the useState is no longer there but the var connection is still there just before it unmounts.

I mean, if I call connectionId.stop(); from a child component of this component, it stops the connection.

I could just use var connection but that doesn't seem the ReactJs way to do things?

const [connectionId, setConnectionId] = useState();

useEffect(() => {

    var connection;

    const fetchJoinedMessage = async () => {
        try {
            connection = new HubConnectionBuilder()
                .withUrl("https://localhost:4581/chat")
                .configureLogging(LogLevel.Information)
                .build();

            await connection.start();
            setConnectionId(connection)

        } catch (err) {
            console.log(err.message)
        }
    }

    fetchJoinedMessage()

     return () => {
         console.log("Component unmounted")

         console.log(connection) // displays the connection
         console.log(connectionId) // connectionId undefined
         //connection.stop(); // connection is stopped
         connectionId.stop(); // connection not stopped
     }

}, [])

Thank you



Solution 1:[1]

If you only need your connectionId on unmount to stop it, then declaring it as you did with connection is ok, consider using let instead of var tho

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bogdan Sarkisyan