59 | );
60 | }
61 |
62 | export default App;
63 |
--------------------------------------------------------------------------------
/src/features/spotifyExample/spotifyExampleSlice.ts:
--------------------------------------------------------------------------------
1 | import { createSlice, PayloadAction } from '@reduxjs/toolkit';
2 | import { AppThunk, RootState } from '../../app/store';
3 | import {
4 | setLoggedIn
5 | } from '../../features/authorization/authorizationSlice';
6 |
7 | interface SpotifyExampleState {
8 | displayName: string,
9 | product: string
10 | }
11 |
12 | const initialState: SpotifyExampleState = {
13 | displayName: '',
14 | product: '',
15 | };
16 |
17 | export const spotifyexampleSlice = createSlice({
18 | name: 'spotifyExample',
19 | initialState,
20 | reducers: {
21 | setDisplayName: (state, action: PayloadAction) => {
22 | state.displayName = action.payload;
23 | },
24 | setProduct: (state, action: PayloadAction) => {
25 | state.product = action.payload;
26 | },
27 | },
28 | });
29 |
30 | export const { setDisplayName, setProduct } = spotifyexampleSlice.actions;
31 |
32 | export const selectDisplayName = (state: RootState) => state.spotifyExample.displayName;
33 | export const selectProduct = (state: RootState) => state.spotifyExample.product;
34 |
35 | export const setUserProfileAsync = (accessToken: string): AppThunk => dispatch => {
36 | const myHeaders = new Headers();
37 | myHeaders.append('Authorization', 'Bearer ' + accessToken);
38 |
39 | fetch('https://api.spotify.com/v1/me', {
40 | method: 'GET',
41 | headers: myHeaders,
42 | }).then(response => response.json())
43 | .then((data) => {
44 | console.log(data);
45 | dispatch(setDisplayName(data.display_name ? data.display_name : data.id));
46 | dispatch(setProduct(data.product));
47 | }).catch((error) => {
48 | console.log(error);
49 | if (error instanceof XMLHttpRequest) {
50 | if (error.status === 401) {
51 | dispatch(setLoggedIn(false));
52 | }
53 | }
54 | });
55 | };
56 |
57 | export default spotifyexampleSlice.reducer;
58 |
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React Redux App
28 |
29 |
30 |
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/src/features/counter/counterSlice.ts:
--------------------------------------------------------------------------------
1 | import { createSlice, PayloadAction } from '@reduxjs/toolkit';
2 | import { AppThunk, RootState } from '../../app/store';
3 |
4 | interface CounterState {
5 | value: number;
6 | }
7 |
8 | const initialState: CounterState = {
9 | value: 0,
10 | };
11 |
12 | export const counterSlice = createSlice({
13 | name: 'counter',
14 | initialState,
15 | reducers: {
16 | increment: state => {
17 | // Redux Toolkit allows us to write "mutating" logic in reducers. It
18 | // doesn't actually mutate the state because it uses the Immer library,
19 | // which detects changes to a "draft state" and produces a brand new
20 | // immutable state based off those changes
21 | state.value += 1;
22 | },
23 | decrement: state => {
24 | state.value -= 1;
25 | },
26 | // Use the PayloadAction type to declare the contents of `action.payload`
27 | incrementByAmount: (state, action: PayloadAction) => {
28 | state.value += action.payload;
29 | },
30 | },
31 | });
32 |
33 | export const { increment, decrement, incrementByAmount } = counterSlice.actions;
34 |
35 | // The function below is called a thunk and allows us to perform async logic. It
36 | // can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This
37 | // will call the thunk with the `dispatch` function as the first argument. Async
38 | // code can then be executed and other actions can be dispatched
39 | export const incrementAsync = (amount: number): AppThunk => dispatch => {
40 | setTimeout(() => {
41 | dispatch(incrementByAmount(amount));
42 | }, 1000);
43 | };
44 |
45 | // The function below is called a selector and allows us to select a value from
46 | // the state. Selectors can also be defined inline where they're used instead of
47 | // in the slice file. For example: `useSelector((state: RootState) => state.counter.value)`
48 | export const selectCount = (state: RootState) => state.counter.value;
49 |
50 | export default counterSlice.reducer;
51 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## ⚠️ ARCHIVED - NOT RECOMMENDED
2 |
3 | This repository is archived and I do not recommend using this approach anymore. My recommendation as of 2025 for modern React applications:
4 |
5 | - **For API handling**: Use [TanStack Query](https://tanstack.com/query)
6 | - **For global state management**: Use [Zustand](https://github.com/pmndrs/zustand)
7 |
8 | ---
9 |
10 | A React app template written in Typescript with Redux store and OAuth 2.0. Does not require any server running. The authorization example in the template is for the [Spotify Web API](https://developer.spotify.com/documentation/web-api/) but can be used for any service with the same authorization flow.
11 |
12 | Tutorial on Medium: [medium.com/@oskarasplin/create-a-react-app-with-typescript-redux-and-oauth-2-0-7f62d57890df](https://medium.com/@oskarasplin/create-a-react-app-with-typescript-redux-and-oauth-2-0-7f62d57890df)
13 |
14 | ### Use with Spotify
15 | Register your app [here](https://developer.spotify.com/documentation/web-api) to retrieve a client ID and add http://localhost:3000 to Redirect URIs in the app settings.
16 |
17 | ### Use with other services
18 | Edit the files in src/features/spotifyExample/ to fit your scenario. Or remove the example by removing `` from App.tsx and `spotifyExample: spotifyExampleReducer` from store.ts.
19 |
20 | ## Try it out
21 |
22 | 1. Clone the repository
23 | 2. Navigate to the root directory of the repository
24 | 3. `npm install`
25 | 4. `cp .env.local_EXAMPLE .env.local` and fill `REACT_APP_SPOTIFY_CLIENT_ID` with your client id
26 | 5. `npm start`
27 |
28 | ### Template built with
29 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app), using the official Typescript and Redux template: https://github.com/reduxjs/cra-template-redux-typescript
30 |
31 | # Create React App standard build notes:
32 |
33 | ## Available Scripts
34 |
35 | In the project directory, you can run:
36 |
37 | ### `npm start`
38 |
39 | Runs the app in the development mode.
40 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
41 |
42 | The page will reload if you make edits.
43 | You will also see any lint errors in the console.
44 |
45 | ### `npm test`
46 |
47 | Launches the test runner in the interactive watch mode.
48 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
49 |
50 | ### `npm run build`
51 |
52 | Builds the app for production to the `build` folder.
53 | It correctly bundles React in production mode and optimizes the build for the best performance.
54 |
55 | The build is minified and the filenames include the hashes.
56 | Your app is ready to be deployed!
57 |
58 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
59 |
60 | ### `npm run eject`
61 |
62 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
63 |
64 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
65 |
66 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
67 |
68 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
69 |
70 | ## Learn More
71 |
72 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
73 |
74 | To learn React, check out the [React documentation](https://reactjs.org/).
75 |
--------------------------------------------------------------------------------
/src/serviceWorker.ts:
--------------------------------------------------------------------------------
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.0/8 are 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 | type Config = {
24 | onSuccess?: (registration: ServiceWorkerRegistration) => void;
25 | onUpdate?: (registration: ServiceWorkerRegistration) => void;
26 | };
27 |
28 | export function register(config?: Config) {
29 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
30 | // The URL constructor is available in all browsers that support SW.
31 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
32 | if (publicUrl.origin !== window.location.origin) {
33 | // Our service worker won't work if PUBLIC_URL is on a different origin
34 | // from what our page is served on. This might happen if a CDN is used to
35 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
36 | return;
37 | }
38 |
39 | window.addEventListener('load', () => {
40 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
41 |
42 | if (isLocalhost) {
43 | // This is running on localhost. Let's check if a service worker still exists or not.
44 | checkValidServiceWorker(swUrl, config);
45 |
46 | // Add some additional logging to localhost, pointing developers to the
47 | // service worker/PWA documentation.
48 | navigator.serviceWorker.ready.then(() => {
49 | console.log(
50 | 'This web app is being served cache-first by a service ' +
51 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
52 | );
53 | });
54 | } else {
55 | // Is not localhost. Just register service worker
56 | registerValidSW(swUrl, config);
57 | }
58 | });
59 | }
60 | }
61 |
62 | function registerValidSW(swUrl: string, config?: Config) {
63 | navigator.serviceWorker
64 | .register(swUrl)
65 | .then(registration => {
66 | registration.onupdatefound = () => {
67 | const installingWorker = registration.installing;
68 | if (installingWorker == null) {
69 | return;
70 | }
71 | installingWorker.onstatechange = () => {
72 | if (installingWorker.state === 'installed') {
73 | if (navigator.serviceWorker.controller) {
74 | // At this point, the updated precached content has been fetched,
75 | // but the previous service worker will still serve the older
76 | // content until all client tabs are closed.
77 | console.log(
78 | 'New content is available and will be used when all ' +
79 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
80 | );
81 |
82 | // Execute callback
83 | if (config && config.onUpdate) {
84 | config.onUpdate(registration);
85 | }
86 | } else {
87 | // At this point, everything has been precached.
88 | // It's the perfect time to display a
89 | // "Content is cached for offline use." message.
90 | console.log('Content is cached for offline use.');
91 |
92 | // Execute callback
93 | if (config && config.onSuccess) {
94 | config.onSuccess(registration);
95 | }
96 | }
97 | }
98 | };
99 | };
100 | })
101 | .catch(error => {
102 | console.error('Error during service worker registration:', error);
103 | });
104 | }
105 |
106 | function checkValidServiceWorker(swUrl: string, config?: Config) {
107 | // Check if the service worker can be found. If it can't reload the page.
108 | fetch(swUrl, {
109 | headers: { 'Service-Worker': 'script' },
110 | })
111 | .then(response => {
112 | // Ensure service worker exists, and that we really are getting a JS file.
113 | const contentType = response.headers.get('content-type');
114 | if (
115 | response.status === 404 ||
116 | (contentType != null && contentType.indexOf('javascript') === -1)
117 | ) {
118 | // No service worker found. Probably a different app. Reload the page.
119 | navigator.serviceWorker.ready.then(registration => {
120 | registration.unregister().then(() => {
121 | window.location.reload();
122 | });
123 | });
124 | } else {
125 | // Service worker found. Proceed as normal.
126 | registerValidSW(swUrl, config);
127 | }
128 | })
129 | .catch(() => {
130 | console.log(
131 | 'No internet connection found. App is running in offline mode.'
132 | );
133 | });
134 | }
135 |
136 | export function unregister() {
137 | if ('serviceWorker' in navigator) {
138 | navigator.serviceWorker.ready
139 | .then(registration => {
140 | registration.unregister();
141 | })
142 | .catch(error => {
143 | console.error(error.message);
144 | });
145 | }
146 | }
147 |
--------------------------------------------------------------------------------