Skip to content
On this page

useLoaderAndShowErrorByToast

This composable provides a convenient wrapper around useLoader and axios. It allows to show a error message with toast easily, with 0 configuration.

Overview

typescript
declare function useLoaderAndShowErrorByToast<T>(initialValue?: T): {
  data: Ref<T>;
  errors: Ref<{
    message: string;
    errors?: Record<string, string[]> | undefined;
  }>;
  loader: (callback: () => Promise<T>) => Promise<T>;
  loading: Ref<boolean>;
};

Params

  • initialData: Initial data state (by default, initial data is undefined, it's optional).

Return Values

  • data: The result of the asynchronous function that is passed in.
  • errors: an error object if the data fetching failed.
  • loader: a function that can be used to get and refresh the data returned by the handler function.
  • loading: a boolean indicating whether the data is still being fetched.

Example

html
<script setup lang="ts">
  import { useLoaderAndShowErrorByToast } from '@/composables';
  import axios from 'axios';

  const { data, errors, loader, loading } = useLoaderAndShowErrorByToast<{
    data: Record<string, unknown>[];
    errors?: Record<string, unknown>;
  }>();

  const getData = (params: { page: number }) => {
    // If an error occurs, a toast will be showed with an API error, or a default error.
    loader(
      // You can wrap this axios.get request for better scalability of your project
      () =>
        axios.get('/endpoint', {
          params,
        }),
    );
  };

  // on created hook
  getData({
    page: 1,
  });
</script>

Clinux UI - Released under the MIT License.