Calling Array.slice() to a fetched array says that slice is not a function
This is what's causing the problem, from what I've understood is that the array is wrapped in a proxy object. I've tried accessing the _rawValue and it worked for a while but it shouldn't be used.
This is the error:
2 Replies
Hi @jonspe. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
The issue you're experiencing is related to how
useFetch
returns data in Nuxt 3. The data
returned by useFetch
is indeed wrapped in a reactive ref, which is why you're encountering the error when trying to call slice()
directly on posts
.
To resolve this issue, you need to access the actual array value inside the ref. Here's how you can modify your code to make it work:
The key change here is using posts.value
instead of just posts
. This accesses the actual array value inside the reactive ref.
Additionally, I've added a optional chaining operator (?.
) to safely handle the case where posts.value
might be null
or undefined
during initial rendering or if the fetch fails.
This approach is consistent with the Nuxt 3 documentation on using useFetch
. As mentioned in the Nuxt 3 Data Fetching documentation, the data returned by useFetch
is a ref, and you need to use .value
to access its contents.
If you're still encountering issues, make sure that the data returned from the API is indeed an array. You can check this by logging posts.value
to the console after the fetch completes.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@165887165736157185> Kapa.ai is still learning and improving, please let me know how I did by reacting below.