Nuxt 공부 - fetch Hook

이윤우·2022년 7월 27일
0

Nuxt

목록 보기
7/8
post-thumbnail

fetch Hook

fetch 훅은 데이터를 비동기적으로 가져오기 위한 것입니다. 경로를 렌더링할 때 서버측에서 호출되고 탐색할 때 클라이언트 측에서 호출됩니다.

  • $fetchState.pending: 클라이언트 측에서 fetch를 호출했을 때 placeholder를 보여줄 수 있다.
  • $fetchState.error: error 메세지를 보여줄 수 있다.
  • $fetchState.timestamp: 마지막 fetch의 시간. keep-alive로 캐싱할 때 유용하다.
<button @click="$fetch">Refresh</button>

또는

export default {
  methods: {
    refresh() {
      this.$fetch()
    }
  }
}

activated hook과 함께 쓰는 fetch hook

  • activated hook과 조합하여 30초 동안 fetch를 캐시할 수 있다.
<template> ... </template>

<script>
  export default {
    data() {
      return {
        posts: []
      }
    },
    activated() {
      // Call fetch again if last fetch more than 30 sec ago
      if (this.$fetchState.timestamp <= Date.now() - 30000) {
        this.$fetch()
      }
    },
    async fetch() {
      this.posts = await fetch('https://api.nuxtjs.dev/posts').then(res =>
        res.json()
      )
    }
  }
</script>
                                             

0개의 댓글