nuxt - nuxtServerInit 에서 사용자정보 로딩하기 > IT 기술백서

IT 기술백서

직접 알아내거나 검색하기 귀찮아서 모아 둔 것

JavaScript | nuxt - nuxtServerInit 에서 사용자정보 로딩하기

본문

페이지를 새로고침했을때 사용자정보를 불러오는 소스이다.

서버렌더링에서도 되어야 해서 nuxtServerInit 에 정의했다.

쿠키 플러그인은 ssr 에서도 사용할 수 있는 cookie-universal-nuxt 사용했다.

 

cookie-universal-nuxt 설치

[code]

yarn add cookie-universal-nuxt

[/code]

 

nuxt.config.js

[code]

modules: [

  'cookie-universal-nuxt',

  [ 'cookie-universal-nuxt', { alias: 'cookiz' } ],

],

[/code] 

 

/store/index.js

[code]

 

 

export const actions = {

  async nuxtServerInit(_, nuxtContext) {

    const accessToken = nuxtContext.$cookies.get('access_token')

    if (accessToken) {

      this.commit('auth/SET_TOKEN', accessToken) // 토큰저장 mutation

      await this.dispatch('auth/me') // 사용자 정보 불러오는 actions

    }

  },

}[/code]

 

※ this.dispatch('auth/me') 에서 Promise 를 리턴하기 때문에 await 로 호출했다.

await 를 하지 않으면 클라이언트에 적용이 되지 않는 현상이 발생한다.

댓글 0개

등록된 댓글이 없습니다.

Menu