I cannot return the response of a post request with Xios from a function passed to child component

Asked

Viewed 47 times

0

I’m using the Google Translation Api, basically the function makes a request for their Api sending as parameters "q" (the text that needs to be translated) and "target" (a string containing the iso code of the language to which I want to translate).


    translate = async text => {
        const { Lang } = this.state;
        let translation = '';
        await axios.post(
            'https://translation.googleapis.com/language/translate/v2',
            {},
            {
                params: {
                    q: text,
                    target: Lang,
                    key: 'MINHA_CHAVE_PRIVADA',
                },
            }
        ).then(res => {
            console.log(res.data.data.translations[0].translatedText);
            translation = res.data.data.translations[0].translatedText;
        });

        console.log(translation);
        return translation;
    }

The problem that is occurring is this: my console.log shows that translations exist, but Return returns nothing.

In my head, it makes sense that I use async and await so that the Return is done after the AJAX request, the way it is above. I used arrow function (Arrow Function) because I read that it preserves this, context or something similar (sorry, I’m beginner), I opted for this because I want to catch the state of my parent component always: Lang ->


const { Lang } = this.state;

And put it on target. But when I put the async and await Keywords in the places that are wrong in the console.log and the React app doesn’t even run.

Console:

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

[![insert image description here][4

As you can see, translations are being returned normally.

When I remove the async and await Keywords, the React app finally runs - getting like this:


    translate = text => {
        const { Lang } = this.state;
        let translation = '';
        axios.post(
            'https://translation.googleapis.com/language/translate/v2',
            {},
            {
                params: {
                    q: text,
                    target: Lang,
                    key: 'MINHA_CHAVE_PRIVADA',
                },
            }
        ).then(res => {
            console.log(res.data.data.translations[0].translatedText);
            translation = res.data.data.translations[0].translatedText;
        });

        console.log(translation);
        return translation;
    }

The Return is performed first, returning empty Translation, including, I did the test and initialized the variable with the string '@' and returned '@'. But only so the function does not crash the entire program..

Anyway, I hope you make it.

Layout.jsx

import React from 'react';
import { Grid, Row, Col } from 'rsuite';
import axios from 'axios';
import Topnav from './Topnav';
import Map from './Map';
import Fixed from './Fixed';
import './All.css';

export default class Layout extends React.Component {
    constructor(){
        super();
        this.state = {
            Data: [],
            Filter: 'cases',
            Lang: 'pt'
        };
    }
    
    async componentDidMount() {...
    }

    translate = async text => {
        const { Lang } = this.state;
        let translation = '';
        await axios.post(
            'https://translation.googleapis.com/language/translate/v2',
            {},
            {
                params: {
                    q: text,
                    target: Lang,
                    key: 'AIzaSyCHUCmpR7cT_yDFHC98CZJy2LTms-IwDlM',
                },
            }
        ).then(res => {
            console.log(res.data.data.translations[0].translatedText);
            translation = res.data.data.translations[0].translatedText;
        });

        console.log(translation);
        return translation;
    }

    switchFilter = filter => {...
    }

    render() {
        const { Data, Filter } = this.state;
        const switchFilter = this.switchFilter;
        const translate = this.translate;

        return (
            <Grid fluid>
                <Row>
                    <Col xs={24} sm={24} md={24}>
                        <Topnav />
                    </Col>
                </Row>
                <Row>
                    <Col xs={24} sm={24} md={8}></Col>
                    <Col xs={24} sm={24} md={16}>
                        <Map tr={translate} Data={Data} Filter={Filter} />
                    </Col>
                </Row>
                <Fixed tr={translate} switchFilter={switchFilter} />
            </Grid>
        )
    }
}

Fixed.jsx (is the only place where I surround the function, despite having put as prop in more than one component)

import React from 'react';
import {
    Nav, Icon
} from 'rsuite';
import 'rsuite/dist/styles/rsuite-default.css';

export default class Fixed extends React.Component {
    render() {
        const tr = this.props.tr;
        const switchFilter = this.props.switchFilter;
        const FixedSettings = {...
        }

        return (
            <div {...FixedSettings}>
                <Nav>
                    <Nav.Item 
                        icon={<Icon icon='heartbeat' />}
                        onClick={() => switchFilter('deaths')}
                    >{tr('Deaths')}</Nav.Item>
                    <Nav.Item 
                        icon={<Icon icon='heart' />}
                        onClick={() => switchFilter('recovered')}
                    >{tr('Recovered')}</Nav.Item>
                    <Nav.Item 
                        icon={<Icon icon='eyedropper' />}
                        onClick={() => switchFilter('tests')}
                    >{tr('Tests')}</Nav.Item>
                    <Nav.Item  
                        icon={<Icon icon='line-chart' />}
                        onClick={() => switchFilter('cases')}
                    >{tr('Cases')}</Nav.Item>
                </Nav>
            </div>
        )
    }
}
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.