How to use nuxtjs3 useFetch pick parameter for arrays or make a deep pick?

47 views Asked by At

In my nuxtjs3 project, I would like to pick the data I get from an API.

In this case, I use jsonPlaceholder. I have no problem when it comes to picking data from an object:

const { data: useFetchOnly } = await useFetch('https://jsonplaceholder.typicode.com/todos/1', {
    pick: ['title']
  })

console.log({useFetchOnly})

but when I try to pick data from an array of objects, I do not know, how to do it. I tried with the following, but without success:

const { data: useFetchArray } = await useFetch('https://jsonplaceholder.typicode.com/todos/', {
    pick: ['title']
  })

console.log({useFetchArray})

Any ideas on how to solve it?

The documentation, that I found is not helping in this case: LINK

1

There are 1 answers

1
its_shakh On BEST ANSWER

Actually, you need transform instead of pick:

If you need more control or map over several objects, you can use the transform function to alter the result of the query.

So your final code should look like this:

const { data} = await useFetch('url', {
    transform: (r) => r.map(({ title }) => title);
})

Also keep in mind that:

Both pick and transform don't prevent the unwanted data from being fetched initially. But they will prevent unwanted data from being added to the payload transferred from server to client.

You can learn more in docs.