docs: add a brief description of transform/pick (#20186)

This commit is contained in:
David Kurek 2023-04-13 12:13:42 +02:00 committed by GitHub
parent b011d3d76f
commit 295473f924
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -127,6 +127,57 @@ watch(count, (newCount) => {
</script> </script>
``` ```
## Transforming Data
If for some reason you are not satisfied with how the requested data is structured, you may want to use the `transform` option from `useFetch` or `useAsyncData` to alter the data by using a function to perform the necessary transformation after your request has been resolved.
We very much recommend that you remove any data or properties that you do not need, in order to reduce your page's payload size - see the [Minimize Payload](#minimize-payload) section.
### Example
```vue
<script setup>
const { data: users } = await useAsyncData(
"users",
() => $fetch('/api/users'),
{
transform: (users) =>
users.map((user) => ({
id: user.id,
fullName: `${user.firstName} ${user.surname}`,
})),
}
);
</script>
<template>
<div>
<ul>
<li v-for="user in users" :key="user.id">
{{ user.fullName }}
</li>
</ul>
</div>
</template>
```
If you are dealing with a complex data structure and you are only interested in a few properties, simply make use of the `pick` option to only pick specific properties you are interested in.
```vue
<script setup>
const { data: user } = await useFetch('/api/users/123', {
pick: ["firstName", "surname"],
});
const userFullName = computed(
() => `${user.value.firstName} ${user.value.surname}`
);
</script>
<template>
<div>Hi {{ userFullName }}</div>
</template>
```
## Refreshing Data ## Refreshing Data
Sometimes throughout the course of your user's page visit, you may need to refresh the data loaded from the API. This can happen if the user chooses to paginate, filter results, search, etc. Sometimes throughout the course of your user's page visit, you may need to refresh the data loaded from the API. This can happen if the user chooses to paginate, filter results, search, etc.