I’m using this code to connect to Socket:
import { createContext, useContext, useEffect, useRef, useState } from "react";
import client, { Socket } from "socket.io-client";
import { env } from "../constants/env";
import { useAuth } from "./AuthContext";
interface SocketContextType {
socket: Socket | null;
}
const SocketContext = createContext({ socket: null } as SocketContextType);
const socketConfig = {
jsonp: false,
autoConnect: false,
secure:true,
// path: env.SOCKET_PATH,
transports: ["websocket"],
};
type Props = {
children: React.ReactNode;
};
export default function SocketProvider({ children }: Props) {
const { user } = useAuth();
const socket = useRef(client('https://socket-dev.com', socketConfig));
useEffect(() => {
if (!user) return;
socket.current.auth = {
id_instituicao: user?.id_instituicao,
usuario: user?.user,
ambiente: "app",
};
console.log(socket.current)
socket.current.connect();
socket.current.on("connect", () => {
console.log("Conectado");
});
socket.current.on("connect_error", (error) => {
console.log("Erro de conexão:", error);
});
socket.current.on("disconnect", (msg) => {
console.log("SocketIO: Disconnect", msg);
socket.current = client('https://socket-dev.com', socketConfig);
});
return () => {
if (socket && socket.current) {
socket?.current?.removeAllListeners();
socket?.current?.close();
}
};
}, []);
return (
<SocketContext.Provider value={{ socket: socket.current }}>
{children}
</SocketContext.Provider>
);
}
const useSocket = () => useContext(SocketContext);
export { useSocket };
But I’m get this error code: Unable to resolve host "socket-dev.com": No address associated with hostname
const socketConfig = {
jsonp: false,
autoConnect: false,
secure:true,
path: env.SOCKET_PATH,
transports: ["websocket"],
};
...
const socket = useRef(client(env.STORAGE_URL, socketConfig));
I was trying to connect with the socket on my node server, like this:
But received: Unable to resolve host "undefined": No address associated with hostname
And if I entered the URL directly, the app would crash with the message: Invalid URL PORT: 5000
I have one electron app and one web app connected to my local socket normally
I have the permission set on my AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET"/>
and i’m using “socket.io-client”: “^4.7.5”
Willian Louza is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.