score:2
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() 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() 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>
);
}
}
Source: stackoverflow.com
Related Query
- React and React Router, rendering the same element twice with a different prop results in two elements with the same prop?
- React Router V4: How to render a modal in the same screen changing only the url and then with that url, be able to rebuild the whole screen
- Is there a clean way to conditionally load and render different components for the same React Router route?
- React Router v5 accompanied with Code Splitting, and Data Prefetching with the use of Server Side Rendering
- Using the same component for different Routes with React Router
- react prop not rendering in parent component and even in the same one
- Approach for different HTML structure with React and using the same components
- React Router v6 : How to render multiple component inside and outside a div with the same path
- React rendering the component twice and 2nd disappears after a flash, [DOM] found 2 elements with non-unique id
- my page is not rendering with different id on the same page when i use link in react components
- React Hooks useEffect saves the last state and won't update it with the new one. It runs twice with two different states
- Using React Router with Switch and can't get the page to render different components when changing routes
- Create custom dynamic routes with react router and regex to the same component
- I'm having an issue with Passport when my React and Node servers are different (Firebase), but no issue when they are the same (Heroku)
- Jest mock the same function twice with different arguments
- React Router v4 - Redirect to same route with different query params
- Cannot render same route with different parameters react router v4
- Why React Router NavLink prop exact (v5) vs. end (v6) lead to different result with trailing slash in url
- What is the general practice for express and react based application. Keeping the server and client code in same or different projects/folders?
- React Redux with redux-observable use the router to navigate to a different page after async action complete
- How to retrieve the parameter after a hash (#) with React Router and useParams hook?
- React native picker and console showing different value of the same state
- React Infinite Scroller - Two children with the same key. loadMore function being called twice
- React Router List and Detail Route at the same time
- how to run my node application and react app in the same time with one command?
- React with Redux and Router - server rendering
- React element resets even when its `key` prop is kept the same
- React Router v4: Component and Children in the same route
- Multiple event handlers for the same event and element with Reactjs
- How to distinguish between a prop and a method with the same name, in Vue?
More Query from same tag
- react prop not updating at correct time when passed from parent component state
- Fetch and render API data inside Tab react js
- Trying to build react library but keep getting Error: Element type is invalid: expected a string
- calling the Redux-Thunk Action after Component Mount by using useEffect. but got issue : React Hook useEffect has missing dependencies
- How do I connect React component to cucumber.js?
- How to set state in a React component using this.setState without explicitly passing the field name to update?
- How do I add in an additional property for each individual mapped item after already making a call to a 3rd party API?
- Parsing error: Unexpected token React in functional component
- How to push a specific json object in an array?
- ReactJS with React Router - strange routing behaviour on Chrome
- addeventlistener for react-select
- Accessing a functional component state from another functional component
- Jest Unit Test - Mocking component with props
- material-table How do I select a row changing the background color upon selection
- i am trying to store the photo in the database (firebase) and in the storage. the photo got store in the Storage, but not added in the firestore
- Using Create-React-App with Express in production
- How do I manage mysql query errors from express in a React form?
- How to display the fetched json from redux in my react component?
- Webpack error: "You may need an appropriate loader to handle this file type"
- React updating state for validation always a step behind even when i set a callback function
- How to map the objects that having the dynamic keys in React?
- ReactJS <input type="date" > format date
- Adding React Template to React
- How can I pass the index from javascript map function to the onclick function?
- Working with images local files in Gatsby.js
- Rendering material-ui-next Checkbox inside a Redux Form
- How do I pass a function through props to a chid component where the parent is a functional component
- How to customize a div's scroll bar with css modules?
- jest shallow render find by class excluding
- How do I dynamically add styles to a React style attribute?