Async function for `useAsyncData` key param
Hello, I have a composable that returns
useAsyncData
and want to do something like this
In other words, I want to set the key to some value fetched async, but if I make the composable async, the return type will always need to be a promise, which is not equivilent to useAsyncData
's type signature:
Can anyone think of a clean way to do this?2 Replies
Hi @rd. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
Based on the knowledge sources provided, there isn't a direct way to use an asynchronous function for the
key
parameter of useAsyncData
while maintaining its return type. However, I can suggest a potential workaround that might help you achieve a similar result.
Instead of trying to make the key
parameter asynchronous, you could use a combination of ref
and watch
to update the key after it's fetched. Here's an approach you could consider:
In this approach:
1. We create a ref
with an initial key value.
2. We use this ref
as the key for useAsyncData
.
3. We add the keyRef
to the watch
option of useAsyncData
. This ensures that when the key changes, the data will be refetched.
4. After setting up useAsyncData
, we fetch the actual key asynchronously and update the keyRef
when it's received.
This method allows you to keep the return type of useAsyncData
while still fetching the key asynchronously. The data will be refetched once the actual key is received and set.
Note that this approach has some limitations:
- The initial fetch will happen with the initial key value.
- There will be a second fetch when the actual key is received.
If these limitations are acceptable for your use case, this could be a viable solution.
For more information on the watch
option and how it can be used with useAsyncData
, you can refer to the Nuxt documentation on Data Fetching.
Remember that this is a workaround and not a direct solution to using an async function for the key parameter. The Nuxt team is continuously improving the framework, so it's worth keeping an eye on future updates that might provide more direct solutions for this use case.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@336916275705937921> Kapa.ai is still learning and improving, please let me know how I did by reacting below.