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