Created
August 10, 2022 21:51
-
-
Save stefann01/c16ccccd12a665f5cd59a00bbea66372 to your computer and use it in GitHub Desktop.
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 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