How to use the @nuxtjs/axios module with Nuxt3?
Asked Answered
P

2

5

I have this code to get API data from https://fakestoreapi.com/products/

<template>
<div>


</div>
</template>


  <script>  
  definePageMeta({
    layout: "products"
  })

export default {
  data () {
    return {
      data: '',
    }
  },
  async fetch() {
    const res = await this.$axios.get('https://fakestoreapi.com/products/')
    console.log(res.data)
  },
}
</script>

I have installed axios and in nuxt.config.ts I have:

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({

    app: {
        head: {
            title: 'Nuxt',
            meta: [
                { name: 'description', content: 'Everything about - Nuxt-3'}
            ],
            link: [
                {rel: 'stylesheet', href: 'https://fonts.googleapis.com/icon?family=Material+Icons' }
            ]
        }
    },
    runtimeConfig: {
        currencyKey: process.env.CURRENCY_API_KEY
    },
    modules: [
        "@nuxtjs/tailwindcss",
    ],
    buildModules: [
        "@nuxtjs/axios"
    ],
    axios: {
      baseURL: '/',
    }
})

I have the following in my console

is an experimental feature and its API will likely change.

I am not getting API data in the console.

Precondition answered 4/12, 2022 at 16:15 Comment(2)
Build Modules are deprecated as far as I know, move it to regular modules section. Also, the suspense thing is a warning should not cause any error so far. Set the value to your data state and check your Vue devtools to see if something is wrong. Otherwise, please provide a minimal reproducible example or a public Github repo. – Pritchard
@Pritchard github.com/AzizxonZufarov/newsnuxt/blob/main/pages/products/… Please visit github repo – Precondition
P
9

As told on this page, we don't use the @nuxtjs/axios module anymore with Nuxt3 but rather ohmyfetch, which is now baked-in directly in the core of the framework through $axios as writted here.

Hence, your config file should look like this

export default defineNuxtConfig({
  app: {
    head: {
      title: 'Nuxt Dojo',
      meta: [
        { name: 'description', content: 'Everything about - Nuxt-3' }
      ],
      link: [
        { rel: 'stylesheet', href: 'https://fonts.googleapis.com/icon?family=Material+Icons' }
      ]
    }
  },
  runtimeConfig: {
    currencyKey: process.env.CURRENCY_API_KEY
  },
  modules: [
    "@nuxtjs/tailwindcss"
  ],
})

And the given /pages/products/index.vue can be like that

<template>
  <div>
    <p v-for="user in users" :key="user.id">ID: {{ user.id }} πŸ‘‰ {{ user.name }}</p>
  </div>
</template>


<script>
definePageMeta({
  layout: "products"
})

export default {
  data () {
    return {
      users: '',
    }
  },
  async mounted() {
    this.users = await $fetch('https://jsonplaceholder.typicode.com/users')
  },
}
</script>

This is how it looks at the end (with a successful HTTP request in the network tab)

enter image description here


As a confirmation, we can see that the module is indeed not supported (and will not be) by Nuxt3 on the modules page.

The Suspense error is detailed in the official documentation

<Suspense> is an experimental feature. It is not guaranteed to reach stable status and the API may change before it does.

It may seem scary but you can totally use the API as per se and since it's a warning and not an error, it's totally fine!

Pritchard answered 4/12, 2022 at 17:37 Comment(2)
That's great. Thanks but one question how can I do : limit the data count, order by desc/asc, sortby date with $fetch? When I use axios it has built-in features, but does $fetch has this kinda features? if yes, please give an example or link for reading. Thanks! – Precondition
@AzizxonZufarov Nuxt3 have plenty of helpers like useAsyncFetch with various options that could help you with that (based on ohmyfetch). Also, I never saw that axios could do such things since it's not its purpose. You can always create a composable with the desired behavior and some sort/fliter/map/etc array methods of yours if Nuxt3 doesn't have enough already. – Pritchard
T
1

With nuxtjs3 I prefer to use a composable, it is flexible and self-imported throughout the app.

composables/useApi.ts

import axios from 'axios'

export const useApi = () => {
  const baseURL = 'https://BASE_URL.com'
  const storeUser = useStoreUser()

  return axios.create({
    baseURL,
    headers: {
      Authorization: `Bearer ${storeUser.token}`
    }
  })
}

Now what I do is simply

<script lang="ts" setup>
const api = useApi()

const { data } = await api({
    method: 'get',
    url: '/auth/login'
})
</script>
Tardigrade answered 2/10, 2023 at 23:58 Comment(4)
You can probably skip axios in 2023, Nuxt has better defaults baked-in. – Pritchard
It's not better. You can't even change the default base_url – Anett
@Anett You don't have to now with server APIs in Nuxt 3. – Cassycast
Does anyone worked with with withCredentials: true option in axios? how to use it with fetch? inside options 'credentials: 'include' seems not working – Acquirement

© 2022 - 2024 β€” McMap. All rights reserved.