Answer the question
In order to leave comments, you need to log in
How to resubmit an AJAX request on click with React?
Hey!
How can I resubmit an AJAX request on click, here is my code:
class App extends React.Component {
constructor(props){
super(props);
this.state = {
category: 'business',
items: []
}
}
componentDidMount() {
axios.get('https://newsapi.org/v2/top-headlines?country=us&category='+this.state.category)
.then(res => {
this.setState({items: res.data.articles});
})
}
changeCategory() {
this.setState({category: 'entertainment'});
console.log(this.state.category);
}
render() {
return (
<div className='wrapper'>
<button onClick={this.changeCategory.bind(this)}>CLICK</button>
</div>
);
}
}
Answer the question
In order to leave comments, you need to log in
class App extends React.Component {
state = {
category: 'business',
items: [],
};
componentDidMount() {
this.fetchData();
}
fetchData() {
axios.get('https://newsapi.org/v2/top-headlines?country=us&category='+this.state.category)
.then(res => {
this.setState({ items: res.data.articles });
});
}
changeCategory = () => {
this.setState(
{ category: 'entertainment' },
this.fetchData,
);
};
render() {
return (
<div className='wrapper'>
<button onClick={this.changeCategory}>CLICK</button>
</div>
);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question