Created
December 9, 2023 15:25
-
-
Save kleva-j/d344f1810a21b2e336a891bd63d02adb to your computer and use it in GitHub Desktop.
Handle api requests in React.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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