[FE skill] SSR window 대신 react query 를 사용해서

손두희(SONDOOHEE)·2023년 4월 22일
0

Problem

Next JS 로 프로젝트를 진행 중 URL의 params 을 가져와서 데이터의 type이나 year을 가져오는데 새로고침 시 windows를 가져오지 못하는 경우가 발생했다.

아마 SSR 이기 때문에 Server에서 DOM 을 그리는 중 windows 라는 변수를 가져오지 못하는 상황인거 같다...

Solution

new URLSearchParams(window.location.search) 을 통해서 파라미터를 가져왔는데 이걸 react.query 를 통해 해결해야겠다

const params = new URLSearchParams(window.location.search) 로 parameter 값을 가져온것을
const parmas = react.query 로 대체했다.

그 후

router.replace({
  pathname: window.location.pathname,
  query:params.toString()
})

router.replace({
  pathname: router.pathname,
  query:{...params, type:item.id}
})

로 변경해야할 param 만 고쳐서 진행하니
reload를 해도 에러 없이 잘 작동했다.

profile
작업을 기록하는 개발자

0개의 댓글