@@ -838,6 +838,75 @@ build: off
838
838
- Single seam for mocking
839
839
840
840
841
+ ### FetchAPI
842
+
843
+ - Add a new route to ` srcServer.js` to simulate an available API endpoint called users
844
+
845
+ ` ` ` javascript
846
+ app.get('/users', function (request, response) {
847
+ response.json([
848
+ { "id": 1, "firstName": "Bob", "lastName": "Smith", "email": "bob@example.com" },
849
+ { "id": 2, "firstName": "Tammy", "lastName": "Norton", "email": "tnorton@example.com" },
850
+ { "id": 3, "firstName": "Tina", "lastName": "Lee", "email": "lee.tina@example.com" },
851
+ ]);
852
+ });
853
+ ` ` `
854
+
855
+ - Verify the new "API" by hitting http://localhost:3000/users in a browser
856
+ - To do this run `npm start` in the shell
857
+ - Create a new folder called `API` inside the `src` folder to contain our API client implementation
858
+ - ` userApi.js`
859
+
860
+ ` ` ` javascript
861
+ import 'whatwg-fetch';
862
+
863
+ /* eslint-disable no-console */
864
+
865
+ export function getUsers() {
866
+ return get('users');
867
+ }
868
+
869
+ function get(url) {
870
+ return fetch(url).then(onSuccess, onError);
871
+ }
872
+
873
+ function onSuccess(response) {
874
+ return response.json();
875
+ }
876
+
877
+ function onError(error) {
878
+ console.log(error);
879
+ }
880
+ ` ` `
881
+
882
+ - ` userApi.js` code is using `fetch` module; uses promises, error handling via fetch
883
+ - ` whatwg-fetch` module is a polyfil for non-modern browsers
884
+ - Repository pattern like
885
+ - Update `index.html` to accommodate user data
886
+ - Recreate`index.js` to use getUsers() from `userApi.js`
887
+
888
+ ` ` ` javascript
889
+ import './index.css';
890
+ import { getUsers } from './api/userApi';
891
+
892
+ getUsers().then(result => {
893
+ let usersBody = "";
894
+
895
+ result.forEach(user => {
896
+ usersBody += ` <div id="row">
897
+ <div id="column1"><a href="#" data-id="${user.id}" class="deleteUser">Delete</a></div>
898
+ <div id="id">${user.id}</div>
899
+ <div id="firstName">${user.firstName}</div>
900
+ <div id="lastName">${user.lastName}</div>
901
+ <div id="email">${user.email}</div>
902
+ </div>`
903
+ });
904
+
905
+ global.document.getElementById('users').outerHTML = usersBody;
906
+ });
907
+ ```
908
+
909
+
841
910
842
911
## Bibliography
843
912
0 commit comments