Merge branch 'develop' into feat/user-profile
This commit is contained in:
@@ -1,24 +1,46 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { type ApiResponse } from '@/types/apiResponse';
|
||||
|
||||
type ApiFunction<T, P> = (params?: P) => Promise<{ data: T }>;
|
||||
// Define options for the hook
|
||||
interface UseApiOptions {
|
||||
// If true, the API call will be executed immediately on mount
|
||||
immediate?: boolean;
|
||||
}
|
||||
|
||||
export function useManualApi<T, P>(apiFunction: ApiFunction<T, P>) {
|
||||
export function useApi<T extends ApiResponse, P extends any[]>(
|
||||
apiFunction: (...args: P) => Promise<{ data: T }>,
|
||||
options: UseApiOptions = {},
|
||||
) {
|
||||
const [data, setData] = useState<T | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<unknown>(null);
|
||||
|
||||
const execute = useCallback(
|
||||
async (...args: P) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const execute = async (params?: P) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await apiFunction(params);
|
||||
setData(response.data);
|
||||
} catch (err) {
|
||||
setError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
try {
|
||||
const response = await apiFunction(...args);
|
||||
|
||||
setData(response.data);
|
||||
} catch (err) {
|
||||
// TODO: can handle some common errors here, 400 and 500 errors
|
||||
setError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[apiFunction],
|
||||
);
|
||||
|
||||
// If the 'immediate' option is true, execute the function on mount
|
||||
useEffect(() => {
|
||||
if (options.immediate) {
|
||||
// We pass undefined as params for the initial call.
|
||||
execute(...(undefined as unknown as P));
|
||||
}
|
||||
};
|
||||
}, [execute, options.immediate]);
|
||||
|
||||
return { data, loading, error, execute };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user