├── .eslintrc.js ├── .gitignore ├── .prettierrc.js ├── @types └── redux.d.ts ├── README.md ├── actions └── index.ts ├── components ├── clock.tsx ├── counter.tsx └── page.tsx ├── interfaces ├── actions.interfaces.ts ├── data.interfaces.ts └── index.ts ├── next-env.d.ts ├── package.json ├── pages ├── _app.tsx ├── index.tsx └── other.tsx ├── reducer.ts ├── saga.ts ├── store.ts ├── tsconfig.json └── yarn.lock /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', // Specifies the ESLint parser 3 | parserOptions: { 4 | ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features 5 | sourceType: 'module', // Allows for the use of imports 6 | ecmaFeatures: { 7 | jsx: true, // Allows for the parsing of JSX 8 | }, 9 | }, 10 | settings: { 11 | react: { 12 | version: 'detect', // Tells eslint-plugin-react to automatically detect the version of React to use 13 | }, 14 | }, 15 | extends: [ 16 | 'plugin:react/recommended', // Uses the recommended rules from @eslint-plugin-react 17 | 'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin 18 | 'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier 19 | 'plugin:prettier/recommended', // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array. 20 | 'plugin:import/recommended', 21 | 'plugin:react-hooks/recommended', 22 | ], 23 | rules: { 24 | 'react/react-in-jsx-scope': 0, 25 | '@typescript-eslint/no-var-requires': 0, 26 | 'import/no-unresolved': 0, 27 | 'import/named': 2, 28 | 'import/order': 1, 29 | // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs 30 | // e.g. "@typescript-eslint/explicit-function-return-type": "off", 31 | }, 32 | }; 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/api/node 2 | # Edit at https://www.gitignore.io/?templates=node 3 | 4 | ### Node ### 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | yarn-debug.log* 10 | yarn-error.log* 11 | lerna-debug.log* 12 | 13 | # Diagnostic reports (https://nodejs.org/api/report.html) 14 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 15 | 16 | # Runtime data 17 | pids 18 | *.pid 19 | *.seed 20 | *.pid.lock 21 | 22 | # Directory for instrumented libs generated by jscoverage/JSCover 23 | lib-cov 24 | 25 | # Coverage directory used by tools like istanbul 26 | coverage 27 | *.lcov 28 | 29 | # nyc test coverage 30 | .nyc_output 31 | 32 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 33 | .grunt 34 | 35 | # Bower dependency directory (https://bower.io/) 36 | bower_components 37 | 38 | # node-waf configuration 39 | .lock-wscript 40 | 41 | # Compiled binary addons (https://nodejs.org/api/addons.html) 42 | build/Release 43 | 44 | # Dependency directories 45 | node_modules/ 46 | jspm_packages/ 47 | 48 | # TypeScript v1 declaration files 49 | typings/ 50 | 51 | # TypeScript cache 52 | *.tsbuildinfo 53 | 54 | # Optional npm cache directory 55 | .npm 56 | 57 | # Optional eslint cache 58 | .eslintcache 59 | 60 | # Optional REPL history 61 | .node_repl_history 62 | 63 | # Output of 'npm pack' 64 | *.tgz 65 | 66 | # Yarn Integrity file 67 | .yarn-integrity 68 | 69 | # dotenv environment variables file 70 | .env 71 | .env.test 72 | 73 | # parcel-bundler cache (https://parceljs.org/) 74 | .cache 75 | 76 | # next.js build output 77 | .next 78 | 79 | # nuxt.js build output 80 | .nuxt 81 | 82 | # react / gatsby 83 | public/ 84 | 85 | # vuepress build output 86 | .vuepress/dist 87 | 88 | # Serverless directories 89 | .serverless/ 90 | 91 | # FuseBox cache 92 | .fusebox/ 93 | 94 | # DynamoDB Local files 95 | .dynamodb/ 96 | 97 | # End of https://www.gitignore.io/api/node -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | semi: true, 3 | trailingComma: 'all', 4 | singleQuote: true, 5 | printWidth: 100, 6 | tabWidth: 2 7 | }; 8 | -------------------------------------------------------------------------------- /@types/redux.d.ts: -------------------------------------------------------------------------------- 1 | import 'redux'; 2 | import { Task } from 'redux-saga'; 3 | 4 | declare module 'redux' { 5 | export interface Store { 6 | sagaTask?: Task; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # next-redux-saga-typescript example 2 | 3 | > This example is based on the [with-redux-saga](https://github.com/zeit/next.js/tree/master/examples/with-redux-saga) example. 4 | 5 | ## How to use 6 | 7 | Install it and run: 8 | 9 | ```bash 10 | npm install 11 | npm run dev 12 | # or 13 | yarn 14 | yarn dev 15 | ``` 16 | -------------------------------------------------------------------------------- /actions/index.ts: -------------------------------------------------------------------------------- 1 | import { User, actionTypes } from '../interfaces'; 2 | import * as actionIs from '../interfaces/actions.interfaces'; 3 | 4 | export function failure(error: Error): actionIs.Failure { 5 | return { 6 | type: actionTypes.FAILURE, 7 | error, 8 | }; 9 | } 10 | 11 | export function increment(): actionIs.Increment { 12 | return { type: actionTypes.INCREMENT }; 13 | } 14 | 15 | export function decrement(): actionIs.Decrement { 16 | return { type: actionTypes.DECREMENT }; 17 | } 18 | 19 | export function reset(): actionIs.Reset { 20 | return { type: actionTypes.RESET }; 21 | } 22 | 23 | export function loadData(): actionIs.LoadData { 24 | return { type: actionTypes.LOAD_DATA }; 25 | } 26 | 27 | export function loadDataSuccess(data: User[]): actionIs.LoadDataSuccess { 28 | return { 29 | type: actionTypes.LOAD_DATA_SUCCESS, 30 | data, 31 | }; 32 | } 33 | 34 | export function startClock(): actionIs.StartClock { 35 | return { type: actionTypes.START_CLOCK }; 36 | } 37 | 38 | export function tickClock(isServer: boolean): actionIs.TickClock { 39 | return { 40 | type: actionTypes.TICK_CLOCK, 41 | light: !isServer, 42 | ts: Date.now(), 43 | }; 44 | } 45 | -------------------------------------------------------------------------------- /components/clock.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | const pad = (n: number): string | number => (n < 10 ? `0${n}` : n); 4 | 5 | const format = (t: Date): string => { 6 | const hours = t.getUTCHours(); 7 | const minutes = t.getUTCMinutes(); 8 | const seconds = t.getUTCSeconds(); 9 | return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`; 10 | }; 11 | 12 | interface ClockProps { 13 | lastUpdate: number; 14 | light: boolean; 15 | } 16 | 17 | const Clock: React.FC = ({ lastUpdate, light }: ClockProps) => { 18 | return ( 19 |
20 | {format(new Date(lastUpdate))} 21 | 33 |
34 | ); 35 | }; 36 | 37 | export default Clock; 38 | -------------------------------------------------------------------------------- /components/counter.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { useSelector, useDispatch } from 'react-redux'; 3 | 4 | import { increment, decrement, reset } from '../actions'; 5 | import { AppState } from '../interfaces'; 6 | 7 | const Counter: React.FC = () => { 8 | const count = useSelector((state: AppState): number => state.count); 9 | const dispatch = useDispatch(); 10 | 11 | const onIncrement = (): void => { 12 | dispatch(increment()); 13 | }; 14 | 15 | const onDecrement = (): void => { 16 | dispatch(decrement()); 17 | }; 18 | 19 | const onReset = (): void => { 20 | dispatch(reset()); 21 | }; 22 | 23 | return ( 24 |
25 | 30 |

31 | Count: {count} 32 |

33 | 34 | 35 | 36 |
37 | ); 38 | }; 39 | 40 | export default Counter; 41 | -------------------------------------------------------------------------------- /components/page.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import Link from 'next/link'; 3 | import { useSelector } from 'react-redux'; 4 | import { createSelector } from 'reselect'; 5 | 6 | import { AppState } from '../interfaces'; 7 | import Counter from './counter'; 8 | import Clock from './clock'; 9 | 10 | interface PageProps { 11 | linkTo: string; 12 | NavigateTo: string; 13 | title: string; 14 | } 15 | 16 | const selectData = createSelector( 17 | (state: AppState) => state.error, 18 | (state: AppState) => state.lastUpdate, 19 | (state: AppState) => state.light, 20 | (state: AppState) => state.placeholderData, 21 | (error, lastUpdate, light, placeholderData) => ({ error, lastUpdate, light, placeholderData }), 22 | ); 23 | 24 | const Page: React.FC = ({ linkTo, NavigateTo, title }: PageProps) => { 25 | const { error, lastUpdate, light, placeholderData } = useSelector(selectData); 26 | 27 | return ( 28 |
29 |

{title}

30 | 31 | 32 | 37 | {placeholderData && ( 38 |
39 |           {JSON.stringify(placeholderData, null, 2)}
40 |         
41 | )} 42 | {error &&

Error: {error.message}

} 43 |
44 | ); 45 | }; 46 | 47 | export default Page; 48 | -------------------------------------------------------------------------------- /interfaces/actions.interfaces.ts: -------------------------------------------------------------------------------- 1 | import { User } from './index'; 2 | 3 | export enum actionTypes { 4 | FAILURE = 'FAILURE', 5 | INCREMENT = 'INCREMENT', 6 | DECREMENT = 'DECREMENT', 7 | RESET = 'RESET', 8 | LOAD_DATA = 'LOAD_DATA', 9 | LOAD_DATA_SUCCESS = 'LOAD_DATA_SUCCESS', 10 | START_CLOCK = 'START_CLOCK', 11 | TICK_CLOCK = 'TICK_CLOCK', 12 | } 13 | 14 | export type Action = 15 | | Failure 16 | | Increment 17 | | Decrement 18 | | Reset 19 | | LoadData 20 | | LoadDataSuccess 21 | | StartClock 22 | | TickClock; 23 | 24 | export interface Failure { 25 | type: actionTypes.FAILURE; 26 | error: Error; 27 | } 28 | 29 | export interface Increment { 30 | type: actionTypes.INCREMENT; 31 | } 32 | 33 | export interface Decrement { 34 | type: actionTypes.DECREMENT; 35 | } 36 | 37 | export interface Reset { 38 | type: actionTypes.RESET; 39 | } 40 | 41 | export interface LoadData { 42 | type: actionTypes.LOAD_DATA; 43 | } 44 | 45 | export interface LoadDataSuccess { 46 | type: actionTypes.LOAD_DATA_SUCCESS; 47 | data: User[]; 48 | } 49 | 50 | export interface StartClock { 51 | type: actionTypes.START_CLOCK; 52 | } 53 | 54 | export interface TickClock { 55 | type: actionTypes.TICK_CLOCK; 56 | light: boolean; 57 | ts: number; 58 | } 59 | -------------------------------------------------------------------------------- /interfaces/data.interfaces.ts: -------------------------------------------------------------------------------- 1 | export interface User { 2 | id: number; 3 | name: string; 4 | username: string; 5 | email: string; 6 | address: { 7 | street: string; 8 | suite: string; 9 | city: string; 10 | zipcode: string; 11 | geo: { 12 | lat: string; 13 | lng: string; 14 | }; 15 | }; 16 | phone: string; 17 | website: string; 18 | company: { 19 | name: string; 20 | catchPhrase: string; 21 | bs: string; 22 | }; 23 | } 24 | 25 | export interface AppState { 26 | count: number; 27 | error: null | Error; 28 | lastUpdate: number; 29 | light: boolean; 30 | placeholderData: User[] | null; 31 | } 32 | -------------------------------------------------------------------------------- /interfaces/index.ts: -------------------------------------------------------------------------------- 1 | export * from './actions.interfaces'; 2 | export * from './data.interfaces'; 3 | -------------------------------------------------------------------------------- /next-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "with-redux-saga", 3 | "version": "1.0.0", 4 | "license": "ISC", 5 | "scripts": { 6 | "dev": "next", 7 | "build": "next build", 8 | "start": "next start", 9 | "lint": "eslint '*/**/*.{js,ts,tsx}'" 10 | }, 11 | "dependencies": { 12 | "axios": "^0.21.1", 13 | "next": "^9.4.4", 14 | "next-redux-wrapper": "^6.0.2", 15 | "react": "^16.0.0", 16 | "react-dom": "^16.0.0", 17 | "react-redux": "^7.1.3", 18 | "redux": "^4.0.4", 19 | "redux-saga": "^1.1.3", 20 | "reselect": "^4.0.0" 21 | }, 22 | "devDependencies": { 23 | "@types/node": "^14.0.14", 24 | "@types/react": "^16.9.41", 25 | "@types/react-dom": "^16.9.8", 26 | "@types/react-redux": "^7.1.9", 27 | "@typescript-eslint/eslint-plugin": "^3.5.0", 28 | "@typescript-eslint/parser": "^3.5.0", 29 | "eslint": "^7.3.1", 30 | "eslint-config-prettier": "^6.11.0", 31 | "eslint-plugin-import": "^2.22.0", 32 | "eslint-plugin-prettier": "^3.1.4", 33 | "eslint-plugin-react": "^7.20.2", 34 | "eslint-plugin-react-hooks": "^4.0.6", 35 | "prettier": "^2.0.5", 36 | "redux-devtools-extension": "^2.13.8", 37 | "typescript": "^3.9.5" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /pages/_app.tsx: -------------------------------------------------------------------------------- 1 | import { AppProps } from 'next/app'; 2 | import { NextPage } from 'next'; 3 | import { wrapper } from '../store'; 4 | 5 | const MyApp: NextPage = ({ Component, pageProps }: AppProps) => { 6 | return ; 7 | }; 8 | 9 | export default wrapper.withRedux(MyApp); 10 | -------------------------------------------------------------------------------- /pages/index.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from 'react'; 2 | import { useDispatch } from 'react-redux'; 3 | import { NextPage } from 'next'; 4 | 5 | import { END } from 'redux-saga'; 6 | import { loadData, startClock, tickClock } from '../actions'; 7 | import Page from '../components/page'; 8 | import { wrapper } from '../store'; 9 | 10 | const Index: NextPage = () => { 11 | const dispatch = useDispatch(); 12 | 13 | useEffect(() => { 14 | dispatch(startClock()); 15 | }); 16 | 17 | return ; 18 | }; 19 | 20 | export const getStaticProps = wrapper.getStaticProps(async ({ store }) => { 21 | store.dispatch(tickClock(false)); 22 | 23 | if (!store.getState().placeholderData) { 24 | store.dispatch(loadData()); 25 | store.dispatch(END); 26 | } 27 | await store.sagaTask?.toPromise(); 28 | }); 29 | 30 | export default Index; 31 | -------------------------------------------------------------------------------- /pages/other.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from 'react'; 2 | import { useDispatch } from 'react-redux'; 3 | import { NextPage } from 'next'; 4 | 5 | import { startClock, tickClock } from '../actions'; 6 | import Page from '../components/page'; 7 | import { wrapper } from '../store'; 8 | 9 | const Other: NextPage = () => { 10 | const dispatch = useDispatch(); 11 | 12 | useEffect(() => { 13 | dispatch(startClock()); 14 | }); 15 | 16 | return ; 17 | }; 18 | 19 | export const getStaticProps = wrapper.getStaticProps(async ({ store }) => { 20 | store.dispatch(tickClock(false)); 21 | }); 22 | 23 | export default Other; 24 | -------------------------------------------------------------------------------- /reducer.ts: -------------------------------------------------------------------------------- 1 | import { AppState, Action, actionTypes } from './interfaces'; 2 | import { HYDRATE } from 'next-redux-wrapper'; 3 | 4 | export const exampleInitialState: AppState = { 5 | count: 0, 6 | error: null, 7 | lastUpdate: 0, 8 | light: false, 9 | placeholderData: null, 10 | }; 11 | 12 | const reducer = ( 13 | state = exampleInitialState, 14 | action: Action | { type: typeof HYDRATE; payload: AppState }, 15 | ): AppState => { 16 | switch (action.type) { 17 | case HYDRATE: 18 | return { ...state, ...action.payload }; 19 | 20 | case actionTypes.FAILURE: 21 | return { 22 | ...state, 23 | ...{ error: action.error }, 24 | }; 25 | 26 | case actionTypes.INCREMENT: 27 | return { 28 | ...state, 29 | ...{ count: state.count + 1 }, 30 | }; 31 | 32 | case actionTypes.DECREMENT: 33 | return { 34 | ...state, 35 | ...{ count: state.count - 1 }, 36 | }; 37 | 38 | case actionTypes.RESET: 39 | return { 40 | ...state, 41 | ...{ count: exampleInitialState.count }, 42 | }; 43 | 44 | case actionTypes.LOAD_DATA_SUCCESS: 45 | return { 46 | ...state, 47 | ...{ placeholderData: action.data }, 48 | }; 49 | 50 | case actionTypes.TICK_CLOCK: 51 | return { 52 | ...state, 53 | ...{ lastUpdate: action.ts, light: !!action.light }, 54 | }; 55 | 56 | default: 57 | return state; 58 | } 59 | }; 60 | 61 | export default reducer; 62 | -------------------------------------------------------------------------------- /saga.ts: -------------------------------------------------------------------------------- 1 | import { all, call, delay, put, take, takeLatest } from 'redux-saga/effects'; 2 | import axios, { AxiosResponse } from 'axios'; 3 | 4 | import { failure, loadDataSuccess, tickClock } from './actions'; 5 | import { User, actionTypes } from './interfaces'; 6 | 7 | function* runClockSaga() { 8 | yield take(actionTypes.START_CLOCK); 9 | while (true) { 10 | yield put(tickClock(false)); 11 | yield delay(1000); 12 | } 13 | } 14 | 15 | function* loadDataSaga() { 16 | try { 17 | const { status, data }: AxiosResponse = yield call( 18 | axios.get, 19 | 'https://jsonplaceholder.typicode.com/users', 20 | ); 21 | 22 | if (status === 200) { 23 | yield put(loadDataSuccess(data)); 24 | } 25 | } catch (err) { 26 | yield put(failure(err)); 27 | } 28 | } 29 | 30 | function* rootSaga(): Generator { 31 | yield all([call(runClockSaga), takeLatest(actionTypes.LOAD_DATA, loadDataSaga)]); 32 | } 33 | 34 | export default rootSaga; 35 | -------------------------------------------------------------------------------- /store.ts: -------------------------------------------------------------------------------- 1 | import { applyMiddleware, createStore, Middleware, StoreEnhancer } from 'redux'; 2 | import { createWrapper, MakeStore } from 'next-redux-wrapper'; 3 | import createSagaMiddleware from 'redux-saga'; 4 | 5 | import rootReducer from './reducer'; 6 | import rootSaga from './saga'; 7 | import { AppState } from './interfaces'; 8 | 9 | const bindMiddleware = (middleware: Middleware[]): StoreEnhancer => { 10 | if (process.env.NODE_ENV !== 'production') { 11 | const { composeWithDevTools } = require('redux-devtools-extension'); 12 | return composeWithDevTools(applyMiddleware(...middleware)); 13 | } 14 | return applyMiddleware(...middleware); 15 | }; 16 | 17 | export const makeStore: MakeStore = () => { 18 | const sagaMiddleware = createSagaMiddleware(); 19 | 20 | const store = createStore(rootReducer, bindMiddleware([sagaMiddleware])); 21 | 22 | store.sagaTask = sagaMiddleware.run(rootSaga); 23 | 24 | return store; 25 | }; 26 | 27 | export const wrapper = createWrapper(makeStore, { debug: true }); 28 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": true, 6 | "skipLibCheck": true, 7 | "strict": true, 8 | "forceConsistentCasingInFileNames": true, 9 | "noEmit": true, 10 | "esModuleInterop": true, 11 | "module": "esnext", 12 | "moduleResolution": "node", 13 | "resolveJsonModule": true, 14 | "isolatedModules": true, 15 | "jsx": "preserve" 16 | }, 17 | "exclude": ["node_modules"], 18 | "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"] 19 | } 20 | --------------------------------------------------------------------------------