T
T
townee2018-05-26 21:52:14
JavaScript
townee, 2018-05-26 21:52:14

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

Now I'm changing the category, but the page is not refreshing, how is it possible to make another request on click?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-05-26
@townee

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 question

Ask a Question

731 491 924 answers to any question