{"id":18272038,"url":"https://github.com/idindrakusuma/learn-react-http-request-and-router","last_synced_at":"2026-04-19T13:32:40.848Z","repository":{"id":119635055,"uuid":"146060189","full_name":"idindrakusuma/learn-react-http-request-and-router","owner":"idindrakusuma","description":"learning best practice of request data in ReactJS","archived":false,"fork":false,"pushed_at":"2018-09-09T11:53:51.000Z","size":885,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-09T03:18:20.313Z","etag":null,"topics":["axios","reactjs"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/idindrakusuma.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-08-25T03:06:41.000Z","updated_at":"2018-09-09T11:53:52.000Z","dependencies_parsed_at":"2023-05-28T03:00:42.282Z","dependency_job_id":null,"html_url":"https://github.com/idindrakusuma/learn-react-http-request-and-router","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/idindrakusuma/learn-react-http-request-and-router","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/idindrakusuma%2Flearn-react-http-request-and-router","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/idindrakusuma%2Flearn-react-http-request-and-router/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/idindrakusuma%2Flearn-react-http-request-and-router/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/idindrakusuma%2Flearn-react-http-request-and-router/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/idindrakusuma","download_url":"https://codeload.github.com/idindrakusuma/learn-react-http-request-and-router/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/idindrakusuma%2Flearn-react-http-request-and-router/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32009130,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-18T20:23:30.271Z","status":"online","status_checked_at":"2026-04-19T02:00:07.110Z","response_time":55,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["axios","reactjs"],"created_at":"2024-11-05T11:39:40.390Z","updated_at":"2026-04-19T13:32:40.832Z","avatar_url":"https://github.com/idindrakusuma.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Learn React Http Request \u0026 React Router\n\n## Rangkuman Belajar\n\n## Permulaan\n- Untuk mendapatkan sample dari API dengan respon `.json`, bisa diakses di https://jsonplaceholder.typicode.com/\n- Untuk http requestnya menggunakan package `axios`. \nsee documentation axios at https://github.com/axios/axios\n\n\n\n### Kapan waktu terbaik melakukan request data?\n\n#### Inisiasi Component\nLihat pada component lifecycle,\n\u003ccenter\u003e\n  \u003cimg src='./docs/images/react-component-lifecycle.png' style='max-width: 800px'\u003e\n\u003c/center\u003e\n\ndari `lifecycle` tersebut, waktu terbaik untuk melakukan `SIDE EFFECT` atau `request data` dari endpoint tertentu adalah pada saat `componentDidMount()`. Kok bisa? baca dokumentasi reactnya,\n\u003e componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.\n\nSee more: https://reactjs.org/docs/react-component.html#componentdidmount\n\n#### Updated Component\n\u003ccenter\u003e\n  \u003cimg src='./docs/images/update-lifecycle.png' style='max-width: 800px'\u003e\n\u003c/center\u003e\n\nsama halnya melakukan request di inisiasi component. Saat melakukan update component (kasus `fetch` detail data by id post) perlu dipertimbangkan `component lifecycle update`-nya. Jika dilihat pada gambar diatas, maka sesi terbaik adalah saat `componentDidUpdate()` dan tentu harus dipertimbangkan berbagai kondisi agar saat melakukan set state tidak berulang tanpa ada hentinya.\n\n```js\n // sample di component FullPost.js\n    componentDidUpdate () {\n        if(this.props.id) {\n            if (this.state.loadedPost \u0026\u0026 this.state.loadedPost.id === this.props.id) return;\n            axios.get('https://jsonplaceholder.typicode.com/posts/' + this.props.id)\n                .then(res =\u003e {\n                    this.setState({ loadedPost: res.data })\n                })\n                .catch(err =\u003e {\n                    console.log(err);\n                })\n        }\n    }\n```\n\n### Best practice untuk `http request` axios\n\nAda berbagai cara untuk melakukan request http menggunakan package `axios` di react. bisa langsung menggunakan `import axios from 'axios'`. Tetapi, hal tersebut akan melakukan pengulang - ulangan code. Karena setiap API mungkin mempunya konfigurasi yang berbeda.\n\n- Kalau di Set global? misal di index.js? \n\u003e Tidak bagus juga, karena ya itu, setiap API mungkin memiliki config yang berbeda2. \n\n- Bagaimana yang terbaik? **Menggunakan Method Instance**\n\nexample, `common/api.service.js`\n```js\nimport axios from 'axios';\n\nconst http = axios.create({\n  baseURL: 'https://jsonplaceholder.typicode.com'\n});\n\nhttp.defaults.headers.common['Authorization'] = 'API-KEY';\nhttp.defaults.headers.post['Content-Type'] = 'application/json';\n\nexport default http;\n```\n\nbaru setelah itu bisa di import di file lain,\n```js\nimport axios from './common/api.service'\n// then call axios as reguler way \n```\n\n### React Router\nReact Router adalah sebuah `package` yang berfungsi untuk menjadikan aplikasi react seperti multipage. example:\n```\ndomain.com/profile\ndomain.com/users\ndan lain sebagainya\n```\n2 package added for using Routing in react, :\n- `npm install -s react-router react-router-dom`\n\n### Absolute Path vs Relative Path\n- Absolute path\n```\ndomain: example.com\n\npathname: this.props.match.url + '/new-post'\n\nhasilnya: example.com/new-post\n\ndomain : example.com/new\nhasilnya tetep: example.com/new-post\n```\n- Relative Path\n```\nexample.com\n\npathname: '/new-post'\n\nhasilnya: example.com/new-post\n\ndomain : example.com/new\nhasilnya tetep: example.com/new/new-post\n```\n\n### Style the Active Link\n\nfor styling active route, you can use `NavLink`.\n```js\nimport {Route, NavLink} from 'react-route-dom';\n\n//use? default will be add class=\"active\"\n\u003cNavLink to='/new-post'\u003e New Post \u003c/NavLink\u003e\n// with custom active class?\n\u003cNavLink to='/new-post' activeClassName=\"my-active\"\u003e New Post \u003c/NavLink\u003e\n// with custom styleInline?\n\u003cNavLink to='/new-post' activeStyle={{textAlign: 'center'}}\u003e New Post \u003c/NavLink\u003e\n```\n\n### Route Swicth\n```ks\n\u003cSwitch\u003e \n    \u003cRoute path='/profile' component={ Profile}\u003e\n    \u003cRoute path='/:id' component={ Profile}\u003e\n\u003cSwitch\u003e\n```\nSwitch akan melakukan rendering route satu kali saja, jadi untuk kasus diatas, sangat cocok diterapkan switch.\n\n### Route history.replace\n\nBerfungsi untuk mengganti route ketika post. Nah ini cocok banget digunakan untuk kasus seperti NewPost.js\ncara penggunaan?\n\n```js\n// example in stateful component\nthis.props.history.replace('/posts')\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fidindrakusuma%2Flearn-react-http-request-and-router","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fidindrakusuma%2Flearn-react-http-request-and-router","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fidindrakusuma%2Flearn-react-http-request-and-router/lists"}