import React, { createContext, useMemo, useContext } from "react";
import { io } from "socket.io-client";
import { BACKEND_URL } from "../constants";

const SocketContext = createContext(null);

export const useSocket = () => {
  const socket = useContext(SocketContext);
  return socket;
};

export const SocketProvider = (props) => {
  const socket = useMemo(
    () =>
      io(`${BACKEND_URL}`, {
        withCredentials: true,
      }),
    []
  );

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