useGetImg Hook
Introduction
The useGetImg
custom hook facilitates the process of fetching images from the "GetImg" API service within a React application. This hook abstracts away the complexity of making API requests, managing loading states, and handling errors, allowing developers to easily integrate image generation functionality into their applications.
Installation
Before using useGetImg
, ensure you have the required libraries installed:
npm install axios
Get API key
To obtain an API key from getimg.ai (opens in a new tab), sign up or log in to your account on their website, navigate to the API settings section, generate a new API key, copy it from the displayed key, and use it by passing it as a parameter when calling the useGetImg hook in your React application. Ensure to keep the API key secure, as it grants access to your getimg.ai (opens in a new tab) account.
Usage
import { useState } from "react";
import {useGetImg} from "use-ai-hooks";
const YourComponent = () => {
const [prompt, setPrompt] = useState("");
const [apiKey, setApiKey] = useState("your-api-key");
const { data, error, loading, generateImage } = useGetImg(apiKey);
const handleSubmit = () => {
generateImage(prompt);
};
return (
<div>
<input type="text" value={prompt} onChange={(e) => setPrompt(e.target.value)} />
<button onClick={handleSubmit}>Generate Image</button>
{loading && <p>Loading...</p>}
{error && <p>Error: {error.message}</p>}
{data && (
<img src={`data:image/jpeg;base64,${data.image}`} alt="Generated" />
)}
</div>
);
};
API Reference
Parameters
apiKey
(string): The API key required to authenticate requests to the GetImg API.
Return Value
data
(object | null): An object containing the generated image data, including the base64 encoded image string, seed, and cost.image
(string): A long base64 encoded image string.seed
(number): The seed used for generating the image.cost
(number): The cost incurred for generating the image.
error
(object | null): An object containing error information if an error occurs during the request.message
(string): Error message describing the issue.
loading
(boolean): A boolean indicating whether the request is in progress.generateImage
(function): A function to trigger the generation of an image based on a provided prompt.
Example Response Format
{
"image": "...looooong base64 encoded image string...",
"seed": 42,
"cost": 0.00663552
}
Hook
import { useState } from "react";
import axios, { AxiosResponse } from "axios";
interface ApiError {
message: string;
}
interface GenerateImageResponse {
data: any;
}
const useGetImg = (apiKey: string) => {
const [data, setData] = useState<GenerateImageResponse | null>(null);
const [error, setError] = useState<ApiError | null>(null);
const [loading, setLoading] = useState<boolean>(false);
const generateImage = async (prompt: string) => {
setLoading(true);
setError(null);
const url = "https://api.getimg.ai/v1/stable-diffusion/text-to-image";
const options = {
headers: {
accept: "application/json",
"content-type": "application/json",
authorization: `Bearer ${apiKey}`,
},
};
const data = {
prompt: prompt,
height: 1024,
width: 1024,
};
try {
const response: AxiosResponse<GenerateImageResponse> = await axios.post(
url,
data,
options
);
setData(response.data);
return response.data;
} catch (err) {
if (axios.isAxiosError(err)) {
setError({ message: err.message });
return err;
} else {
setError({ message: "An unexpected error occurred" });
return err;
}
} finally {
setLoading(false);
}
};
return { data, error, loading, generateImage };
};
export default useGetImg;