Added openapi based api client
This commit is contained in:
59
apps/frontend/app/providers/ApiProvider.tsx
Normal file
59
apps/frontend/app/providers/ApiProvider.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import { createContext, use, useContext, type PropsWithChildren } from 'react';
|
||||
import { createTanstackApi, createApi } from '../lib/api';
|
||||
import axios from 'axios';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
|
||||
type ApiProviderProps = PropsWithChildren<{}>;
|
||||
type ApiContextType = {
|
||||
apiClient: ReturnType<typeof createApi>;
|
||||
tanstackApiClient: ReturnType<typeof createTanstackApi>;
|
||||
};
|
||||
|
||||
const ApiContext = createContext<ApiContextType | null>(null);
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
/**
|
||||
* Example usage:
|
||||
* ```ts
|
||||
* const { tanstackApiClient } = useApi();
|
||||
* const { queryOptions } = tanstackApiClient.get('/api/health/info');
|
||||
* useQuery({
|
||||
* ...queryOptions,
|
||||
* queryFn: async (...args) => {
|
||||
* console.log('Fetching health info...');
|
||||
* const data = await queryOptions.queryFn!(...args);
|
||||
* console.log('Health Info:', data);
|
||||
* return data;
|
||||
* },
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
|
||||
export const ApiProvider: React.FC<ApiProviderProps> = ({ children }) => {
|
||||
const axiosInstance = axios.create({
|
||||
withCredentials: true,
|
||||
});
|
||||
const apiClient = createApi(axiosInstance);
|
||||
const tanstackApiClient = createTanstackApi(axiosInstance);
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ApiContext
|
||||
value={{
|
||||
apiClient,
|
||||
tanstackApiClient,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</ApiContext>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
|
||||
export function useApi() {
|
||||
const context = use(ApiContext);
|
||||
if (!context) {
|
||||
throw new Error('useApi must be used within an ApiProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
Reference in New Issue
Block a user