useDalle Hook
Introduction
The useDalle
custom hook facilitates interaction with the OpenAI DALL-E API within React applications. By utilizing this hook, developers can easily generate images based on provided prompts.
Installation
To use the useDalle
hook in your React application, follow these installation steps:
-
Ensure that React is installed in your project.
-
Install the necessary dependencies:
npm install axios
Usage
import React, { useState } from 'react';
import {useDalle} from 'use-ai-hooks'; // Import the custom hook
const DalleComponent = () => {
const [prompt, setPrompt] = useState('');
const apiKey = 'YOUR_API_KEY'; // Your OpenAI API key
const { image, error, loading, generateImage } = useDalle(apiKey);
const handleGenerate = () => {
if (prompt) {
generateImage({ prompt });
}
};
return (
<div>
<h1>DALL-E Image Generation</h1>
<textarea
placeholder="Enter prompt for image generation"
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
/>
<button onClick={handleGenerate} disabled={loading}>
Generate Image
</button>
{loading && <p>Loading...</p>}
{error && <p>Error: {error.message}</p>}
{image && <div>
<h2>Generated Image</h2>
<img src={image.data?.url} alt="Generated Image" />
</div>}
</div>
);
};
export default DalleComponent;
API Reference
Parameters
apiKey
(string): The API key required to authenticate requests to the OpenAI DALL-E API.
Returns
An object with the following properties:
image
(any): The generated image obtained from the OpenAI DALL-E API.error
(object | null): An object containing information about any errors that occurred during the API request.message
(string): A description of the error that occurred.
loading
(boolean): A boolean indicating whether the API request is currently in progress.generateImage(options: DalleOptions)
: A function to generate an image based on the provided options using the OpenAI DALL-E API.
Hook
import { useState } from "react";
import axios from "axios";
interface DalleOptions {
prompt: string;
}
interface ApiError {
message: string;
}
const useDalle = (apiKey: string) => {
const [image, setImage] = useState<any>(null);
const [error, setError] = useState<ApiError | null>(null);
const [loading, setLoading] = useState<boolean>(false);
const generateImage = async (options: DalleOptions) => {
setLoading(true);
setError(null);
try {
const response = await axios.post(
"https://api.openai.com/v1/images/generations",
{
prompt: options.prompt,
n: 1,
size: "1024x1024",
},
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
}
);
setImage(response || null);
return response;
} 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 { image, error, loading, generateImage };
};
export default useDalle;