Skip to content

Commit

Permalink
used atom for client
Browse files Browse the repository at this point in the history
  • Loading branch information
sphinxrave committed Oct 15, 2023
1 parent 8a1011c commit 4e5cecb
Showing 1 changed file with 29 additions and 27 deletions.
56 changes: 29 additions & 27 deletions packages/react/src/hooks/useClient.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,35 @@
import { tokenAtom } from "@/store/auth";
import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { useAtomValue } from "jotai";
import { useCallback } from "react";
import { atom, useAtomValue } from "jotai";

const axiosInstance = axios.create();

export const clientAtom = atom((get) => {
const token = get(tokenAtom);

const r = function <T>(
url: string,
config?: AxiosRequestConfig
): Promise<AxiosResponse<T>> {

const configWithUser: AxiosRequestConfig = {
baseURL: `${window.location.protocol}//${window.location.host}/api/v2`,
...config,
headers: {
...config?.headers,
...token && { Authorization: `Bearer ${token}`, },
},
paramsSerializer: (params) => new URLSearchParams(params).toString(),
};

return axiosInstance(url, configWithUser);
}

r.loggedIn = !!token

return r;
});

export function useClient() {
const token = useAtomValue(tokenAtom);

const AxiosInstance = useCallback(
function <T>(
url: string,
config?: AxiosRequestConfig,
): Promise<AxiosResponse<T>> {
const configWithUser: AxiosRequestConfig = {
baseURL: `${window.location.protocol}//${window.location.host}/api/v2`,
...config,
headers: {
...config?.headers,
Authorization: `Bearer ${token}`,
},
paramsSerializer: {
serialize: (params) => new URLSearchParams(params).toString(),
},
};
return axiosInstance(url, configWithUser);
},
[token],
);

return AxiosInstance;
}
return useAtomValue(clientAtom)
}

0 comments on commit 4e5cecb

Please sign in to comment.