Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialOliver Small
12,578 PointsAPI requests for a react site with multiple pages.
If I have a react site with multiple pages, when and where is the best place/time to do the api get requests?
For example if I had a blog site, I may want to have a featured list of blog posts on the homepage. Then I may have a second page called 'blog posts' which would show a list of all the blog posts, and the third page would be a detail view, showing all the info from a single blog post.
Would I be right in thinking that I should make these api requests within each page component? I feel like I shouldn't be using react context api or redux in this sort of instance?
1 Answer
Cory Harkins
16,500 PointsHi Oliver!
This would be a great time to have a Redux store actually!
When generating your store you have actions that can fire off HTTP requests and populate your store via reducers. This is helpful with a multi-routed SPA like you mentioned above.
You can fetch for all blog posts for a given time frame, and filter that single return from the api for the pages you are viewing. If featured blogs are say any blog written this week, but you need all the blogs for the month anyway, why not just pull all blogs for month and feature any blog written between timeNow < daysAgo.
The location of Axios/Fetch requests are easy to get confused as to when they should fire. Often though, they are made in componentDidMount() for the wrapping component, and shared down to the children as needed. When I say wrapping component it could be the main App, OR any parent/logic based component that gives data to display components. A component only mounts once, so be mindful about that as you construct your application.
Oliver Small
12,578 PointsOliver Small
12,578 PointsSorry for the delayed response, but thanks so much for getting back to me!
Cory Harkins
16,500 PointsCory Harkins
16,500 PointsNo problem Oliver!