Skip to content

Commit

Permalink
chore: fix websockets
Browse files Browse the repository at this point in the history
  • Loading branch information
LucSPI committed May 20, 2023
1 parent 42fc171 commit 46b21b4
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 36 deletions.
16 changes: 2 additions & 14 deletions src/providers/SocketProvider/context.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,7 @@
import { createContext, useContext } from 'react';
import { Socket, io } from 'socket.io-client';
import { Socket } from 'socket.io-client';

const URL = process.env.NODE_ENV === 'production' ? '' : 'http://localhost:3000';

export const socket = io(URL, {
transports: ['websocket'],
autoConnect: true,
path: '/ws',
withCredentials: true,
auth: {
token: `Bearer ${localStorage.getItem('token')}`,
},
});

export const SocketContext = createContext<Socket | null>(socket);
export const SocketContext = createContext<Socket | null>(null);

export const useSocket = () => {
const socket = useContext(SocketContext);
Expand Down
32 changes: 10 additions & 22 deletions src/providers/SocketProvider/provider.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,15 @@
import { PropsWithChildren, useEffect, useRef } from 'react';
import { PropsWithChildren } from 'react';
import { io } from 'socket.io-client';
import { SocketContext } from './context';

const URL = process.env.NODE_ENV === 'production' ? window.location : 'http://localhost:3000';
const socket = io(URL, {
autoConnect: true,
path: '/ws',
withCredentials: true,
auth: {
token: `Bearer ${localStorage.getItem('token')}`,
},
});
export default function SocketProvider({ children }: PropsWithChildren) {
const socket = useRef(
io({
autoConnect: true,
path: '/ws',
withCredentials: true,
auth: {
token: `Bearer ${localStorage.getItem('token')}`,
},
}),
).current;

useEffect(() => {
socket.on('connect', () => {
// eslint-disable-next-line no-console
console.log(socket.id); // x8WIv7-mJelg7on_ALbx
// eslint-disable-next-line no-console
console.log(socket.recovered); // true
});
return () => {};
});
return <SocketContext.Provider value={socket}>{children}</SocketContext.Provider>;
}

0 comments on commit 46b21b4

Please sign in to comment.