Skip to content

Instantly share code, notes, and snippets.

@stefann01
Created August 10, 2022 21:51
Show Gist options
  • Save stefann01/c16ccccd12a665f5cd59a00bbea66372 to your computer and use it in GitHub Desktop.
Save stefann01/c16ccccd12a665f5cd59a00bbea66372 to your computer and use it in GitHub Desktop.
import React, { useState, useCallback } from "react";
export const usePostQuery = <BodyData, ResponseData>(
query: string,
headers?: HeadersInit
): {
post: (data: BodyData) => Promise<void>;
loading: boolean;
error: string | null;
responseData: ResponseData | null;
} => {
const [responseData, setResponseData] = useState<ResponseData | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
const post = useCallback(
async (data: BodyData) => {
try {
setLoading(true);
const response = await fetch(query, {
method: "POST",
body: JSON.stringify(data),
headers,
});
const json = await response.json();
setResponseData(json);
setLoading(false);
} catch (error: any) {
setError(error.message);
setLoading(false);
}
},
[headers, query]
);
return { responseData, loading, error, post };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment