Instructor: Here, we have an application fetching person1 from the Star Wars API using a fetch JSON component. This component accepts a render prop function. Its parameters are isLoading and data.
This way, we can show a loading indicator until the request is finished loading, and the name, once it's done. The fetch JSON component stores isLoading, as well as data in the state. Both are updated once the request is finished.
So far so good. Now, we implement a button to change the person to be fetched in our application. When we click the button, nothing happens. This is the case because the component fetch JSON only triggers a request on componentDidMount.
To trigger a new request on every URL update, we can leverage getDerivedStateFromProps. It's a static function that receives two parameters. It should return an object to update a state, a now to indicate that the new props do not require any state updates.
Our goal is to reset the state once a new URL has been provided. Since we can't access previousProps, we have to stop the URL in state. In getDerivedStateFromProps, we compare the previous URL with the next one. Only if it changed, we reset data to null and loading to true.
Last but not least, we need to make sure the new URL is fetched inside componentDidUpdate. Voila. Our component works as expected. When is getDerivedStateFromProps invoked? Right after component is instantiated, as well as when it receives new props.
Note that if a parent component causes a component to rerender, this method will be called even if props have not changed. You may want to compare new and previous values if you only want to handle changes.
Keep in mind, because getDerivedStateFromProps is a static function, you won't have access to the component instance using this. While it has nothing to do with getDerivedStateFromProps, there's one more buck I want to highlight.
Clicking the button while another request is loading can lead to the situation at multiple request and process, and can finish. As you could see, briefly, Luke Skywalker was rendered.
Therefore, in fetch an update, it's best to store the URL, and in the setState function, we can check if the URL we fetched is the last one in the current state. This time, Luke Skywalker wasn't rendered.