Danae
Danae

Reputation: 141

react fetch data and render the error if any

I have implemented this component to get a some character info. I wanna get the name,vehicles and starships. If for some reason the character fails to load I want to display the particular error message. In the code below the url is broken in order to see if the error is being caught(which it is).

Here is my code.

   class Character extends Component {
      constructor(props) {
        super(props);
         this.state = {
          name: '',
          vehicles: [],
          starships: [],
        }
        this.handleCharacter();
      }

      handleCharacter(){
        let vehicles = [];
        let starships = [];
        let name= '';
        fetch('https://swapi.co/api/people/jhjh').then(results => {
          if(results.ok){
            return results.json();
          }
          throw new Error('Character fail to load');
        })
        .then(data => {
          data.results.forEach(item => {
            name = item.name;
            vehicles.push(item.vehicles);
            starships.push(item.starships);
          });
          this.setState(() => {
              return{ 
                  name: name,
                  vehicles:vehicles,
                  starships:starships
              }
          })
        })
        .catch(function(error) {
            console.log(error.message)
        });
      }

      render(){
        return (
          <div>
           //a bunch of code rendered
          // Somewhere here I wand to render a div only if there is an error
         </div>
        );
      }
    }

Upvotes: 0

Views: 1312

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

You need to set the state from the catch method. But you need to use an arrow function so that this refers to the component.

 .catch(error => {
    this.setState({ error: error.message } )
  });

then in your render you can check for this.state.error.

Make sure to clear it again on successful results

this.setState(() => {
          return{ 
              name: name,
              vehicles:vehicles,
              starships:starships,
              error: false
          }
      })

Upvotes: 2

Ariel Salem
Ariel Salem

Reputation: 357

You're on the right track, what you can do is simply conditionally render the error message by setting the state in your catch statement:

 .catch(function(error) {
    this.setState({ error: error.message } )
  });

render(){
    return (
      <div>
       //a bunch of code rendered
      {this.state.error && <div>{this.state.error}</div>}
     </div>
    );
  }

Upvotes: 1

Related Questions