...

/

Handling API States

Handling API States

Learn how to handle API states by using different properties while performing asynchronous operations.

The isLoading property

We might want to handle different states when performing asynchronous operations. For example, when we fetch data from a server, we might want to display a loader or skeleton content to inform a user that something is happening.

This could be achieved by adding an isLoading property, as shown below.

<p v-if="isLoading">Loading data</p>
<div v-else>
<img :src="dog" alt="Dog image" />
</div>
Template for "isLoading" property

This means that if isLoading is set to true, then display the Loading data text. Otherwise, show the dog image.

The isError property

What about error handling? We could add another property called isError and also use try/catch for error handling.

<p v-if="isLoading">Loading data</p>
<p v-else-if="isError">
There was a problem.
</p>
<div v-else>
<img :src="dog" alt="Dog image" />
</div>
Template for "isError" property

Run the code below to see the live example of isLoading and isError while fetching the dog image from API in the Companion App.

Note: The code below may take a while to run. When the server starts, go to the app URL to see the output.

<template>
  <div id="app" class="bg-gray-100">
    <GlobalSpinnerProvider>
      <Layout>
        <div id="nav"></div>
        <router-view />
      </Layout>
    </GlobalSpinnerProvider>
  </div>
</template>
<script>
import Layout from '@/layout/Layout'
import GlobalSpinnerProvider from '@/components/common/spinner/GlobalSpinnerProvider.vue'
import { setUser } from '@/services/stateful/userService'

/**
 * Set user name for Managing State / Stateful Services example
 */
setUser({
  name: 'William',
})

export default {
  components: {
    Layout,
    GlobalSpinnerProvider,
  },
}
</script>
<style lang="scss" src="@/styles/index.scss"></style>
Implement the API status handling
  • A new Vue app is created in the main.js file that renders the App component.
  • The ApiStatusExample.vue component renders a heading and the NaiveIsLoading component.
  • The NaiveIsLoading component showcases how to handle loading and error API status by having a stateful value for each, isLoading and isError. When isLoading is set to true, the Loading data message is displayed. When isError is true, an error message is displayed. Otherwise, an image of a dog is displayed.

This works fine, but we need two reactive values for just one API action. Sometimes, components have a few API actions, and we’d need 2 x number of action properties for each, for example, isLoadingData, isLoadingDataError, ...