How to use pending and status in useFetch in Nuxt 3?
Asked Answered
S

2

6

I'm trying to use either pending or status with the useFetch composable in Nuxt 3 to disable a button and show a spinner when a POST request is pending like so:

const { pending, status, execute } = await useFetch("/notifyme", {
  immediate: false,
  baseURL: config.public.apiBase,
  method: "POST",
  body: {
    email: email.value,
  },
});

When using pending as below, the button is disabled and spinner is showing by default even before the request has been made:

<button
:disabled="pending"
type="submit">
Notify me
<ButtonSpinner v-show="pending" />
</button>

When using status as below, the button is not disabled and spinner is not showing by when the request is made:

<button
:disabled="status==='pending'"
type="submit">
Notify me
<ButtonSpinner v-show="status==='pending'" />
</button>

I'm confused as to how to use pending and status for useFetch and why both of them exist if they are so similar.

Supply answered 7/8, 2023 at 7:21 Comment(0)
S
1

I think there is an issue using pending and immediate: false together:

useFetch/useAsyncData: BUG: when immediate: false, then pending is true before call execute/refresh (must to be false) #19218

As I understand it, this is why the status feature was developed.

The reason I couldn't get status option to work with my code in my question was that this feature was added in a later version of Nuxt 3 that I didn't have installed yet.

I had to run nuxi upgrade to get the latest version of Nuxt 3 with the new status feature.

Supply answered 8/8, 2023 at 19:31 Comment(0)
S
0

In order for the pending and the status to work, you need to set server to false. See example

And, instead of using the useFetch, use useLazyFetch

Here an example.

const { data, pending, execute, status } = await useLazyFetch('https://catfact.ninja/fact', {
    server: false
})

Tested and it works. Stackblitz

I'm confused as to how to use pending and status for useFetch and why both of them exist if they are so similar.

No, they are not similar. The pending only return true or false. The pending will set to true if the API is still loading and become false when it is done. For the status, this will indicate the status of the data requested. It will output idle, pending, success, and error

Saccharase answered 7/8, 2023 at 8:12 Comment(2)
Thanks a lot for your answer. I see now that there are differences between pending and status.Supply
useLazyFetch is just a wrapper for useFetch with the option lazy: trueAccost

© 2022 - 2024 — McMap. All rights reserved.