Haiii! I think your code is actually working without any changes—if you wait for a bit between clicks you would eventually getting the desired habit that you want (I suppose that’s not desirable in a user’s perspective)!
I don’t have a lot of experience with using shouldComponentUpdate
and componentWillUpdate
—but I don’t think those lifecycles are needed in your case and would only complicate your logic.
One thing that I find helpful to keep in mind when I just started using React is that changes to a state that is being rendered inside the render()
method will cause a re-render. If we put it into the context of your project:
- The app should initially display a list of all campers:
componentDidMount() {
self = this;
$.getJSON(recentUrl, function(x) {
self.setState({campers: x});
// Since this.state.campers is inside the render() method, once the async API calls finishes this setState() method will be called, causing a re-render and showing the "recent" list
});
}
- The method will simply make an API call again and set
this.state.campers
to the new list received in order to cause a re-render:
switchAllTime() {
$.getJSON(allTimeUrl, function(x) {
self.setState({
campers: x,
url: allTimeUrl
});
});
};
switchRecent() {
$.getJSON(recentUrl, function(x) {
self.setState({
campers: x,
url: recentUrl
});
});
};
You can now get rid of componentWillMount
and shouldComponentUpdate
and your app should be working!
It is worth noting that there are other ways to structure this that will give you the same result, and that there are little things you may consider doing such as making sure that API calls are only made when the current URL is different to the new URL, or refactoring your code by having a single function for both onClick
triggers.
In addition, once you are a bit more comfortable with the basics I would suggest moving away from Codepen and use Glitch (there are various React boilerplates that you can remix) or, better still,create-react-app
instead. Using ES6 syntax will also make your React code much cleaner, too!
I hope that’s reasonably easy to follow helps! Good luck. 