useLoaderAndShowSuccessAndErrorByToast
This composable provides a convenient wrapper around useLoader and axios. It allows to show a success and error message with toast easily, with 0 configuration.
Overview
typescript
declare function useLoaderAndShowSuccessAndErrorByToast<T>(
initialValue?: T,
successType?: Ref<'create' | 'edit' | 'delete'>,
): {
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). - successType: The main success type to help the success message (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
handlerfunction. - loading: a boolean indicating whether the data is still being fetched.
Example
html
<script setup lang="ts">
import { useLoaderAndShowSuccessAndErrorByToast } from '@/composables';
import axios from 'axios';
const { data, errors, loader, loading } =
useLoaderAndShowSuccessAndErrorByToast<{
data: Record<string, unknown>[];
errors?: Record<string, unknown>;
}>();
const getUser = (userId: number) => {
// If an error occurs, a toast will be showed with an API success or error, or a default success or error.
loader(
// You can wrap this axios.get request for better scalability of your project
() => axios.get('/endpoint/:id'.replace(':id', userId)),
);
};
// on created hook
getUser(98);
</script>