Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
137
rated 0 times [  144] [ 7]  / answers: 1 / hits: 47500  / 6 Years ago, tue, october 30, 2018, 12:00:00

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;
});
}

More From » reactjs

 Answers
8

You have to return the fetch request from your fetchAPI function, and you also want to add an additional then and give it a function in which you put the result in the state in the toggleButtonState function.



In your example the then inside the fetchAPI function is redundant, since it just returns the value as is. You can remove that and still get the same result.



Example





function fetch() {
return new Promise(resolve => setTimeout(() => resolve(42), 1000));
}

function fetchAPI(param) {
// param is a highlighted word from the user before it clicked the button
return fetch(https://api.com/?param= + param);
}

class App extends React.Component {
state = { result: null };

toggleButtonState = () => {
let selectedWord = window.getSelection().toString();
fetchAPI(selectedWord).then(result => {
this.setState({ result });
});
};

render() {
return (
<div>
<button onClick={this.toggleButtonState}> Click me </button>
<div>{this.state.result}</div>
</div>
);
}
}

ReactDOM.render(<App />, document.getElementById(root));

<script src=https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js></script>
<div id=root></div>




[#53207] Saturday, October 27, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
annaliese

Total Points: 86
Total Questions: 97
Total Answers: 107

Location: Dominican Republic
Member since Sun, Sep 4, 2022
2 Years ago
;