Skip to content Skip to sidebar Skip to footer

React And Axios Fires Twice (once Undefined, Once Successfully)

Following the React AJAX example i have created a JSX file which purpose is to fetch and render a movie. For all i know, i am doing everything right here. When i console.log the da

Solution 1:

Check the state inside the render method. With this approach you can render a loading screen:

importReactfrom"react";
import axios from"axios";

exportdefaultclassNetflixHeroextendsReact.Component {
 constructor() {
    super();
    this.state = {
      movie: []
    }
 }
}

componentDidMount() {
  const apiKey = '87dfa1c669eea853da609d4968d294be';
  let requestUrl = 'https://api.themoviedb.org/3/' + this.props.apiAction + '&api_key=' + apiKey;
  axios.get(requestUrl).then(response => {
      this.setState({movie: response.data.results})
  });
}

render() {
  //Loading...if( this.state.movie[0] === undefined ) {
      return<div>Loading...</div>
  }

  //Loaded successfully...return(
   <div> Movie loaded... [Do action here] </div>
  )
}

Explanation

Every time the state changes, a re-render will be triggered. The first time, your Component is constructed with this.state.movie = []. After that, componentDidMount() is triggered, which changes your state. This is triggering the render method a second time.

Post a Comment for "React And Axios Fires Twice (once Undefined, Once Successfully)"