---
url: https://vue-json-excel3.netlify.app/using-callbacks-examples.md
description: >-
  Format exported values with field callbacks, and fetch data on demand with
  loading hooks.
---

# Using Callbacks

## Field callbacks

When a field has a `callback`, there are three ways to choose what it receives:

* **`field: 'path.to.nested.property'`** — a specific nested value.
* **`field: 'path.to.nested.object'`** — a whole nested object.
* **No `field`** — the whole row.

```vue
<script setup>
import JsonExcel from 'vue-json-excel3'

const jsonData = [
  { name: 'Tony Peña', city: 'New York', phone: { mobile: '1-541-754-3010', landline: '(541) 754-3010' } },
  { name: 'Thessaloniki', city: 'Athens', phone: { mobile: '+1 855 275 5071', landline: '(2741) 2621-244' } },
]

const jsonFields = {
  'Complete name': 'name',
  City: 'city',
  // 1. A nested value
  Landline: {
    field: 'phone.landline',
    callback: (value) => `Landline Phone - ${value}`,
  },
  // 2. A nested object
  Phones: {
    field: 'phone',
    callback: (phone) => `${phone.mobile} / ${phone.landline}`,
  },
  // 3. The whole row (no field)
  Summary: {
    callback: (row) => `${row.name} lives in ${row.city}`,
  },
}
</script>

<template>
  <JsonExcel class="btn" :data="jsonData" :fields="jsonFields" type="xlsx" name="callbacks.xlsx">
    Download with callbacks
  </JsonExcel>
</template>
```

## Fetch data on demand

If the data comes from a server, use the `fetch` prop instead of `data`. The function runs when the user clicks and must return the rows to export. Pair it with `before-generate` and `before-finish` to show a loading state.

::: warning
`fetch` is only used when no `data` prop is set.
:::

```vue
<script setup>
import { ref } from 'vue'
import JsonExcel from 'vue-json-excel3'

const loading = ref(false)

const jsonFields = {
  'Holiday name': 'name',
  Date: 'date',
}

// Runs when the user clicks — replace with your own API call.
async function fetchData() {
  await new Promise((resolve) => setTimeout(resolve, 1200))
  return [
    { name: 'Labor Day', date: '2017-09-04' },
    { name: 'Patriot Day', date: '2017-09-11' },
    { name: 'Constitution Day', date: '2017-09-17' },
  ]
}
</script>

<template>
  <JsonExcel
    class="btn"
    :fetch="fetchData"
    :fields="jsonFields"
    :before-generate="() => (loading = true)"
    :before-finish="() => (loading = false)"
    type="xlsx"
    name="holidays.xlsx"
  >
    {{ loading ? 'Fetching data…' : 'Fetch & download' }}
  </JsonExcel>
</template>
```

A real API call looks like this:

```js
async function fetchData() {
  const response = await fetch('/api/holidays?country=US&year=2017')
  const { holidays } = await response.json()
  return holidays
}
```
