useLoader
This composable provides a convenient wrapper to get access to data, that resolves asynchronously with axios.
It automatically generates a key based on URL and fetch options, provides type hints for request url based on server routes, and infers API response type.
Overview
typescript
interface LoaderError {
message: string;
errors?: Record<string, string[]>;
}
declare function useLoader<T>(
initialData?: T,
success?: (res: T) => void,
err?: (error: Error, errors: Ref<LoaderError>) => void,
): {
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). - success: Success callback after finish the request (it's optional).
- error: Error callback after finish the request (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 { useLoader } from '@/composables';
import axios from 'axios';
const { data, errors, loader, loading } = useLoader<{
data: Record<string, unknown>[];
errors?: Record<string, unknown>;
}>();
const getData = (params: { page: number }) => {
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>