This simple translation function returns value in it's own file but when I tried calling it in other file and catching result it gives undefined
Here is code below I also made it in codesandbox so it's easier to read: https://codesandbox.io/s/cool-dewdney-qq9pu?fontsize=14&hidenavigation=1&theme=dark
App.js
import React from "react";
import "./styles.css";
import translateText from "./translator";
import { render } from "react-dom";
import Button from "@material-ui/core/Button";
const text = "Dog";
const lang = "pl";
class App extends React.Component {
translationHandle() {
if (text && lang) {
console.log(translateText(text, lang)); // gives undefined
const result = translateText(text, lang);
console.log(result); // also gives undefined
}
}
render() {
return (
<div className="App">
<h1>Why does it give undefined</h1>
<Button onClick={this.translationHandle}>Click</Button>
</div>
);
}
}
export default App;
translate.js
const translate = require("yandex-translate")(api_key);
const translateText = (text, lang) => {
translate.translate(text, { to: lang }, function(err, res) {
console.log(res.text); // returns value only in this file
return res.text; // gives undefined
});
};
export default translateText;
also secondary question: how can I change translateText function so it catches error as well thank you for help