sp-dev-fx-webparts/samples/react-react-query
Hugo Bernier 411f1b1eca Changed authors to contributors 2023-02-18 22:58:44 -05:00
..
assets Samples reviewed and prepared for merge 2022-11-08 19:11:58 +01:00
config
src
teams
tests/components
.eslintrc.js
.gitignore
.npmignore
.yo-rc.json
README.md Changed authors to contributors 2023-02-18 22:58:44 -05:00
gulpfile.js
package-lock.json Bump decode-uri-component in /samples/react-react-query 2022-12-30 23:42:23 -05:00
package.json
tsconfig.json

README.md

react-react-query

Summary

This sample shows how to use react query library and react hooks with SPFx. Main focus is on contextually centralized MS Graph Client to avoid calls duplication.

Used SharePoint Framework Version

version

Applies to

Get your own free development tenant by subscribing to Microsoft 365 developer program

Prerequisites

MS SPO Extensibility Principal should be provisioned and access to MS Graph API with User.Read should be granted before running this sample.

Contributors

Version history

Version Date Comments
1.0 October, 19 Initial release

Disclaimer

THIS CODE IS PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.


Minimal Path to Awesome

  • Clone this repository
  • Ensure that you are at the solution folder
  • in the command-line run:
    • npm install
    • gulp serve

Include any additional steps as needed.

Features

The idea of this sample is simple. Quite often in our solutions we need to use data from one endpoint in multiple places. I think the most common scenario might be displaying current user info.

One of the most popular libraries to handle http requests in React is react-query. This library simplifies http calls by providing easy to use react hook.

You can see, that although we are rendering user four times, there is only one batched request to MS Graph API. Note, I implemented three different user components to test nesting case as well as using the same hook in different component.

Additional benefit of such approach is better isolation from SPFx itself. Not only it would be easier to move this solution from SPFx to simple React project (should You need to expose similar functionality outside of SharePoint context), but it improved testability of the solution. I added two tests to the solution: User.test.tsx - which mocks whole context and UserMockHook which benefits from the fact, that we can mock only useUserQuery hook.

References