Simple react http client wrapper for axios and @tanstack/react-query
npm install @dhoniaridho/react-ohttpThis package provides a set of React hooks for making HTTP requests.
You can install the package using npm or yarn:
``bash`
npm install react-ohttp
or
`bash`
pnpm add react-ohttp
`jsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App.tsx";
import { HttpProvider } from "react-ohttp";
import { QueryClient } from "@tanstack/react-query";
const queryClient = new QueryClient();
createRoot(document.getElementById("root")!).render(
baseURL="https://jsonplaceholder.typicode.com/"
beforeRequest={(config) => {
console.log(config);
config.headers.Authorization = Bearer ${Math.random()};
return config;
}}
onFulfill={(response) => {
console.log(response);
return response;
}}
onReject={(error) => {
console.log(error);
throw error;
}}
>
);
`
The useHttp hook is used to make HTTP requests with various methods.
`jsx
import React from "react";
import { useHttp } from "react-ohttp";
const ExampleComponent = () => {
const { data, error, isLoading } = useHttp(
"https://api.example.com/data/{id}",
{
method: "GET",
searchParams: { key: "value" },
vars: {
id: "123",
},
}
);
if (isLoading) return
Loading...
;Error: {error.message}
; return (
{JSON.stringify(data, null, 2)}export default ExampleComponent;
`
The useHttpMutation hook is used to make HTTP requests with mutation methods like POST, PUT, DELETE, etc.
`jsx
import React from "react";
import { useHttpMutation } from "@ohttp/react-http";
const ExampleComponent = () => {
const { mutate, isPending } = useHttpMutation("todo", { method: "POST" });
const onCreate = (data: object) => {
mutate(
{
body: data,
},
{
onError: (err) => {
alert(err.data.message);
},
}
);
};
if (isLoading) return
Loading...
;Error: {error.message}
; return (
export default ExampleComponent;
`
#### useHttp
- url (string): The URL to make the HTTP request to.options
- (object): Configuration options for the request.method
- (string): The HTTP method to use (default is 'GET').params
- (object): Query parameters to include in the request.httpOptions
- (object): Additional Axios request configuration options.queryOptions
- (object): React Query options.data
- Returns an object with the following properties:
- : The response data.error
- : Any error that occurred.isLoading
- : Whether the request is in progress.
#### useHttpMutation
- url (string): The URL to make the HTTP request to.options
- (object): Configuration options for the request.method
- (string): The HTTP method to use.httpOptions
- (object): Additional Axios request configuration options.queryOptions
- (object): React Query options.mutate
- Returns an object with the following properties:
- : A function to trigger the mutation.isLoading
- : Whether the request is in progress.isError
- : Whether an error occurred.error`: The error that occurred.
-