samedi 28 octobre 2017

React.js update state property to a new object

After componentDidMount quote is equal to {id: 16, text: "Be yourself; everyone else is already taken.", author: "Oscar Wilde", next_id: 18, previous_id: null}

When I click next, componentWillRecieveProps is invoked and tries to update quote to another object. I get an error. the same if I try to change it to a string. But when I try to change quote to a number or boolean, it works.

componentDidMount() {
  this.fetchQuote(16)
}

fetchQuote(id) {
  axios.get(`api/quotes/${id}`)
  .then(response => {
    console.log("Data: ", response.data);
    this.setState({
      quote: response.data
    }, ()=> {console.log("fetch: ", this.state);})
  })
  .catch(error => {
    console.error(error)
    this.setState({ fireRedirect: true })
  })
}

componentWillReceiveProps(nextProps) {
  this.qsParams = queryString.parse(nextProps.location.search)
  this.quoteId = Number(this.qsParams.quote)
  this.fetchQuote(this.quoteId)

}

componentWillReceiveProps(nextProps) successful triggers fetchQuote and that function makes a request and gets right data which is an object, but can't change quote to that received data

Aucun commentaire:

Enregistrer un commentaire