├── .vscode └── settings.json ├── public ├── robots.txt ├── favicon.ico ├── logo192.png ├── logo512.png ├── manifest.json └── index.html ├── src ├── index.css ├── App.test.js ├── toggle │ ├── actions.ts │ ├── reducer.ts │ └── Toggle.tsx ├── App.css ├── index.tsx ├── react-app-env.d.ts ├── helpers │ └── rootReducer.ts ├── movies │ ├── Movie.tsx │ ├── reducer.ts │ ├── MoviesList.tsx │ ├── actions.ts │ └── MovieDetail.tsx ├── App.tsx ├── logo.svg └── serviceWorker.js ├── .gitignore ├── tsconfig.json ├── package.json └── README.md /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.enabled": false 3 | } 4 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leomeloxp/lut-react-redux-typescript/HEAD/public/favicon.ico -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leomeloxp/lut-react-redux-typescript/HEAD/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leomeloxp/lut-react-redux-typescript/HEAD/public/logo512.png -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: sans-serif; 5 | background: #222; 6 | } 7 | -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /src/toggle/actions.ts: -------------------------------------------------------------------------------- 1 | import { EReduxActionTypes, IReduxBaseAction } from '../helpers/rootReducer'; 2 | 3 | export interface IReduxToggleMessageAction extends IReduxBaseAction { 4 | type: EReduxActionTypes.TOGGLE_MESSAGE; 5 | } 6 | 7 | export function toggleMessage(): IReduxToggleMessageAction { 8 | return { 9 | type: EReduxActionTypes.TOGGLE_MESSAGE 10 | }; 11 | } 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-header { 6 | background-color: #111; 7 | height: 60px; 8 | padding: 20px; 9 | color: white; 10 | } 11 | 12 | .App-title { 13 | font-size: 1.5em; 14 | } 15 | 16 | .App-intro { 17 | font-size: large; 18 | } 19 | 20 | @keyframes App-logo-spin { 21 | from { transform: rotate(0deg); } 22 | to { transform: rotate(360deg); } 23 | } 24 | 25 | h3 { 26 | color: #FFF; 27 | } -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 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 you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | declare module 'react-overdrive' { 4 | import { Component, CSSProperties } from 'react'; 5 | export interface Props { 6 | id: string; 7 | duration?: number; 8 | easing?: string; 9 | element?: string; 10 | animationDelay?: number; 11 | onAnimationEnd?: () => void; 12 | style?: CSSProperties; 13 | } 14 | export interface State { 15 | loading: boolean; 16 | } 17 | export default class Overdrive extends Component {} 18 | } 19 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "esnext", 4 | "allowJs": true, 5 | "esModuleInterop": true, 6 | "allowSyntheticDefaultImports": true, 7 | "strict": true, 8 | "forceConsistentCasingInFileNames": true, 9 | "module": "esnext", 10 | "moduleResolution": "node", 11 | "resolveJsonModule": true, 12 | "isolatedModules": true, 13 | "noEmit": true, 14 | "jsx": "react", 15 | "lib": [ 16 | "dom", 17 | "dom.iterable", 18 | "esnext" 19 | ], 20 | "skipLibCheck": true 21 | }, 22 | "include": [ 23 | "src" 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /src/helpers/rootReducer.ts: -------------------------------------------------------------------------------- 1 | import { combineReducers } from 'redux'; 2 | import movies from '../movies/reducer'; 3 | import toggle from '../toggle/reducer'; 4 | 5 | export enum EReduxActionTypes { 6 | GET_MOVIE = 'GET_MOVIE', 7 | GET_MOVIES = 'GET_MOVIES', 8 | RESET_MOVIE = 'RESET_MOVIE', 9 | TOGGLE_MESSAGE = 'TOGGLE_MESSAGE' 10 | } 11 | 12 | export interface IReduxBaseAction { 13 | type: EReduxActionTypes; 14 | } 15 | 16 | const rootReducer = combineReducers({ 17 | toggle, 18 | movies 19 | }); 20 | 21 | export type AppState = ReturnType; 22 | 23 | export default rootReducer; 24 | -------------------------------------------------------------------------------- /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 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /src/movies/Movie.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import Overdrive from 'react-overdrive'; 3 | import { Link } from 'react-router-dom'; 4 | import styled from 'styled-components'; 5 | import { IMovie } from './reducer'; 6 | 7 | const POSTER_PATH = 'http://image.tmdb.org/t/p/w154'; 8 | 9 | const Movie = ({ movie }: { movie: IMovie }) => ( 10 | 11 | 12 | 13 | 14 | 15 | ); 16 | 17 | export default Movie; 18 | 19 | export const Poster = styled.img` 20 | box-shadow: 0 0 35px black; 21 | `; 22 | -------------------------------------------------------------------------------- /src/toggle/reducer.ts: -------------------------------------------------------------------------------- 1 | import { EReduxActionTypes } from '../helpers/rootReducer'; 2 | import { IReduxToggleMessageAction } from './actions'; 3 | 4 | export interface IReduxMessageState { 5 | messageVisibility: boolean; 6 | } 7 | 8 | const initialState: IReduxMessageState = { 9 | messageVisibility: false 10 | }; 11 | 12 | export default function(state: IReduxMessageState = initialState, action: IReduxToggleMessageAction) { 13 | const { type } = action; 14 | switch (type) { 15 | case EReduxActionTypes.TOGGLE_MESSAGE: 16 | return { ...state, messageVisibility: !state.messageVisibility }; 17 | default: 18 | return state; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/toggle/Toggle.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { connect } from 'react-redux'; 3 | import { bindActionCreators, Dispatch } from 'redux'; 4 | import { AppState } from '../helpers/rootReducer'; 5 | import { IReduxToggleMessageAction, toggleMessage } from './actions'; 6 | 7 | const Toggle: React.FC & ReturnType> = ({ 8 | messageVisibility, 9 | toggleMessage 10 | }) => ( 11 |
12 | {messageVisibility &&

You will be seeing this if redux action is toggled

} 13 | 14 |
15 | ); 16 | 17 | const mapStateToProps = (state: AppState) => ({ 18 | messageVisibility: state.toggle.messageVisibility 19 | }); 20 | 21 | const mapDispatchToProps = (dispatch: Dispatch) => 22 | bindActionCreators({ toggleMessage }, dispatch); 23 | 24 | export default connect( 25 | mapStateToProps, 26 | mapDispatchToProps 27 | )(Toggle); 28 | -------------------------------------------------------------------------------- /src/movies/reducer.ts: -------------------------------------------------------------------------------- 1 | import { EReduxActionTypes } from '../helpers/rootReducer'; 2 | import { IReduxGetMovieAction, IReduxGetMoviesAction, IReduxResetMovieAction } from './actions'; 3 | 4 | export interface IMovie { 5 | backdrop_path: string; 6 | id: string; 7 | overview: string; 8 | poster_path: string; 9 | release_date: string; 10 | title: string; 11 | } 12 | 13 | export interface IReduxMoviesState { 14 | movies: IMovie[]; 15 | moviesLoaded: boolean; 16 | moviesLoadedAt?: number; 17 | movie?: IMovie; 18 | movieLoaded: boolean; 19 | } 20 | 21 | const initialState: IReduxMoviesState = { 22 | movies: [], 23 | moviesLoaded: false, 24 | moviesLoadedAt: undefined, 25 | movie: undefined, 26 | movieLoaded: false 27 | }; 28 | 29 | type TMoviesReducerActions = IReduxGetMoviesAction | IReduxGetMovieAction | IReduxResetMovieAction; 30 | 31 | export default function(state: IReduxMoviesState = initialState, action: TMoviesReducerActions) { 32 | switch (action.type) { 33 | case EReduxActionTypes.GET_MOVIES: 34 | return { ...state, movies: action.data, moviesLoaded: true, moviesLoadedAt: Date.now() }; 35 | case EReduxActionTypes.GET_MOVIE: 36 | return { ...state, movie: action.data, movieLoaded: true }; 37 | case EReduxActionTypes.RESET_MOVIE: 38 | return { ...state, movie: undefined, movieLoaded: false }; 39 | default: 40 | return state; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/App.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Provider } from 'react-redux'; 3 | import { BrowserRouter as Router, Link, Route, Switch } from 'react-router-dom'; 4 | import { applyMiddleware, createStore } from 'redux'; 5 | import { composeWithDevTools } from 'redux-devtools-extension'; 6 | import { load, save } from 'redux-localstorage-simple'; 7 | import reduxLogger from 'redux-logger'; 8 | import thunk from 'redux-thunk'; 9 | import './App.css'; 10 | import rootReducer from './helpers/rootReducer'; 11 | import logo from './logo.svg'; 12 | import MovieDetail from './movies/MovieDetail'; 13 | import MoviesList from './movies/MoviesList'; 14 | import Toggle from './toggle/Toggle'; 15 | 16 | const middleware = [reduxLogger, thunk]; 17 | 18 | const store = createStore(rootReducer, load(), composeWithDevTools(applyMiddleware(...middleware, save()))); 19 | 20 | const App = () => ( 21 | 22 | 23 |
24 |
25 | 26 | logo 27 | 28 |
29 | 30 | 31 | 32 | 33 | 34 |
35 |
36 |
37 | ); 38 | 39 | export default App; 40 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rrfe", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "react": "^16.9.0", 7 | "react-dom": "^16.9.0", 8 | "react-overdrive": "0.0.10", 9 | "react-redux": "^7.1.0", 10 | "react-router-dom": "^5.0.1", 11 | "react-scripts": "3.1.1", 12 | "redux": "^4.0.4", 13 | "redux-devtools-extension": "^2.13.8", 14 | "redux-localstorage-simple": "^2.1.6", 15 | "redux-logger": "^3.0.6", 16 | "redux-thunk": "^2.3.0", 17 | "styled-components": "^4.3.2" 18 | }, 19 | "scripts": { 20 | "start": "react-scripts start", 21 | "build": "react-scripts build", 22 | "test": "react-scripts test", 23 | "eject": "react-scripts eject" 24 | }, 25 | "eslintConfig": { 26 | "extends": "react-app" 27 | }, 28 | "browserslist": { 29 | "production": [ 30 | ">0.2%", 31 | "not dead", 32 | "not op_mini all" 33 | ], 34 | "development": [ 35 | "last 1 chrome version", 36 | "last 1 firefox version", 37 | "last 1 safari version" 38 | ] 39 | }, 40 | "devDependencies": { 41 | "@types/node": "^12.7.2", 42 | "@types/react": "^16.9.2", 43 | "@types/react-dom": "^16.9.0", 44 | "@types/react-redux": "^7.1.2", 45 | "@types/react-router-dom": "^4.3.5", 46 | "@types/redux-logger": "^3.0.7", 47 | "@types/styled-components": "^4.1.18", 48 | "typescript": "^3.5.3" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/movies/MoviesList.tsx: -------------------------------------------------------------------------------- 1 | import React, { PureComponent } from 'react'; 2 | import { connect } from 'react-redux'; 3 | import { AnyAction, bindActionCreators, Dispatch } from 'redux'; 4 | import styled from 'styled-components'; 5 | import { AppState } from '../helpers/rootReducer'; 6 | import { getMovies } from './actions'; 7 | import Movie from './Movie'; 8 | import { IMovie } from './reducer'; 9 | 10 | class MoviesList extends PureComponent & ReturnType, {}> { 11 | public componentDidMount() { 12 | const { getMovies, isLoaded, moviesLoadedAt } = this.props; 13 | const oneHour = 60 * 60 * 1000; 14 | if (!isLoaded || !moviesLoadedAt || Date.now() - moviesLoadedAt > oneHour) { 15 | getMovies(); 16 | //this.props.getMovies(); 17 | } 18 | } 19 | 20 | public render() { 21 | const { movies, isLoaded } = this.props; 22 | if (!isLoaded) { 23 | return

Loading...

; 24 | } 25 | return ( 26 | 27 | {movies.map((movie: IMovie) => ( 28 | 29 | ))} 30 | 31 | ); 32 | } 33 | } 34 | 35 | const mapStateToProps = (state: AppState) => ({ 36 | movies: state.movies.movies, 37 | isLoaded: state.movies.moviesLoaded, 38 | moviesLoadedAt: state.movies.moviesLoadedAt 39 | }); 40 | 41 | const mapDispatchToProps = (dispatch: Dispatch) => 42 | bindActionCreators( 43 | { 44 | getMovies 45 | }, 46 | dispatch 47 | ); 48 | 49 | export default connect( 50 | mapStateToProps, 51 | mapDispatchToProps 52 | )(MoviesList); 53 | 54 | const MovieGrid = styled.div` 55 | display: grid; 56 | padding: 1rem; 57 | grid-template-columns: repeat(6, 1fr); 58 | grid-row-gap: 1rem; 59 | `; 60 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Level Up Tutorials - React and Redux for Everyone (Typescript Edition) 2 | 3 | This is a [Typescript](https://www.typescriptlang.org/) implementation of Level Up Tutorials Movie Database using React and Redux. 4 | 5 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app), check their repo to learn more about it. 6 | 7 | You can see the videos for the course that builds this application at [Level Up Tutorials](https://www.leveluptutorials.com/tutorials/redux-and-react-for-everyone/). 8 | 9 | ## Getting started 10 | 11 | - Clone this repo 12 | - `git checkout end-of-9 # optional, in case you want to re-write the TS code yourself` 13 | - `npm install` 14 | - `npm start` 15 | 16 | See the Create React App docs for more details on what else can be done with this app. 17 | 18 | ## Notes 19 | 20 | As this project was created using Typescript instead of plain JS, I took some creative liberties and altered the code ever so slightly from what Scott originally wrote for the course. I still tried to keep as much of the code like the original as possible, which means there could be some minor bits which are not as nice Typescript code as it can be written. 21 | 22 | The code is organised as one commit per video from video number 9 (where most of the actual project starts). You can check out each of these checkpoints as a git tag for easier access. 23 | 24 | If you find anything that is not inline with the course content or you believe to be wrong, feel free to open an issue or submit a PR. 25 | 26 | If you have any questions, wanna say thanks or chat more about TS or code in general, you can find me on Twitter ([@leomeloxp](https://twitter.com/leomeloxp)), my website [leomeloxp.dev](https://leomeloxp.dev) and on LUT's Slack group (see [LUT's site](https://www.leveluptutorials.com/) for the link to their Slack). 27 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/movies/actions.ts: -------------------------------------------------------------------------------- 1 | import { ThunkAction, ThunkDispatch } from 'redux-thunk'; 2 | import { EReduxActionTypes, IReduxBaseAction } from '../helpers/rootReducer'; 3 | import { IMovie, IReduxMoviesState } from './reducer'; 4 | 5 | export interface IReduxGetMoviesAction extends IReduxBaseAction { 6 | type: EReduxActionTypes.GET_MOVIES; 7 | data: IMovie[]; 8 | } 9 | export interface IReduxGetMovieAction extends IReduxBaseAction { 10 | type: EReduxActionTypes.GET_MOVIE; 11 | data: IMovie; 12 | } 13 | 14 | export interface IReduxResetMovieAction extends IReduxBaseAction { 15 | type: EReduxActionTypes.RESET_MOVIE; 16 | } 17 | 18 | export function getMovies(): ThunkAction< 19 | Promise, 20 | IReduxMoviesState, 21 | undefined, 22 | IReduxGetMoviesAction 23 | > { 24 | return async (dispatch: ThunkDispatch) => { 25 | const res = await fetch( 26 | 'https://api.themoviedb.org/3/discover/movie?api_key=65e043c24785898be00b4abc12fcdaae&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1' 27 | ); 28 | const movies = await res.json(); 29 | 30 | return dispatch({ 31 | type: EReduxActionTypes.GET_MOVIES, 32 | data: movies.results 33 | }); 34 | }; 35 | } 36 | 37 | export function getMovie( 38 | id: string 39 | ): ThunkAction, IReduxMoviesState, undefined, IReduxGetMovieAction> { 40 | return async (dispatch: ThunkDispatch) => { 41 | const res = await fetch( 42 | `https://api.themoviedb.org/3/movie/${id}?api_key=65e043c24785898be00b4abc12fcdaae&language=en-US` 43 | ); 44 | const movie = await res.json(); 45 | return dispatch({ 46 | type: EReduxActionTypes.GET_MOVIE, 47 | data: movie 48 | }); 49 | }; 50 | } 51 | 52 | export function resetMovie(): IReduxResetMovieAction { 53 | return { 54 | type: EReduxActionTypes.RESET_MOVIE 55 | }; 56 | } 57 | -------------------------------------------------------------------------------- /src/movies/MovieDetail.tsx: -------------------------------------------------------------------------------- 1 | /* eslint react/no-did-mount-set-state: 0 */ 2 | import React, { Component } from 'react'; 3 | import Overdrive from 'react-overdrive'; 4 | import { connect } from 'react-redux'; 5 | import { AnyAction, bindActionCreators, Dispatch } from 'redux'; 6 | import styled from 'styled-components'; 7 | import { AppState } from '../helpers/rootReducer'; 8 | import { getMovie, resetMovie } from './actions'; 9 | import { Poster } from './Movie'; 10 | 11 | const POSTER_PATH = 'http://image.tmdb.org/t/p/w154'; 12 | const BACKDROP_PATH = 'http://image.tmdb.org/t/p/w1280'; 13 | 14 | class MovieDetail extends Component & ReturnType, {}> { 15 | public componentDidMount() { 16 | const { match } = this.props as any; 17 | const { getMovie } = this.props; 18 | 19 | getMovie(match.params.id); 20 | //this.props.getMovie(match.params.id); 21 | } 22 | 23 | public componentWillUnmount() { 24 | this.props.resetMovie(); 25 | } 26 | 27 | public render() { 28 | const { movie } = this.props; 29 | console.log({ movie }); 30 | 31 | if (!movie || !movie.id) { 32 | return null; 33 | } 34 | 35 | return ( 36 | 37 | 38 | 39 | 40 | 41 |
42 | {movie.title ?

Hello

:

Hi

} 43 |

{movie.title}

44 |

{movie.release_date}

45 |

{movie.overview}

46 |
47 |
48 |
49 | ); 50 | } 51 | } 52 | 53 | const mapStateToProps = (state: AppState) => ({ 54 | movie: state.movies.movie, 55 | isLoaded: state.movies.movieLoaded 56 | }); 57 | 58 | const mapDispatchToProps = (dispatch: Dispatch) => 59 | bindActionCreators( 60 | { 61 | getMovie, 62 | resetMovie 63 | }, 64 | dispatch 65 | ); 66 | 67 | export default connect( 68 | mapStateToProps, 69 | mapDispatchToProps 70 | )(MovieDetail); 71 | 72 | const MovieWrapper = styled.div<{ backdrop: string }>` 73 | position: relative; 74 | padding-top: 50vh; 75 | background: url(${props => props.backdrop}) no-repeat; 76 | background-size: cover; 77 | `; 78 | 79 | const MovieInfo = styled.div` 80 | background: white; 81 | text-align: left; 82 | padding: 2rem 10%; 83 | display: flex; 84 | > div { 85 | margin-left: 20px; 86 | } 87 | img { 88 | position: relative; 89 | top: -5rem; 90 | } 91 | `; 92 | -------------------------------------------------------------------------------- /src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /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(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/) 19 | ); 20 | 21 | export function register(config) { 22 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 23 | // The URL constructor is available in all browsers that support SW. 24 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 25 | if (publicUrl.origin !== window.location.origin) { 26 | // Our service worker won't work if PUBLIC_URL is on a different origin 27 | // from what our page is served on. This might happen if a CDN is used to 28 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 29 | return; 30 | } 31 | 32 | window.addEventListener('load', () => { 33 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 34 | 35 | if (isLocalhost) { 36 | // This is running on localhost. Let's check if a service worker still exists or not. 37 | checkValidServiceWorker(swUrl, config); 38 | 39 | // Add some additional logging to localhost, pointing developers to the 40 | // service worker/PWA documentation. 41 | navigator.serviceWorker.ready.then(() => { 42 | console.log( 43 | 'This web app is being served cache-first by a service ' + 44 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 45 | ); 46 | }); 47 | } else { 48 | // Is not localhost. Just register service worker 49 | registerValidSW(swUrl, config); 50 | } 51 | }); 52 | } 53 | } 54 | 55 | function registerValidSW(swUrl, config) { 56 | navigator.serviceWorker 57 | .register(swUrl) 58 | .then(registration => { 59 | registration.onupdatefound = () => { 60 | const installingWorker = registration.installing; 61 | if (installingWorker == null) { 62 | return; 63 | } 64 | installingWorker.onstatechange = () => { 65 | if (installingWorker.state === 'installed') { 66 | if (navigator.serviceWorker.controller) { 67 | // At this point, the updated precached content has been fetched, 68 | // but the previous service worker will still serve the older 69 | // content until all client tabs are closed. 70 | console.log( 71 | 'New content is available and will be used when all ' + 72 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 73 | ); 74 | 75 | // Execute callback 76 | if (config && config.onUpdate) { 77 | config.onUpdate(registration); 78 | } 79 | } else { 80 | // At this point, everything has been precached. 81 | // It's the perfect time to display a 82 | // "Content is cached for offline use." message. 83 | console.log('Content is cached for offline use.'); 84 | 85 | // Execute callback 86 | if (config && config.onSuccess) { 87 | config.onSuccess(registration); 88 | } 89 | } 90 | } 91 | }; 92 | }; 93 | }) 94 | .catch(error => { 95 | console.error('Error during service worker registration:', error); 96 | }); 97 | } 98 | 99 | function checkValidServiceWorker(swUrl, config) { 100 | // Check if the service worker can be found. If it can't reload the page. 101 | fetch(swUrl) 102 | .then(response => { 103 | // Ensure service worker exists, and that we really are getting a JS file. 104 | const contentType = response.headers.get('content-type'); 105 | if (response.status === 404 || (contentType != null && contentType.indexOf('javascript') === -1)) { 106 | // No service worker found. Probably a different app. Reload the page. 107 | navigator.serviceWorker.ready.then(registration => { 108 | registration.unregister().then(() => { 109 | window.location.reload(); 110 | }); 111 | }); 112 | } else { 113 | // Service worker found. Proceed as normal. 114 | registerValidSW(swUrl, config); 115 | } 116 | }) 117 | .catch(() => { 118 | console.log('No internet connection found. App is running in offline mode.'); 119 | }); 120 | } 121 | 122 | export function unregister() { 123 | if ('serviceWorker' in navigator) { 124 | navigator.serviceWorker.ready.then(registration => { 125 | registration.unregister(); 126 | }); 127 | } 128 | } 129 | --------------------------------------------------------------------------------