asynchronousnuxt.jscontentfulnuxt3.js

Nuxt3 loading Contentful data


In Nuxt 2 project I used Contentful for CMS data, it provides a client which you configure using method const api = createClient(api_token, ...) and then can do something like api.getEntries(page_type, ...) So in this case URL and other things are obfuscated, I can not use https://nuxt.com/docs/api/composables/use-fetch that is useful when app talks directly to some REST api.

How, in Nuxt 3, do I fetch async data via 3rd party plugin/sdk that exposes "get functions"? If I leave it just on the root of <script setup>, data is loaded both on the server and then again on the client, so it seems wrong to me as it should be wrapped in some lifecycle method, like it was in Nuxt 2.


Solution

  • According to the official Nuxt documentation, if you want to fetch content using the SDK, you will have to use the useAsyncData function.

    Here's the excerpt from the docs: There are some cases when using the useFetch composable is not appropriate, for example when a CMS or a third-party provide their own query layer. In this case, you can use useAsyncData to wrap your calls and still keep the benefits provided by the composable.