|
| 1 | +# 11 Table fetch |
| 2 | + |
| 3 | +In this sample we are going to update the previous sampe (mock table) and instead of |
| 4 | +returning mock data, return real data from the github rest api. |
| 5 | + |
| 6 | +# Steps to reproduce the sample |
| 7 | + |
| 8 | +- We will take as starting point sample _10 tableMock_, let's copy the content from this |
| 9 | + sample and execute _npm install_. |
| 10 | + |
| 11 | +```bash |
| 12 | +npm install |
| 13 | +``` |
| 14 | + |
| 15 | +- To retrieve data from the Github REST api we will make use of axios, let's install the package |
| 16 | + (no need to install typing, they are already included in the library). |
| 17 | + |
| 18 | +```bash |
| 19 | +npm install axios --save |
| 20 | +``` |
| 21 | + |
| 22 | +- Time to open the _memberApi_ file and replace the mock data with a real api call. |
| 23 | + |
| 24 | +_./src/api/memberApi.ts_ |
| 25 | + |
| 26 | +```diff |
| 27 | +import { MemberEntity } from "../model/member"; |
| 28 | ++ import Axios, { AxiosResponse } from 'axios'; |
| 29 | + |
| 30 | ++ const gitHubURL = 'https://api.github.com'; |
| 31 | ++ const gitHubMembersUrl = `${gitHubURL}/orgs/lemoncode/members`; |
| 32 | + |
| 33 | +export const getMembersCollection = (): Promise<MemberEntity[]> => { |
| 34 | + const promise = new Promise<MemberEntity[]>((resolve, reject) => { |
| 35 | ++ try { |
| 36 | ++ Axios.get<MemberEntity[]>(gitHubMembersUrl) |
| 37 | ++ .then(response => resolve(mapMemberListApiToModel(response))); |
| 38 | ++ } catch (ex) { |
| 39 | ++ reject(ex); |
| 40 | ++ } |
| 41 | +- setTimeout( |
| 42 | +- () => |
| 43 | +- resolve([ |
| 44 | +- { |
| 45 | +- id: 1457912, |
| 46 | +- login: "brauliodiez", |
| 47 | +- avatar_url: "https://avatars.githubusercontent.com/u/1457912?v=3" |
| 48 | +- }, |
| 49 | +- { |
| 50 | +- id: 4374977, |
| 51 | +- login: "Nasdan", |
| 52 | +- avatar_url: "https://avatars.githubusercontent.com/u/4374977?v=3" |
| 53 | +- } |
| 54 | +- ]), |
| 55 | +- 500 |
| 56 | +- ); |
| 57 | + }); |
| 58 | + |
| 59 | + return promise; |
| 60 | +}; |
| 61 | + |
| 62 | ++ const mapMemberListApiToModel = ({data}: AxiosResponse<any[]>): MemberEntity[] => |
| 63 | ++ data.map(gitHubMember => ({ |
| 64 | ++ id: gitHubMember.id, |
| 65 | ++ login: gitHubMember.login, |
| 66 | ++ avatar_url: gitHubMember.avatar_url |
| 67 | ++ })); |
| 68 | +``` |
| 69 | + |
| 70 | +- Aaaand... we don't need to add any update on the rest of the application, why? |
| 71 | + The function is providing the same contract it returns a promise<MemberEntity[]>, |
| 72 | + let's give a try: |
| 73 | + |
| 74 | +```bash |
| 75 | +npm start |
| 76 | +``` |
0 commit comments