Skip to content

Instantly share code, notes, and snippets.

@kleva-j
Created December 9, 2023 15:25
Show Gist options
  • Save kleva-j/d344f1810a21b2e336a891bd63d02adb to your computer and use it in GitHub Desktop.
Save kleva-j/d344f1810a21b2e336a891bd63d02adb to your computer and use it in GitHub Desktop.
Handle api requests in React.
import { AxiosError, AxiosResponse } from "axios";
type BaseRequest<T, V> = (params?: T) => Promise<AxiosResponse<V>>;
type SuccessResponse<V> = {
code: "success";
data: V;
};
type ErrorResponse<E = AxiosError> = {
code: "error";
error: E;
};
type BaseResponse<V, E> = Promise<SuccessResponse<V> | ErrorResponse<E>>;
export const requestHandler =
<T, V, E = AxiosError>(request: BaseRequest<T, V>) =>
async (params?: T): BaseResponse<V, E> => {
try {
const response = await request(params);
return { code: "success", data: response.data };
} catch (e) {
return { code: "error", error: e as E };
}
};
import axios from "axios";
import { requestHandler } from "./requestHandler";
interface User {
id: number;
name: string;
}
interface GetUsersParams {
limit?: number;
page?: number;
}
export const getUsers = requestHandler<GetUsersParams, User[]>((params) =>
axios.get("/api/users", { params })
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment