Tích hợp lời gọi API váo ứng dụng của bạn
Tiếp theo, hãy tích hợp lời gọi API này vào ứng dụng web của bạn. Chứng ta sẽ tạo một form đơn giản nơi người
dùng có thể nhập vào một prompt và xem text được khởi tạo.
Trong file bộ phận chính của bạn, nhập khẩu hàm generateText và thiết lập một form với một text area cho prompt
và một nút để đệ trình.
import React, { useState } from ‘react’;
import { generateText } from ‘./openaiService’;function App() {
const [prompt, setPrompt] = useState(”);
const [response, setResponse] = useState(”);const handleSubmit = async (e) => {
e.preventDefault();
try {
const text = await generateText(prompt);
setResponse(text);
} catch (error) {
console.error(‘Error:’, error);
}
};return (
<div>
<h1>OpenAI Text Generation</h1>
<form onSubmit={handleSubmit}>
<textarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
placeholder=”Enter your prompt”
></textarea>
<button type=”submit”>Generate</button>
</form>
<div>
<h2>Generated Text</h2>
<p>{response}</p>
</div>
</div>
);
}export default App;
Code này thiết lập một bộ phận React đơn giản với một form. Khi người dùng đệ trình form, nó gọi hàm generateText
và hiển thị text được khởi tạo.