top of page
Search

Using props instead of an API call

  • Writer: Chuck Curtis
    Chuck Curtis
  • Aug 13, 2019
  • 2 min read

Updated: Aug 19, 2019

I've moved the delete button from the Groups component into the Group component and realized that all the data that I need to populate the Group component has already there! Now I can remove the componentDidMount() method from the Group component, if only I can figure out how to use props to send the data between components.


After some careful googling I found this article where the author explains how he passes data through a Link component to a new route. I play around with my own code for some time before I'm able to make it work, but it turned out to be easier than I thought it could have!




First I have to update the 'to' property in the link to make it an object with keys of 'pathname' and 'group'. The pathname key is the same as the to property itself was before. For the group key, I pass through the group object that is being mapped over in my list. I open up the React app and confirm that the link is still working. I'm also able to use the React Dev tools to see that the group data is available in the Group component by accessing props.location.


I head over the Group component in atom and add the props parameter to my constructor function. Then I deconstruct the props.location object so that my state has direct access to the group object.


Finally, I completely comment out the componentDidMount() method, which had been making an axios call and then setting this.state with the group data. I head back over to the React app and I'm stoked to see that the Links are working and the correct group data is still there, even though I'm not making another axios call! Yay for less reliance on the API!


One thing that I do notice, which I'll need to address in the future, is that if I just try to go directly to a specific group my typing in the direct URL, the group does not populate. This makes sense because I'm skipping the step where I'm actually fetching the data and there's no props being passed through. I'm thinking that I'll end up using a conditional for making an axios call if no props are sent. That way I'm only making an API call when I absolutely need to.

 
 
 

Comments


Post: Blog2_Post

Subscribe Form

Thanks for submitting!

  • Facebook
  • Twitter
  • LinkedIn

©2019 by Web Dev with Chuck. Proudly created with Wix.com

bottom of page