import React, { createContext, useEffect, useState } from "react";
import { io } from "socket.io-client";

export const SocketContext = createContext();

export const SocketProvider = ({ children }) => {
    const [socket, setSocket] = useState(null);

    useEffect(() => {

        const socket_obj = io(process.env.REACT_APP_BACKEND_URL, {
            withCredentials: true,
        });

        
        socket_obj.on("connect", () => {
            console.log("connected", socket_obj.id);
        })
        
        socket_obj.on("error", () => {
            console.log("socket error");
        })
        
        setSocket(socket_obj);
    }, [])


    return (
        <SocketContext.Provider value={socket}>
            {children}
        </SocketContext.Provider>
    );
}