Multiple component instances - how to identify in code?


(Davíð Þórisson) #1

I am trying to understand how multiple component instances define themselves and differ from its “others”… I’ll present a simple example:

Say I have a Blog component and nested (child) Comment components. Comment subscribes to app actions like “saveNewComment” and because there are multiple instances of this component, action would be handled by each and every instance and comment thus saved multiple times.

(this example is of course theoretical, in reality action handler would be in Blog!)

Q: Since component’s key property is no longer accessible, how can I identify the component instance eg. for debugging in console? I might for example want to follow when an instance is unmounted and keep track of that by it’s unique key/id?


(Troy Rhinehart) #2

Sorry, I wasn’t able to fully follow your example but it sounds like each “Blog” has a “Comments” component right? Well, each comment then has an association to a blog post, aka a unique id. So, a generic “Comments” component would then have the prop blogId and an array of associated comments. Using that blogId, just pass it as an argument to your action creator and now you have identified which blog post to associate the new comment to.


(Troy Rhinehart) #3

Or, if you rather have the “Blog” component handle the id associations, then you’ll need to bind the function you pass to the “Comments” component with the id, this way the “Component” doesn’t know about the blogId but the handler will be provided the id when invoked in the “Blog”.


(Thomas Clarke) #4

If you’re using a database to store the comments, that will be keyed, so why not pass the databaseKey in as a separate property?
You could then even use a keyExtractor function to get the databaseKey, rather than duplicating it with the key property.