본문 바로가기

FE/Next

Router 사용시 socket 연결이 되지 않는 현상

window.location.href 쓸 때는 잘 되는데,

Router.push 쓰니까 웹소켓이 연결되지 않는다.

 

// socket.js

const socket = io.connet({});

export default socket

// somePage.jsx

import socket

useEffect(() => {
	if (asPath.indexOf('url') !== -1) {
    	if (socket) { 
        	socket.on{
            	socket.emit{
                	socket.on{
                    	// ajax function, rerender function here
                    }
                }
            }
        }
    }
}, [asPath]) // asPath = useRouter().asPath

 

window.location.href 로 이 코드를 동작시키면 페이지 이동할 때마다 전체 코드를 실행하지만

Router 를 사용하게 되면 useEffect 안쪽의 코드만이 실행되어 

socket 이 누락된다.

 

그래서 다음과 같은 동적 소켓을 만들어 해결했다.

 

//socket.js

const dynamicSocket = () => ( // return socket by functional component
	io.connect({})
)

 

 

'FE > Next' 카테고리의 다른 글

Next (12+) + twin.macro (tailwindCSS) setting  (0) 2022.03.14
NextJS meta (SEO) 태그가 중복되어 생기는 현상  (3) 2021.04.08