├── .gitignore
├── .prettierrc
├── README.md
├── package-lock.json
├── package.json
├── public
├── Redux.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
└── src
├── App.js
├── App.test.js
├── components
├── addTodo
│ └── index.js
├── colorModeSwitcher
│ └── index.js
├── errorMessage
│ └── index.js
├── layout
│ └── index.js
└── todoList
│ └── index.js
├── index.js
├── pages
├── homepage
│ └── index.js
└── index.js
├── redux
├── slices
│ └── todoSlice.js
└── store
│ └── index.js
├── reportWebVitals.js
├── serviceWorker.js
├── setupTests.js
└── test-utils.js
/.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 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "arrowParens": "avoid",
3 | "trailingComma": "es5",
4 | "singleQuote": true,
5 | "semi": true
6 | }
7 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Redux Toolkit Example
2 |
3 | This app was created to showcase Redux Toolkit at React Online Meetup.
4 |
5 | ## Slide
6 |
7 | - [Theory](https://redux-theory-deck.netlify.app/)
8 | - [Code](https://redux-code-presentation.netlify.app/0)
9 |
10 | ## How to use this App
11 |
12 | The master branch is site with Redux & Exercise. You can try the exercise on [CodeSandbox](https://codesandbox.io/s/devtghoshredux-toolkit-example-wb1j2?file=/src/components/todoList/index.js)
13 |
14 | The answer branch is the solution to the checkbox exercise.
15 |
16 | The base branch is the site without ay of the Redux functionality. Try recreating the redux functionality on [CodeSandbox](https://codesandbox.io/s/practical-sutherland-xlln7)
17 |
18 | ## How to run this App
19 |
20 | - Install `git`
21 | - Install `node version 12.18` and `npm`
22 | - Clone the git repo `git clone https://github.com/DevTGhosh/redux-toolkit-example`
23 | - Run `npm install` to download the necessary node modules
24 | - Run `npm run start`
25 | - View the App in your browser at `localhost:3000`
26 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "redux-toolkit",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@chakra-ui/core": "^1.0.0-rc.2",
7 | "@chakra-ui/icons": "^1.0.0-rc.3",
8 | "@chakra-ui/theme": "^1.0.0-rc.2",
9 | "@chakra-ui/theme-tools": "^1.0.0-rc.2",
10 | "@reduxjs/toolkit": "^1.4.0",
11 | "@testing-library/jest-dom": "^5.11.4",
12 | "@testing-library/react": "^10.4.9",
13 | "@testing-library/user-event": "^12.1.3",
14 | "axios": "^0.20.0",
15 | "react": "^16.13.1",
16 | "react-dom": "^16.13.1",
17 | "react-icons": "^3.11.0",
18 | "react-redux": "^7.2.1",
19 | "react-scripts": "3.4.3",
20 | "redux": "^4.0.5",
21 | "web-vitals": "^0.2.4"
22 | },
23 | "scripts": {
24 | "start": "react-scripts start",
25 | "build": "react-scripts build",
26 | "test": "react-scripts test",
27 | "eject": "react-scripts eject"
28 | },
29 | "eslintConfig": {
30 | "extends": "react-app"
31 | },
32 | "browserslist": {
33 | "production": [
34 | ">0.2%",
35 | "not dead",
36 | "not op_mini all"
37 | ],
38 | "development": [
39 | "last 1 chrome version",
40 | "last 1 firefox version",
41 | "last 1 safari version"
42 | ]
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/public/Redux.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DevTGhosh/redux-toolkit-example/b38d49245a2d3520212c94554e492321538e0589/public/Redux.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | Redux Toolkit Example
28 |
29 |
30 |
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DevTGhosh/redux-toolkit-example/b38d49245a2d3520212c94554e492321538e0589/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DevTGhosh/redux-toolkit-example/b38d49245a2d3520212c94554e492321538e0589/public/logo512.png
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { ChakraProvider } from '@chakra-ui/core';
3 | import theme from '@chakra-ui/theme';
4 | import Index from './pages';
5 |
6 | function App() {
7 | return (
8 |
9 |
10 |
11 | );
12 | }
13 |
14 | export default App;
15 |
--------------------------------------------------------------------------------
/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { screen } from '@testing-library/react';
3 | import { render } from './test-utils';
4 | import App from './App';
5 |
6 | test('renders learn react link', () => {
7 | render();
8 | const linkElement = screen.getByText(/learn chakra/i);
9 | expect(linkElement).toBeInTheDocument();
10 | });
11 |
--------------------------------------------------------------------------------
/src/components/addTodo/index.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 | import { useDispatch } from 'react-redux';
3 | import { Button, Input, HStack } from '@chakra-ui/core';
4 | import { AddIcon } from '@chakra-ui/icons';
5 | import { addTodo } from '../../redux/slices/todoSlice';
6 |
7 | export default function AddTodo() {
8 | const [value, setValue] = useState('');
9 | const dispatch = useDispatch();
10 | const handleChange = event => setValue(event.target.value);
11 | const handleSubmit = event => {
12 | event.preventDefault();
13 | if (value !== '') {
14 | dispatch(addTodo(value));
15 | setValue('');
16 | }
17 | };
18 | return (
19 |
38 | );
39 | }
40 |
--------------------------------------------------------------------------------
/src/components/colorModeSwitcher/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { useColorMode, useColorModeValue, IconButton } from '@chakra-ui/core';
3 | import { HiMoon, HiSun } from 'react-icons/hi';
4 |
5 | export const ColorModeSwitcher = props => {
6 | const { toggleColorMode } = useColorMode();
7 | const text = useColorModeValue('dark', 'light');
8 | const SwitchIcon = useColorModeValue(HiMoon, HiSun);
9 |
10 | return (
11 | }
20 | {...props}
21 | />
22 | );
23 | };
24 |
--------------------------------------------------------------------------------
/src/components/errorMessage/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import {
3 | Alert,
4 | AlertIcon,
5 | AlertTitle,
6 | AlertDescription,
7 | CloseButton,
8 | } from '@chakra-ui/core';
9 |
10 | export default function ErrorMessage({ error }) {
11 | return (
12 |
18 |
19 | An error has occurred!
20 | {error}
21 |
22 |
23 | );
24 | }
25 |
--------------------------------------------------------------------------------
/src/components/layout/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Box, Grid, Text, Link } from '@chakra-ui/core';
3 | import { ColorModeSwitcher } from '../colorModeSwitcher';
4 |
5 | export default function Layout(props) {
6 | return (
7 |
8 |
17 |
18 | {props.children}
19 |
20 |
21 | Redux Toolkit Example Created by{' '}
22 |
27 | Devjyoti Ghosh
28 |
29 |
30 |
31 |
32 |
33 | );
34 | }
35 |
--------------------------------------------------------------------------------
/src/components/todoList/index.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect } from 'react';
2 | import { useDispatch, useSelector } from 'react-redux';
3 | import { Box, VStack, Text, Checkbox, Skeleton } from '@chakra-ui/core';
4 | import { fetchTodos } from '../../redux/slices/todoSlice';
5 | import ErrorMessage from '../errorMessage';
6 |
7 | export default function TodoList() {
8 | const dispatch = useDispatch();
9 | const todoListdata = useSelector(state => state.todos.todoList);
10 | const apiStatus = useSelector(state => state.todos.status);
11 | const apiErrorMessage = useSelector(state => state.todos.error);
12 |
13 | useEffect(() => {
14 | if (apiStatus === 'idle') {
15 | dispatch(fetchTodos());
16 | }
17 | }, [apiStatus, dispatch]);
18 |
19 | const handleCheck = event => {
20 | //TODO: When checkbox is checked remove the todo from the redux store
21 | console.count('Checkbox function');
22 | };
23 |
24 | return (
25 | <>
26 | {apiStatus === 'loading' ? (
27 |
28 |
29 |
30 | ) : apiStatus === 'failed' ? (
31 |
32 | ) : (
33 | <>
34 | {todoListdata.map(todo => (
35 |
36 |
44 |
50 | {todo.value}
51 |
52 |
53 |
54 | ))}
55 | >
56 | )}
57 | >
58 | );
59 | }
60 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import { Provider } from 'react-redux';
4 | import App from './App';
5 | import * as serviceWorker from './serviceWorker';
6 | import reportWebVitals from './reportWebVitals';
7 | import store from './redux/store';
8 |
9 | ReactDOM.render(
10 |
11 |
12 |
13 |
14 | ,
15 | document.getElementById('root')
16 | );
17 |
18 | // If you want your app to work offline and load faster, you can change
19 | // unregister() to register() below. Note this comes with some pitfalls.
20 | // Learn more about service workers: https://cra.link/PWA
21 | serviceWorker.unregister();
22 |
23 | // If you want to start measuring performance in your app, pass a function
24 | // to log results (for example: reportWebVitals(console.log))
25 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
26 | reportWebVitals();
27 |
--------------------------------------------------------------------------------
/src/pages/homepage/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { VStack } from '@chakra-ui/core';
3 | import AddTodo from '../../components/addTodo';
4 | import TodoList from '../../components/todoList';
5 |
6 | export default function Home() {
7 | return (
8 |
15 |
16 |
17 |
18 | );
19 | }
20 |
--------------------------------------------------------------------------------
/src/pages/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import Layout from '../components/layout';
3 | import Home from './homepage';
4 |
5 | // This page will contain your Routing info and Layout if all pages share the same layout
6 | export default function Index() {
7 | return (
8 |
9 |
10 |
11 | );
12 | }
13 |
--------------------------------------------------------------------------------
/src/redux/slices/todoSlice.js:
--------------------------------------------------------------------------------
1 | import { createSlice, nanoid, createAsyncThunk } from '@reduxjs/toolkit';
2 | import axios from 'axios';
3 |
4 | export const fetchTodos = createAsyncThunk('todos/fetchTodos', async () => {
5 | const response = await axios.get(
6 | 'https://eager-supreme-appalachiosaurus.glitch.me/todos'
7 | );
8 | return response.data.todoList;
9 | });
10 |
11 | export const todoSlice = createSlice({
12 | name: 'todos',
13 | initialState: {
14 | todoList: [],
15 | status: 'idle',
16 | error: null,
17 | },
18 | reducers: {
19 | addTodo: {
20 | reducer: (state, action) => {
21 | state.todoList.push(action.payload);
22 | },
23 | prepare(value) {
24 | return {
25 | payload: {
26 | key: nanoid(),
27 | value: value,
28 | },
29 | };
30 | },
31 | },
32 | },
33 | extraReducers: {
34 | [fetchTodos.pending]: (state, action) => {
35 | state.status = 'loading';
36 | },
37 | [fetchTodos.fulfilled]: (state, action) => {
38 | state.status = 'succeeded';
39 | state.todoList.push(...action.payload);
40 | },
41 | [fetchTodos.rejected]: (state, action) => {
42 | state.status = 'failed';
43 | state.error = action.error.message;
44 | },
45 | },
46 | });
47 |
48 | export const { addTodo } = todoSlice.actions;
49 |
50 | export default todoSlice.reducer;
51 |
--------------------------------------------------------------------------------
/src/redux/store/index.js:
--------------------------------------------------------------------------------
1 | import { configureStore } from '@reduxjs/toolkit';
2 | import todoReducer from '../slices/todoSlice';
3 |
4 | export default configureStore({
5 | reducer: {
6 | todos: todoReducer,
7 | },
8 | });
9 |
--------------------------------------------------------------------------------
/src/reportWebVitals.js:
--------------------------------------------------------------------------------
1 | const reportWebVitals = onPerfEntry => {
2 | if (onPerfEntry && onPerfEntry instanceof Function) {
3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
4 | getCLS(onPerfEntry);
5 | getFID(onPerfEntry);
6 | getFCP(onPerfEntry);
7 | getLCP(onPerfEntry);
8 | getTTFB(onPerfEntry);
9 | });
10 | }
11 | };
12 |
13 | export default reportWebVitals;
14 |
--------------------------------------------------------------------------------
/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://cra.link/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 | 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://cra.link/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://cra.link/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 | headers: { 'Service-Worker': 'script' },
105 | })
106 | .then(response => {
107 | // Ensure service worker exists, and that we really are getting a JS file.
108 | const contentType = response.headers.get('content-type');
109 | if (
110 | response.status === 404 ||
111 | (contentType != null && contentType.indexOf('javascript') === -1)
112 | ) {
113 | // No service worker found. Probably a different app. Reload the page.
114 | navigator.serviceWorker.ready.then(registration => {
115 | registration.unregister().then(() => {
116 | window.location.reload();
117 | });
118 | });
119 | } else {
120 | // Service worker found. Proceed as normal.
121 | registerValidSW(swUrl, config);
122 | }
123 | })
124 | .catch(() => {
125 | console.log(
126 | 'No internet connection found. App is running in offline mode.'
127 | );
128 | });
129 | }
130 |
131 | export function unregister() {
132 | if ('serviceWorker' in navigator) {
133 | navigator.serviceWorker.ready
134 | .then(registration => {
135 | registration.unregister();
136 | })
137 | .catch(error => {
138 | console.error(error.message);
139 | });
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/src/setupTests.js:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom';
6 |
--------------------------------------------------------------------------------
/src/test-utils.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render } from '@testing-library/react';
3 | import { ChakraProvider, CSSReset } from '@chakra-ui/core';
4 | import theme from '@chakra-ui/theme';
5 |
6 | const AllProviders = ({ children }) => (
7 |
8 |
9 | {children}
10 |
11 | );
12 |
13 | const customRender = (ui, options) =>
14 | render(ui, { wrapper: AllProviders, ...options });
15 |
16 | export { customRender as render };
17 |
--------------------------------------------------------------------------------