score:2

Accepted answer

I think reason is, componentDidMount will get called only ocne, just after the initial rendering, since you are using the same component for each route, so componentDidMount will not get called again. You need to use componentwillreceiveprops lifecycle method also, and check if you receive the new APIkey then do the api call inside that.

componentDidMount:

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

componentWillReceiveProps:

componentWillReceiveProps() is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.

Write the component like this:

export default class GetArticles extends Component {

  constructor(props) {
    super(props);
    this.state = {
      articleTitles: [],
      loading: true
    };
  }

  componentDidMount() {
    console.log('initial rendering', this.props.APIKey)
    this._callApi(this.props.APIKey);
  }

  componentWillReceiveProps(newProps){
     if(newProps.APIKey != this.props.APIKey){
        this._callApi(newProps.APIKey);
        console.log('second time rendering', newProps.APIKey)
     }
  }

  _callApi(APIKey){
    axios.get(APIKey)
      .then(response => {
        let titles = response.data.articles.map( (currentObj) => {
          return currentObj.title;
        } );

        this.setState({
          articleTitles: titles,
          loading: false
        });
      })
      .catch(error => {
        console.log('Error fetching and parsing data', error);
      });
  }

  render() {
    return (
      <div>
        <div className="main-content">
          <h1 className="main-title">Articles</h1>
          { (this.state.loading) ? <p>Loading</p> :   <ArticleList list={this.state.articleTitles} /> }
        </div>
      </div>
    );
  }
}

Related Query

More Query from same tag