2

In my React.js app, I am fetching a quote from API and storing it in the state object, When trying to access the properties of the object which is stored in state. Returning null.

Code:

import React, { Component } from "react";

export default class Quotes extends Component {
  constructor(props) {
    super(props);

    this.state = {
      quote: null,
    };
  }

  componentDidMount() {
    fetch("https://quote-garden.herokuapp.com/api/v2/quotes/random")
      .then((response) => response.json())
      .then((quote) => this.setState({ quote: quote.quote }))
      .catch((error) => console.log(error));
  }
  render() {
    console.log(this.state.quote.quoteText); //This is returning null
    console.log(this.state.quote); //This is working fine.
    return (
      <div>
        <p>// Author of Quote</p>
      </div>
    );
  }
}

I am new to React.js, I spining my head for this problem around 2 hourse. I didn't get any solution on web

output showing quote object

When I try to console.log(this.state.quote) it prints out this output, well it is fine.

and when I try console.log(this.state.quote.quoteText) It will return can not read property

output showing can not find property

2 Answers2

2

You must note the you are trying to fetch data asynchronously and also you fetch data in componentDidMount which is run after render, so there will be an initial rendering cycle wherein you will not have the data available to you and this.state.quote will be null

The best way to handle such scenarios is to maintain a loading state and do all processing only after the data is available

import React, { Component } from "react";

export default class Quotes extends Component {
  constructor(props) {
    super(props);

    this.state = {
      quote: null,
      isLoading: true,
    };
  }

  componentDidMount() {
    fetch("https://quote-garden.herokuapp.com/api/v2/quotes/random")
      .then((response) => response.json())
      .then((quote) => this.setState({ quote: quote.quote, isLoading: false }))
      .catch((error) => console.log(error));
  }
  render() {
    if(this.state.isLoading) {
     return <div>Loading...</div>
   }
    console.log(this.state.quote.quoteText); //This is returning proper value
    console.log(this.state.quote); 
    return (
      <div>
        <p>// Author of Quote</p>
      </div>
    );
  }
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

When you are accessing the quoteText without checking whether the key in the object is present or not it throws an error -

render(){
  if(this.state.quote && this.state.quote.hasOwnProperty('quoteText')){ 
    console.log(this.state.quote.quoteText);
   }
}
Dlucidone
  • 1,091
  • 9
  • 23