Home > Enterprise >  Javascript: How to set variable to API response value fetch api?
Javascript: How to set variable to API response value fetch api?

Time:04-28

Here is the code I am working with:

const encodedParams = new URLSearchParams();
encodedParams.append("q", "Hello, world!");
encodedParams.append("target", "es");
encodedParams.append("source", "en");

const options = {
    method: 'POST',
    headers: {
        'content-type': 'application/x-www-form-urlencoded',
        'Accept-Encoding': 'application/gzip',
        'X-RapidAPI-Host': 'google-translate1.p.rapidapi.com',
        'X-RapidAPI-Key': '3955ade317mshe662a97591d523ap1e4475jsn3bb2b223ccbb'
    },
    body: encodedParams
};

fetch('https://google-translate1.p.rapidapi.com/language/translate/v2', options)
    .then(response => response.json())
    .then(response => console.log(response))
    .catch(err => console.error(err));

Here is the response I receive from the API

{data: {…}}
data:
translations: Array(1)
0: {translatedText: '¡Hola Mundo!'}
length: 1
[[Prototype]]: Array(0)
[[Prototype]]: Object
[[Prototype]]: Object

How would I grab the translatedText from the API response and set a variable equal to that. I have tried TRANSLATED_TEXT = response.data.translations[0].translatedText;

I need to set a variable and then put the variable into a h1 on an HTML document. Any help with grabbing the API response would be appreciated!

CodePudding user response:

Found a similar example: https://rapidapi.com/googlecloud/api/google-translate1/discussions/21334

Try: response.data.data['translations'][0]['translatedText']

Hope it helps.

CodePudding user response:

try response.data.translations[0].translatedText.value;

or response.data.translations[0].translatedText[0].text;

  • Related