Hooks
useTranslation

useTranslation Hook

Introduction

useTranslation is a custom React hook designed to simplify text translation using the OpenAI API. This hook encapsulates the translation logic, making it easy to integrate translation features into your React applications.

Installation

Before using useTranslation, ensure you have the required libraries installed:

npm install axios 

Usage

import React, { useState } from 'react';
import {useTranslation} from 'use-ai-hooks'; // Import the custom hook
 
const TranslationComponent = () => {
  const [textToTranslate, setTextToTranslate] = useState('');
  const [targetLanguage, setTargetLanguage] = useState('');
  const apiKey = 'YOUR_API_KEY'; // Your OpenAI API key
 
  const { translatedText, error, loading, translateText } = useTranslation(apiKey);
 
  const handleTranslate = () => {
    if (textToTranslate && targetLanguage) {
      translateText({ text: textToTranslate, targetLanguage });
    }
  };
 
  return (
    <div>
      <h1>Text Translation</h1>
      <input
        type="text"
        placeholder="Enter text to translate"
        value={textToTranslate}
        onChange={(e) => setTextToTranslate(e.target.value)}
      />
      <input
        type="text"
        placeholder="Enter target language"
        value={targetLanguage}
        onChange={(e) => setTargetLanguage(e.target.value)}
      />
      <button onClick={handleTranslate} disabled={loading}>
        Translate
      </button>
 
      {loading && <p>Loading...</p>}
      {error && <p>Error: {error.message}</p>}
      {translatedText && <p>Translated Text: {translatedText}</p>}
    </div>
  );
};
 
export default TranslationComponent;
 
 

API Reference

Initializes the translation hook with the provided OpenAI API key.

  • apiKey: string: Your OpenAI API key required to access the translation service.

Returns an object with the following properties:

  • translatedText: string | null: The translated text, or null if no translation is available.
  • error: { message: string } | null: An error object containing the error message, or null if no error occurred.
  • loading: boolean: A boolean value indicating whether the translation request is in progress.
  • translateText(options: TranslationOptions) => void: A function to initiate text translation. Accepts an object containing the text to translate and the target language.

TranslationOptions

An interface defining the options for text translation:

interface TranslationOptions {
  text: string; // The text to translate
  targetLanguage: string; // The target language for translation
  model?: "gpt-3.5-turbo-0125" | "gpt-3.5-turbo" | "gpt-3.5-turbo-1106" | "gpt-3.5-turbo-instruct" | "pt-3.5-turbo-16k" | "gpt-3.5-turbo-0613" | "gpt-3.5-turbo-16k-0613"; // Optional: The translation model to use
}
 

Hook

import { useState } from "react";
import axios from "axios";
 
interface ApiError {
  message: string;
}
 
interface TranslationOptions {
  text: string;
  targetLanguage: string;
  model?:
    | "gpt-3.5-turbo-0125"
    | "gpt-3.5-turbo"
    | "gpt-3.5-turbo-1106"
    | "gpt-3.5-turbo-instruct"
    | "pt-3.5-turbo-16k"
    | "gpt-3.5-turbo-0613"
    | "gpt-3.5-turbo-16k-0613";
}
 
const useTranslation = (apiKey: string) => {
  const [translatedText, setTranslatedText] = useState<string | null>(null);
  const [error, setError] = useState<ApiError | null>(null);
  const [loading, setLoading] = useState<boolean>(false);
 
  const translateText = async ({
    text,
    targetLanguage,
    model = "gpt-3.5-turbo",
  }: TranslationOptions) => {
    setLoading(true);
    setError(null);
 
    try {
      const result = await axios.post(
        "https://api.openai.com/v1/chat/completions",
        {
          model,
          messages: [
            { role: "system", content: "You are a translation model." },
            {
              role: "user",
              content: `Translate the following text to ${targetLanguage}: ${text}`,
            },
          ],
        },
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${apiKey}`,
          },
        }
      );
 
      const responseText = result.data.choices[0]?.message?.content?.trim();
      setTranslatedText(responseText || null);
      return responseText;
    } catch (err) {
      if (axios.isAxiosError(err)) {
        setError({ message: err.message });
      } else {
        setError({ message: "An unexpected error occurred" });
      }
      return err;
    } finally {
      setLoading(false);
    }
  };
 
  return { translatedText, error, loading, translateText };
};
 
export default useTranslation;