In my recent blogpost I wrote about using batch requests with the SharePoint Rest Api within a SharePoint Framework (SPFx) solution. Today I want to construct a similar scenario which shows batch requesting using the new Microsoft Graph access class within SPFx.
Please note that this approach is currently, when writing this post (Jul-2018), in final preview mode and therefore not supported in production scenarios as it might be subject to change. A GA is expected with the next SPFx version (1.6.0) end of this month.
But now lets start with a simple scenario. Lets suppose we have a bunch of Group IDs
Within our component we will do several things now. First within the constructor (you might use a Graph call several times within your code, otherwise you can also do it in your function) we instantiate a MSGraphClient
this.client = this.props.context.serviceScope.consume(MSGraphClient.serviceKey);
In a getGroupsData function we then create our requests based on the IDs of our Groups from above (Please note that we also handover an index which we can later use to simply identify the repsonse if needed as the repsonses might be ordered differently than the requests originally were):
What happens afterwards is one simple call to the Graph Api handing over all requests in the body. If no error occurs and we recieve a Status of 200 per response (also one single request might fail, for instance when we have provided a wrong Id) we can push the response part to our array based on our custom UnifiedGroup interface.
When every response is handled, we set our state which lets our component re-render as usual.
Please pay attention that there is a hard limit of 20 (!!) requests per batch request. So in case you would have more than 20 Ids (or something similar, this is a constructed scenarion of course) you need to create several batch requests, similar to a paging approach.
Before we can test our stuff, we also need to request permissions in the package-solution.json
For debugging with the workbench this is sufficient (this now works with SPFx 1.5.0!), when deploying our solution we have to grant that permissions by an admin tenant-wide also as described here
Once we run our simple solution it might (simply rendered) look like this:
Finally for your reference the whole component’s source: