How to make an API request In React on button click

时间:2019-04-08 13:22:38

标签: reactjs api axios

I am trying to build a random quote generator that loads A quote on componentDidMount with an axios api request , then loads new quotes on button click.

This is for A freecodecamp project. I have tried making the call again on button click, then adding the new respone to state, but it will not work at all.

import React, { Component } from 'react'
import Button from './Button';
import axios from 'axios'
class QuoteBox extends Component{
constructor(props){
    super(props)

    this.state = {
      quotes: []

    }

 }
componentDidMount(){
 axios.get('http://quotesondesign.com/wp-json/posts? 
filter[orderby]=rand&filter[posts_per_page]=1')
 .then(res=> this.setState({quotes: res.data[0]}))

}
getNext = (ev) =>{
  ev.preventDefault()
  axios.get('http://quotesondesign.com/wp-json/posts? 
filter[orderby]=rand&filter[posts_per_page]=2')
  .then(res=> this.setState({quotes:[...this.state,res.data[0]]}))
}


render(){
const {content,title} = this.state.quotes
const filteredContent = String(content).replace(/(<\w>)|(<\/\w>)| 
(&#\d{4})/gm, "").replace(/(;)/g,"'")
 console.log(content)

 return(
   <React.Fragment>
      <h2>A little inspiration for the day</h2>
      <div className='outerQuoteBox'>
        <div className='innerQuoteBox'>
            <p>{filteredContent}</p><br/><br/>{title}
        </div>
        <Button getNext={this.getNext} />
    </div>
    </React.Fragment>)
   }
  }
export default QuoteBox

And this is my button component

import React, { Component } from 'react'

export class Button extends Component {
 render() {
  return (
   <React.Fragment>
    <button onClick={this.props.getNext} className='nextBtn' 
      type='button'>Next</button>
    </React.Fragment>
   )
 }
}

export default Button

When I click the button, it seems like the request isnt going through at all. If i check State in the dev tools, only the first quote from componentDidMount is in the array. I dont understand where my mistake is.

Edit: I had used the wrong prop reference, so it wasnt making the call. I fixed this and it does make the call now, and it brings in one new quote, but thats it. And it doesnt add the new one to state, it just replaces it with the one new one. and thats all it will do. The api instructions say the end point im using should return a new random quote, but it does not.

1 个答案:

答案 0 :(得分:2)

It looks like you're referencing the wrong prop on the button.

Change getQuote to getNext and it should work...

import React, { Component } from 'react'

export class Button extends Component {
 render() {
  return (
   <React.Fragment>
    <button onClick={this.props.getNext} className='nextBtn' 
      type='button'>Next</button>
    </React.Fragment>
   )
 }
}

export default Button