I'm trying to start an API call from a component when a user clicks a button. One URL param depends on the word a user selected before clicking the button. The fetch function is in an external function. When I call the function on button click and console log the result, it shows undefined
, probably because of the async nature of the function.
How can I solve this if I want to put the fetch response into the App
component state?
import { fetchAPI } from '../fetchAPI';
export default class App extends Component {
constructor() {
super();
this.toggleButtonState = this.toggleButtonState.bind(this);
state = { ... }
}
toggleButtonState() {
let selectedWord = window.getSelection().toString();
fetchAPI(selectedWord);
// call the fetchAPI function and put the result into state
}
export function fetchAPI(param) {
// param is a highlighted word from the user before it clicked the button
fetch('https://api.com/?param=' + param)
.then(function(result) {
return result;
});
}