├── .github └── FUNDING.yml ├── .gitignore ├── .travis.yml ├── README.md ├── package-lock.json ├── package.json ├── public ├── favicon.ico ├── index.html └── manifest.json └── src ├── App.css ├── App.js ├── App.test.js ├── __snapshots__ └── App.test.js.snap ├── index.css ├── index.js └── serviceWorker.js /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: rwieruch 4 | patreon: # rwieruch 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with a single custom sponsorship URL 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | 6 | # testing 7 | /coverage 8 | 9 | # production 10 | /build 11 | 12 | # misc 13 | .DS_Store 14 | .env.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | 3 | node_js: 4 | - stable 5 | 6 | install: 7 | - npm install 8 | 9 | script: 10 | - npm test -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The Road to Learn React - Hacker News Client 2 | 3 | [![Build Status](https://travis-ci.org/the-road-to-learn-react/hackernews-client.svg?branch=master)](https://travis-ci.org/the-road-to-learn-react/hackernews-client) [![Slack](https://slack-the-road-to-learn-react.wieruch.com/badge.svg)](https://slack-the-road-to-learn-react.wieruch.com/) [![Greenkeeper badge](https://badges.greenkeeper.io/the-road-to-learn-react/hackernews-client.svg)](https://greenkeeper.io/) 4 | 5 | The application you will build when you read the book to [learn React](https://www.robinwieruch.de/the-road-to-learn-react/). 6 | 7 | Find all chapter outcomes over [here](https://github.com/the-road-to-learn-react/hackernews-client). 8 | * [Chapter 1 Outcome](https://github.com/the-road-to-learn-react/hackernews-client/tree/dc46f5efde0059d88a12a52886dd77b85997f78d) 9 | * [Chapter 2 Outcome](https://github.com/the-road-to-learn-react/hackernews-client/tree/387b16504cad20ecf196662959087806c59de13f) 10 | * [Chapter 3 Outcome](https://github.com/the-road-to-learn-react/hackernews-client/tree/ffbcb39b125a6cde080bffb74bdb8b4bd105cf75) 11 | * [Chapter 4 Outcome](https://github.com/the-road-to-learn-react/hackernews-client/tree/1ee4c812f685c752a7e333a6b886875317800883) 12 | * [Chapter 5 Outcome](https://github.com/the-road-to-learn-react/hackernews-client/tree/5e7cb9b8db98d1237badb462f40b4048462b21f1) 13 | * [Chapter 6 Outcome](https://github.com/the-road-to-learn-react/hackernews-client/tree/62c8ed57ca2b00b8e35016379d013f9ce7bc5a7c) 14 | 15 | After reading the book, you can continue to [learn more about JavaScript](https://roadtoreact.com). 16 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hackernews-client", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "axios": "^0.18.0", 7 | "classnames": "^2.2.6", 8 | "lodash": "^4.17.11", 9 | "react": "^16.8.4", 10 | "react-dom": "^16.8.4", 11 | "react-scripts": "3.1.0" 12 | }, 13 | "scripts": { 14 | "start": "react-scripts start", 15 | "build": "react-scripts build", 16 | "test": "react-scripts test", 17 | "eject": "react-scripts eject" 18 | }, 19 | "eslintConfig": { 20 | "extends": "react-app" 21 | }, 22 | "browserslist": [ 23 | ">0.2%", 24 | "not dead", 25 | "not ie <= 11", 26 | "not op_mini all" 27 | ], 28 | "devDependencies": { 29 | "enzyme": "^3.9.0", 30 | "enzyme-adapter-react-16": "^1.10.0", 31 | "react-addons-test-utils": "^15.6.2", 32 | "react-test-renderer": "^16.8.4" 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/the-road-to-learn-react/hackernews-client/32bc7c4b2a06bb60b6624a5ee410f68090fcf3be/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 10 | 11 | 15 | 16 | 25 | React App 26 | 27 | 28 | 29 |
30 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": ".", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .page { 2 | margin: 20px; 3 | } 4 | 5 | .interactions { 6 | text-align: center; 7 | } 8 | 9 | .table { 10 | margin: 20px 0; 11 | } 12 | 13 | .table-header { 14 | display: flex; 15 | line-height: 24px; 16 | font-size: 16px; 17 | padding: 0 10px; 18 | justify-content: space-between; 19 | } 20 | 21 | .table-empty { 22 | margin: 200px; 23 | text-align: center; 24 | font-size: 16px; 25 | } 26 | 27 | .table-row { 28 | display: flex; 29 | line-height: 24px; 30 | white-space: nowrap; 31 | margin: 10px 0; 32 | padding: 10px; 33 | background: #ffffff; 34 | border: 1px solid #e3e3e3; 35 | } 36 | 37 | .table-header > span { 38 | overflow: hidden; 39 | text-overflow: ellipsis; 40 | padding: 0 5px; 41 | } 42 | 43 | .table-row > span { 44 | overflow: hidden; 45 | text-overflow: ellipsis; 46 | padding: 0 5px; 47 | } 48 | 49 | .button-inline { 50 | border-width: 0; 51 | background: transparent; 52 | color: inherit; 53 | text-align: inherit; 54 | -webkit-font-smoothing: inherit; 55 | padding: 0; 56 | font-size: inherit; 57 | cursor: pointer; 58 | } 59 | 60 | .button-active { 61 | border-radius: 0; 62 | border-bottom: 1px solid #38BB6C; 63 | } -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import axios from 'axios'; 3 | import { sortBy } from 'lodash'; 4 | import classNames from 'classnames'; 5 | import './App.css'; 6 | 7 | const DEFAULT_QUERY = 'redux'; 8 | const DEFAULT_HPP = '100'; 9 | 10 | const PATH_BASE = 'https://hn.algolia.com/api/v1'; 11 | const PATH_SEARCH = '/search'; 12 | const PARAM_SEARCH = 'query='; 13 | const PARAM_PAGE = 'page='; 14 | const PARAM_HPP = 'hitsPerPage='; 15 | 16 | const largeColumn = { 17 | width: '40%', 18 | }; 19 | 20 | const midColumn = { 21 | width: '30%', 22 | }; 23 | 24 | const smallColumn = { 25 | width: '10%', 26 | }; 27 | 28 | const SORTS = { 29 | NONE: list => list, 30 | TITLE: list => sortBy(list, 'title'), 31 | AUTHOR: list => sortBy(list, 'author'), 32 | COMMENTS: list => sortBy(list, 'num_comments').reverse(), 33 | POINTS: list => sortBy(list, 'points').reverse(), 34 | }; 35 | 36 | const updateSearchTopStoriesState = (hits, page) => (prevState) => { 37 | const { searchKey, results } = prevState; 38 | 39 | const oldHits = results && results[searchKey] 40 | ? results[searchKey].hits 41 | : []; 42 | 43 | const updatedHits = [ 44 | ...oldHits, 45 | ...hits 46 | ]; 47 | 48 | return { 49 | results: { 50 | ...results, 51 | [searchKey]: { hits: updatedHits, page } 52 | }, 53 | isLoading: false 54 | }; 55 | }; 56 | 57 | class App extends Component { 58 | constructor(props) { 59 | super(props); 60 | 61 | this.state = { 62 | results: null, 63 | searchKey: '', 64 | searchTerm: DEFAULT_QUERY, 65 | error: null, 66 | isLoading: false, 67 | }; 68 | 69 | this.needsToSearchTopStories = this.needsToSearchTopStories.bind(this); 70 | this.setSearchTopStories = this.setSearchTopStories.bind(this); 71 | this.fetchSearchTopStories = this.fetchSearchTopStories.bind(this); 72 | this.onSearchChange = this.onSearchChange.bind(this); 73 | this.onSearchSubmit = this.onSearchSubmit.bind(this); 74 | this.onDismiss = this.onDismiss.bind(this); 75 | } 76 | 77 | needsToSearchTopStories(searchTerm) { 78 | return !this.state.results[searchTerm]; 79 | } 80 | 81 | setSearchTopStories(result) { 82 | const { hits, page } = result; 83 | this.setState(updateSearchTopStoriesState(hits, page)); 84 | } 85 | 86 | fetchSearchTopStories(searchTerm, page = 0) { 87 | this.setState({ isLoading: true }); 88 | 89 | axios(`${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${searchTerm}&${PARAM_PAGE}${page}&${PARAM_HPP}${DEFAULT_HPP}`) 90 | .then(result => this.setSearchTopStories(result.data)) 91 | .catch(error => this.setState({ error })); 92 | } 93 | 94 | componentDidMount() { 95 | const { searchTerm } = this.state; 96 | this.setState({ searchKey: searchTerm }); 97 | this.fetchSearchTopStories(searchTerm); 98 | } 99 | 100 | onSearchChange(event) { 101 | this.setState({ searchTerm: event.target.value }); 102 | } 103 | 104 | onSearchSubmit(event) { 105 | const { searchTerm } = this.state; 106 | this.setState({ searchKey: searchTerm }); 107 | 108 | if (this.needsToSearchTopStories(searchTerm)) { 109 | this.fetchSearchTopStories(searchTerm); 110 | } 111 | 112 | event.preventDefault(); 113 | } 114 | 115 | onDismiss(id) { 116 | const { searchKey, results } = this.state; 117 | const { hits, page } = results[searchKey]; 118 | 119 | const isNotId = item => item.objectID !== id; 120 | const updatedHits = hits.filter(isNotId); 121 | 122 | this.setState({ 123 | results: { 124 | ...results, 125 | [searchKey]: { hits: updatedHits, page } 126 | } 127 | }); 128 | } 129 | 130 | render() { 131 | const { 132 | searchTerm, 133 | results, 134 | searchKey, 135 | error, 136 | isLoading 137 | } = this.state; 138 | 139 | const page = ( 140 | results && 141 | results[searchKey] && 142 | results[searchKey].page 143 | ) || 0; 144 | 145 | const list = ( 146 | results && 147 | results[searchKey] && 148 | results[searchKey].hits 149 | ) || []; 150 | 151 | return ( 152 |
153 |
154 | 159 | Search 160 | 161 |
162 | { error 163 | ?
164 |

Something went wrong.

165 |
166 | : 170 | } 171 |
172 | this.fetchSearchTopStories(searchKey, page + 1)} 175 | > 176 | More 177 | 178 |
179 | 180 | ); 181 | } 182 | } 183 | 184 | const Search = ({ 185 | value, 186 | onChange, 187 | onSubmit, 188 | children 189 | }) => 190 | 191 | 196 | 199 | 200 | 201 | class Table extends Component { 202 | constructor(props) { 203 | super(props); 204 | 205 | this.state = { 206 | sortKey: 'NONE', 207 | isSortReverse: false, 208 | }; 209 | 210 | this.onSort = this.onSort.bind(this); 211 | } 212 | 213 | onSort(sortKey) { 214 | const isSortReverse = this.state.sortKey === sortKey && 215 | !this.state.isSortReverse; 216 | 217 | this.setState({ sortKey, isSortReverse }); 218 | } 219 | 220 | render() { 221 | const { 222 | list, 223 | onDismiss 224 | } = this.props; 225 | 226 | const { 227 | sortKey, 228 | isSortReverse, 229 | } = this.state; 230 | 231 | const sortedList = SORTS[sortKey](list); 232 | const reverseSortedList = isSortReverse 233 | ? sortedList.reverse() 234 | : sortedList; 235 | 236 | return ( 237 |
238 |
239 | 240 | 245 | Title 246 | 247 | 248 | 249 | 254 | Author 255 | 256 | 257 | 258 | 263 | Comments 264 | 265 | 266 | 267 | 272 | Points 273 | 274 | 275 | 276 | Archive 277 | 278 |
279 | {reverseSortedList.map(item => 280 |
281 | 282 | {item.title} 283 | 284 | 285 | {item.author} 286 | 287 | 288 | {item.num_comments} 289 | 290 | 291 | {item.points} 292 | 293 | 294 | 300 | 301 |
302 | )} 303 |
304 | ); 305 | } 306 | } 307 | 308 | const Sort = ({ 309 | sortKey, 310 | activeSortKey, 311 | onSort, 312 | children 313 | }) => { 314 | const sortClass = classNames( 315 | 'button-inline', 316 | { 'button-active': sortKey === activeSortKey } 317 | ); 318 | 319 | return ( 320 | 326 | ); 327 | } 328 | 329 | const Button = ({ 330 | onClick, 331 | className = '', 332 | children, 333 | }) => 334 | 341 | 342 | const Loading = () => 343 |
Loading ...
344 | 345 | const withLoading = (Component) => ({ isLoading, ...rest }) => 346 | isLoading 347 | ? 348 | : 349 | 350 | const ButtonWithLoading = withLoading(Button); 351 | 352 | export default App; 353 | 354 | export { 355 | Button, 356 | Search, 357 | Table, 358 | }; -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import renderer from 'react-test-renderer'; 4 | import Enzyme, { shallow } from 'enzyme'; 5 | import Adapter from 'enzyme-adapter-react-16'; 6 | import App, { Search, Button, Table } from './App'; 7 | 8 | Enzyme.configure({ adapter: new Adapter() }); 9 | 10 | describe('App', () => { 11 | 12 | it('renders without crashing', () => { 13 | const div = document.createElement('div'); 14 | ReactDOM.render(, div); 15 | ReactDOM.unmountComponentAtNode(div); 16 | }); 17 | 18 | test('has a valid snapshot', () => { 19 | const component = renderer.create( 20 | 21 | ); 22 | const tree = component.toJSON(); 23 | expect(tree).toMatchSnapshot(); 24 | }); 25 | 26 | }); 27 | 28 | describe('Search', () => { 29 | 30 | it('renders without crashing', () => { 31 | const div = document.createElement('div'); 32 | ReactDOM.render(Search, div); 33 | ReactDOM.unmountComponentAtNode(div); 34 | }); 35 | 36 | test('has a valid snapshot', () => { 37 | const component = renderer.create( 38 | Search 39 | ); 40 | const tree = component.toJSON(); 41 | expect(tree).toMatchSnapshot(); 42 | }); 43 | 44 | }); 45 | 46 | describe('Button', () => { 47 | 48 | it('renders without crashing', () => { 49 | const div = document.createElement('div'); 50 | ReactDOM.render(, div); 51 | ReactDOM.unmountComponentAtNode(div); 52 | }); 53 | 54 | test('has a valid snapshot', () => { 55 | const component = renderer.create( 56 | 57 | ); 58 | const tree = component.toJSON(); 59 | expect(tree).toMatchSnapshot(); 60 | }); 61 | 62 | }); 63 | 64 | describe('Table', () => { 65 | 66 | const props = { 67 | list: [ 68 | { title: '1', author: '1', num_comments: 1, points: 2, objectID: 'y' }, 69 | { title: '2', author: '2', num_comments: 1, points: 2, objectID: 'z' }, 70 | ], 71 | sortKey: 'TITLE', 72 | isSortReverse: false, 73 | }; 74 | 75 | it('renders without crashing', () => { 76 | const div = document.createElement('div'); 77 | ReactDOM.render(
, div); 78 | }); 79 | 80 | test('has a valid snapshot', () => { 81 | const component = renderer.create( 82 |
83 | ); 84 | const tree = component.toJSON(); 85 | expect(tree).toMatchSnapshot(); 86 | }); 87 | 88 | it('shows two items in list', () => { 89 | const element = shallow( 90 |
91 | ); 92 | 93 | expect(element.find('.table-row').length).toBe(2); 94 | }); 95 | 96 | }); -------------------------------------------------------------------------------- /src/__snapshots__/App.test.js.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`App has a valid snapshot 1`] = ` 4 |
7 |
10 |
13 | 18 | 23 | 24 |
25 |
28 |
31 | 38 | 45 | 46 | 53 | 60 | 61 | 68 | 75 | 76 | 83 | 90 | 91 | 98 | Archive 99 | 100 |
101 |
102 |
105 |
106 | Loading ... 107 |
108 |
109 |
110 | `; 111 | 112 | exports[`Button has a valid snapshot 1`] = ` 113 | 119 | `; 120 | 121 | exports[`Search has a valid snapshot 1`] = ` 122 | 123 | 126 | 131 | 132 | `; 133 | 134 | exports[`Table has a valid snapshot 1`] = ` 135 |
138 |
141 | 148 | 155 | 156 | 163 | 170 | 171 | 178 | 185 | 186 | 193 | 200 | 201 | 208 | Archive 209 | 210 |
211 |
214 | 221 | 222 | 1 223 | 224 | 225 | 232 | 1 233 | 234 | 241 | 1 242 | 243 | 250 | 2 251 | 252 | 259 | 266 | 267 |
268 |
271 | 278 | 279 | 2 280 | 281 | 282 | 289 | 2 290 | 291 | 298 | 1 299 | 300 | 307 | 2 308 | 309 | 316 | 323 | 324 |
325 |
326 | `; 327 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | color: #222; 3 | background: #f4f4f4; 4 | font: 400 14px CoreSans, Arial, sans-serif; 5 | } 6 | 7 | a { 8 | color: #222; 9 | } 10 | 11 | a:hover { 12 | text-decoration: underline; 13 | } 14 | 15 | ul, li { 16 | list-style: none; 17 | padding: 0; 18 | margin: 0; 19 | } 20 | 21 | input { 22 | padding: 10px; 23 | border-radius: 5px; 24 | margin-right: 10px; 25 | border: 1px solid #dddddd; 26 | } 27 | 28 | button { 29 | padding: 10px; 30 | border-radius: 5px; 31 | border: 1px solid #dddddd; 32 | background: transparent; 33 | color: #808080; 34 | cursor: pointer; 35 | } 36 | 37 | button:hover { 38 | color: #222; 39 | } -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | if (module.hot) { 10 | module.hot.accept(); 11 | } 12 | 13 | // If you want your app to work offline and load faster, you can change 14 | // unregister() to register() below. Note this comes with some pitfalls. 15 | // Learn more about service workers: https://bit.ly/CRA-PWA 16 | serviceWorker.unregister(); 17 | -------------------------------------------------------------------------------- /src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl) 104 | .then(response => { 105 | // Ensure service worker exists, and that we really are getting a JS file. 106 | const contentType = response.headers.get('content-type'); 107 | if ( 108 | response.status === 404 || 109 | (contentType != null && contentType.indexOf('javascript') === -1) 110 | ) { 111 | // No service worker found. Probably a different app. Reload the page. 112 | navigator.serviceWorker.ready.then(registration => { 113 | registration.unregister().then(() => { 114 | window.location.reload(); 115 | }); 116 | }); 117 | } else { 118 | // Service worker found. Proceed as normal. 119 | registerValidSW(swUrl, config); 120 | } 121 | }) 122 | .catch(() => { 123 | console.log( 124 | 'No internet connection found. App is running in offline mode.' 125 | ); 126 | }); 127 | } 128 | 129 | export function unregister() { 130 | if ('serviceWorker' in navigator) { 131 | navigator.serviceWorker.ready.then(registration => { 132 | registration.unregister(); 133 | }); 134 | } 135 | } 136 | --------------------------------------------------------------------------------