├── .env
├── .gitignore
├── README.md
├── package.json
├── public
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
├── src
├── App.css
├── App.test.tsx
├── App.tsx
├── components
│ ├── post.tsx
│ └── postList.tsx
├── containers
│ ├── __test__
│ │ └── postListContainer.spec.tsx
│ └── postListContainer.tsx
├── index.css
├── index.tsx
├── logo.svg
├── react-app-env.d.ts
├── serviceWorker.ts
└── state
│ ├── configureStore.dev.ts
│ ├── ducks
│ ├── index.ts
│ └── post
│ │ ├── __tests__
│ │ ├── __mockData__
│ │ │ └── postsData.json
│ │ ├── actions.spec.ts
│ │ ├── reducers.spec.ts
│ │ └── sagas.spec.ts
│ │ ├── actions.ts
│ │ ├── reducers.ts
│ │ ├── sagas.ts
│ │ └── types.ts
│ ├── index.ts
│ ├── middlewares
│ └── sagas.ts
│ └── utils
│ └── apiCaller.ts
├── tsconfig.json
└── yarn.lock
/.env:
--------------------------------------------------------------------------------
1 | REACT_APP_JSON_PLACEHOLDER=https://jsonplaceholder.typicode.com
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Scalable Redux architecture for React Projects with Redux-Saga and Typescript
2 |
3 | ## Starting Project
4 |
5 | `yarn start`
6 |
7 | ## Runnign Tests
8 |
9 | `yarn test`
10 |
11 | ## Dependencies
12 |
13 | - redux@4.0.4
14 | - react-redux@7.1.0
15 | - redux-saga@1.0.5
16 | - redux-saga-test-plan@4.0.0-beta.4
17 | - typesafe-actions@4.4.2
18 | - enzyme@3.10.0
19 | - redux-mock-store@1.5.3
20 | - enzyme-adapter-react-16@1.14.0
21 |
22 | ## Folder Structure
23 |
24 | ```
25 | src
26 | ├── App.css
27 | ├── App.test.tsx
28 | ├── App.tsx
29 | ├── components
30 | │ ├── post.tsx
31 | │ └── postList.tsx
32 | ├── containers
33 | │ ├── __tests__
34 | │ │ └── postList.container.spec.tsx
35 | │ └── postList.tsx
36 | ├── index.css
37 | ├── index.tsx
38 | ├── logo.svg
39 | ├── react-app-env.d.ts
40 | ├── serviceWorker.ts
41 | └── state
42 | ├── configureStore.dev.ts
43 | ├── ducks
44 | │ ├── index.ts
45 | │ └── post
46 | │ ├── __tests__
47 | │ │ ├── __mockData__
48 | │ │ ├── actions.spec.ts
49 | │ │ │ └── postsData.json
50 | │ │ ├── reducers.spec.ts
51 | │ │ └── sagas.spec.ts
52 | │ ├── actions.ts
53 | │ ├── reducers.ts
54 | │ ├── sagas.ts
55 | │ └── types.ts
56 | ├── index.ts
57 | ├── middlewares
58 | │ └── saga.ts
59 | └── utils
60 | └── apiCaller.ts
61 | ```
62 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "my-app-test",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@types/jest": "24.0.18",
7 | "@types/node": "12.7.3",
8 | "@types/react": "16.9.2",
9 | "@types/react-dom": "16.9.0",
10 | "enzyme": "3.10.0",
11 | "enzyme-adapter-react-16": "1.14.0",
12 | "eslint-utils": "^1.4.1",
13 | "react": "^16.9.0",
14 | "react-dom": "^16.9.0",
15 | "react-redux": "7.1.0",
16 | "react-scripts": "3.1.1",
17 | "redux": "4.0.4",
18 | "redux-mock-store": "1.5.3",
19 | "redux-saga": "1.0.5",
20 | "redux-saga-test-plan": "4.0.0-beta.4",
21 | "typesafe-actions": "4.4.2",
22 | "typescript": "3.6.2"
23 | },
24 | "scripts": {
25 | "start": "react-scripts start",
26 | "build": "react-scripts build",
27 | "test": "react-scripts test",
28 | "eject": "react-scripts eject"
29 | },
30 | "eslintConfig": {
31 | "extends": "react-app"
32 | },
33 | "browserslist": {
34 | "production": [
35 | ">0.2%",
36 | "not dead",
37 | "not op_mini all"
38 | ],
39 | "development": [
40 | "last 1 chrome version",
41 | "last 1 firefox version",
42 | "last 1 safari version"
43 | ]
44 | },
45 | "devDependencies": {
46 | "@types/enzyme": "3.10.3",
47 | "@types/enzyme-adapter-react-16": "1.0.5",
48 | "@types/react-redux": "7.1.1",
49 | "@types/redux-mock-store": "1.0.1"
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ersah123/scalable-react-redux-saga/1cb1a9bb1025b6f7f4f2a35724badcfcd41028cd/public/favicon.ico
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ersah123/scalable-react-redux-saga/1cb1a9bb1025b6f7f4f2a35724badcfcd41028cd/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ersah123/scalable-react-redux-saga/1cb1a9bb1025b6f7f4f2a35724badcfcd41028cd/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 |
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | animation: App-logo-spin infinite 20s linear;
7 | height: 40vmin;
8 | pointer-events: none;
9 | }
10 |
11 | .App-header {
12 | background-color: #282c34;
13 | min-height: 100vh;
14 | display: flex;
15 | flex-direction: column;
16 | align-items: center;
17 | justify-content: center;
18 | font-size: calc(10px + 2vmin);
19 | color: white;
20 | }
21 |
22 | .App-link {
23 | color: #61dafb;
24 | }
25 |
26 | @keyframes App-logo-spin {
27 | from {
28 | transform: rotate(0deg);
29 | }
30 | to {
31 | transform: rotate(360deg);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/App.test.tsx:
--------------------------------------------------------------------------------
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/App.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { Provider } from "react-redux";
3 | import "./App.css";
4 | import PostListContainer from "./containers/postListContainer";
5 | import configureStore from "./state";
6 | const initialState = (window as any).initialReduxState;
7 | const store = configureStore(initialState);
8 | const App: React.FC = () => {
9 | return (
10 |
11 |
12 |
13 | );
14 | };
15 | export default App;
16 |
--------------------------------------------------------------------------------
/src/components/post.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 |
3 | type props = {
4 | title: string;
5 | };
6 |
7 | const Post: React.FC = ({ title }: props) => {
8 | return {title};
9 | };
10 |
11 | export default Post;
12 |
--------------------------------------------------------------------------------
/src/components/postList.tsx:
--------------------------------------------------------------------------------
1 | import React, { useEffect } from "react";
2 | import {
3 | IDispatchToProps,
4 | IPostRaw,
5 | IPostState
6 | } from "../state/ducks/post/types";
7 | import Post from "./post";
8 |
9 | type AllProps = IPostState & IDispatchToProps;
10 |
11 | const PostList: React.FC = ({ data, fetchPosts }: AllProps) => {
12 | useEffect(() => {
13 | fetchPosts();
14 | }, [fetchPosts]);
15 | return (
16 |
17 |
18 | {data.map((post: IPostRaw) => (
19 |
20 | ))}
21 |
22 |
23 | );
24 | };
25 |
26 | export default PostList;
27 |
--------------------------------------------------------------------------------
/src/containers/__test__/postListContainer.spec.tsx:
--------------------------------------------------------------------------------
1 | import { configure, mount } from "enzyme";
2 | import Adapter from "enzyme-adapter-react-16";
3 | import React from "react";
4 | import { Provider } from "react-redux";
5 | import configureStore from "redux-mock-store";
6 | import PostList from "../../components/postList";
7 | import { initialState } from "../../state/ducks/post/reducers";
8 | import PostListContainer from "../postListContainer";
9 |
10 | configure({ adapter: new Adapter() });
11 | const mockStore = configureStore();
12 |
13 | describe("container ", () => {
14 | let wrapper, store, container, component: any;
15 | beforeEach(() => {
16 | store = mockStore({ post: initialState });
17 |
18 | store.dispatch = jest.fn();
19 |
20 | wrapper = mount(
21 |
22 |
23 |
24 | );
25 |
26 | container = wrapper.find(PostListContainer);
27 | component = container.find(PostList);
28 | });
29 |
30 | it("should render both the container and the component", () => {
31 | expect(container.length).toBeTruthy();
32 | expect(component.length).toBeTruthy();
33 | });
34 |
35 | it("should map state to props", () => {
36 | const expectedPropKeys = ["loading", "errors", "data"];
37 |
38 | expect(Object.keys(component.props())).toEqual(
39 | expect.arrayContaining(expectedPropKeys)
40 | );
41 | });
42 |
43 | it("should map dispatch to props", () => {
44 | const expectedPropKeys = ["fetchPosts"];
45 |
46 | expect(Object.keys(component.props())).toEqual(
47 | expect.arrayContaining(expectedPropKeys)
48 | );
49 | });
50 | });
51 |
--------------------------------------------------------------------------------
/src/containers/postListContainer.tsx:
--------------------------------------------------------------------------------
1 | import React, { useCallback } from "react";
2 | import { useDispatch, useSelector } from "react-redux";
3 | import PostList from "../components/postList";
4 | import { IApplicationState } from "../state/ducks/index";
5 | import { fetchPosts } from "../state/ducks/post/actions";
6 | import { IPostState } from "../state/ducks/post/types";
7 |
8 | const PostListContainer = () => {
9 | const dispatch = useDispatch();
10 |
11 | const stateToProps: IPostState = useSelector(
12 | ({ post }: IApplicationState) => ({
13 | loading: post.loading,
14 | errors: post.errors,
15 | data: post.data
16 | })
17 | );
18 |
19 | const dispatchToProps = {
20 | fetchPosts: useCallback(() => dispatch(fetchPosts()), [dispatch])
21 | };
22 |
23 | return ;
24 | };
25 |
26 | export default PostListContainer;
27 |
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
12 | monospace;
13 | }
14 |
--------------------------------------------------------------------------------
/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/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/src/react-app-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/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.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 | 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(
32 | (process as { env: { [key: string]: string } }).env.PUBLIC_URL,
33 | window.location.href
34 | );
35 | if (publicUrl.origin !== window.location.origin) {
36 | // Our service worker won't work if PUBLIC_URL is on a different origin
37 | // from what our page is served on. This might happen if a CDN is used to
38 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
39 | return;
40 | }
41 |
42 | window.addEventListener('load', () => {
43 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
44 |
45 | if (isLocalhost) {
46 | // This is running on localhost. Let's check if a service worker still exists or not.
47 | checkValidServiceWorker(swUrl, config);
48 |
49 | // Add some additional logging to localhost, pointing developers to the
50 | // service worker/PWA documentation.
51 | navigator.serviceWorker.ready.then(() => {
52 | console.log(
53 | 'This web app is being served cache-first by a service ' +
54 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
55 | );
56 | });
57 | } else {
58 | // Is not localhost. Just register service worker
59 | registerValidSW(swUrl, config);
60 | }
61 | });
62 | }
63 | }
64 |
65 | function registerValidSW(swUrl: string, config?: Config) {
66 | navigator.serviceWorker
67 | .register(swUrl)
68 | .then(registration => {
69 | registration.onupdatefound = () => {
70 | const installingWorker = registration.installing;
71 | if (installingWorker == null) {
72 | return;
73 | }
74 | installingWorker.onstatechange = () => {
75 | if (installingWorker.state === 'installed') {
76 | if (navigator.serviceWorker.controller) {
77 | // At this point, the updated precached content has been fetched,
78 | // but the previous service worker will still serve the older
79 | // content until all client tabs are closed.
80 | console.log(
81 | 'New content is available and will be used when all ' +
82 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
83 | );
84 |
85 | // Execute callback
86 | if (config && config.onUpdate) {
87 | config.onUpdate(registration);
88 | }
89 | } else {
90 | // At this point, everything has been precached.
91 | // It's the perfect time to display a
92 | // "Content is cached for offline use." message.
93 | console.log('Content is cached for offline use.');
94 |
95 | // Execute callback
96 | if (config && config.onSuccess) {
97 | config.onSuccess(registration);
98 | }
99 | }
100 | }
101 | };
102 | };
103 | })
104 | .catch(error => {
105 | console.error('Error during service worker registration:', error);
106 | });
107 | }
108 |
109 | function checkValidServiceWorker(swUrl: string, config?: Config) {
110 | // Check if the service worker can be found. If it can't reload the page.
111 | fetch(swUrl)
112 | .then(response => {
113 | // Ensure service worker exists, and that we really are getting a JS file.
114 | const contentType = response.headers.get('content-type');
115 | if (
116 | response.status === 404 ||
117 | (contentType != null && contentType.indexOf('javascript') === -1)
118 | ) {
119 | // No service worker found. Probably a different app. Reload the page.
120 | navigator.serviceWorker.ready.then(registration => {
121 | registration.unregister().then(() => {
122 | window.location.reload();
123 | });
124 | });
125 | } else {
126 | // Service worker found. Proceed as normal.
127 | registerValidSW(swUrl, config);
128 | }
129 | })
130 | .catch(() => {
131 | console.log(
132 | 'No internet connection found. App is running in offline mode.'
133 | );
134 | });
135 | }
136 |
137 | export function unregister() {
138 | if ('serviceWorker' in navigator) {
139 | navigator.serviceWorker.ready.then(registration => {
140 | registration.unregister();
141 | });
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/src/state/configureStore.dev.ts:
--------------------------------------------------------------------------------
1 | import { applyMiddleware, createStore, Store } from "redux";
2 | import { IApplicationState, rootReducer, rootSaga } from "./ducks/index";
3 | import sagaMiddleware from "./middlewares/sagas";
4 |
5 | export default function configureStore(
6 | initialState: IApplicationState
7 | ): Store {
8 | const middlewares = applyMiddleware(sagaMiddleware); // Create Store
9 | const store = createStore(rootReducer, initialState, middlewares);
10 |
11 | sagaMiddleware.run(rootSaga);
12 |
13 | return store;
14 | }
15 |
--------------------------------------------------------------------------------
/src/state/ducks/index.ts:
--------------------------------------------------------------------------------
1 | import { combineReducers } from "redux";
2 | import { all, fork } from "redux-saga/effects";
3 | import {
4 | Action,
5 | MetaAction,
6 | PayloadAction,
7 | TypeConstant
8 | } from "typesafe-actions";
9 | import { postReducer } from "./post/reducers";
10 | import postSaga from "./post/sagas";
11 | import { IPostState } from "./post/types";
12 | // The top-level state object
13 | export interface IApplicationState {
14 | post: IPostState;
15 | }
16 | export interface IMetaAction extends MetaAction {}
17 | export interface IReducerAction
18 | extends Action,
19 | PayloadAction {}
20 | export const rootReducer = combineReducers({
21 | post: postReducer
22 | });
23 | export function* rootSaga() {
24 | yield all([fork(postSaga)]);
25 | }
26 | interface IMeta {
27 | method: string;
28 | route: string;
29 | }
30 |
--------------------------------------------------------------------------------
/src/state/ducks/post/__tests__/__mockData__/postsData.json:
--------------------------------------------------------------------------------
1 |
2 | [
3 | {
4 | "userId": 1,
5 | "id": 1,
6 | "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
7 | "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
8 | },
9 | {
10 | "userId": 1,
11 | "id": 2,
12 | "title": "qui est esse",
13 | "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
14 | },
15 | {
16 | "userId": 1,
17 | "id": 3,
18 | "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
19 | "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
20 | }
21 | ]
22 |
23 |
--------------------------------------------------------------------------------
/src/state/ducks/post/__tests__/actions.spec.ts:
--------------------------------------------------------------------------------
1 | import { action } from "typesafe-actions";
2 | import { fetchPosts, fetchPostsSuccess } from "../actions";
3 | import { PostActionTypes } from "../types";
4 | import * as postData from "./__mockData__/postsData.json";
5 |
6 | describe("post actions", () => {
7 | it("should create an action to fetch all posts", () => {
8 | const expectedAction = action(PostActionTypes.FETCH_POSTS, [], {
9 | method: "get",
10 | route: "/posts"
11 | });
12 |
13 | expect(fetchPosts()).toEqual(expectedAction);
14 | });
15 |
16 | it("should create an success action", () => {
17 | const expectedAction = action(
18 | PostActionTypes.FETCH_POSTS_SUCCESS,
19 | postData
20 | );
21 |
22 | expect(fetchPostsSuccess(postData)).toEqual(expectedAction);
23 | });
24 | });
25 |
--------------------------------------------------------------------------------
/src/state/ducks/post/__tests__/reducers.spec.ts:
--------------------------------------------------------------------------------
1 | import { fetchPosts, fetchPostsSuccess } from "../actions";
2 | import { initialState, postReducer } from "../reducers";
3 | import * as postData from "./__mockData__/postsData.json";
4 | describe("post reducer", () => {
5 | it("should return initial state", () => {
6 | expect(
7 | postReducer(initialState, { type: "no type", payload: null })
8 | ).toEqual(initialState);
9 | });
10 | it("should handle fetching all posts", () => {
11 | expect(postReducer(initialState, fetchPosts())).toEqual({
12 | ...initialState,
13 | loading: true
14 | });
15 | });
16 | it("should handle all data successfully fetch post", () => {
17 | expect(postReducer(initialState, fetchPostsSuccess(postData))).toEqual({
18 | ...initialState,
19 | data: postData
20 | });
21 | });
22 | });
23 |
--------------------------------------------------------------------------------
/src/state/ducks/post/__tests__/sagas.spec.ts:
--------------------------------------------------------------------------------
1 | import { expectSaga } from "redux-saga-test-plan";
2 | import * as matchers from "redux-saga-test-plan/matchers";
3 | import apiCaller from "../../../utils/apiCaller";
4 | import { fetchPosts, fetchPostsSuccess } from "../actions";
5 | import postSaga from "../sagas";
6 | import * as postData from "./__mockData__/postsData.json";
7 |
8 | describe("post saga", () => {
9 | it("should handle successfully fetching posts", () => {
10 | return (
11 | expectSaga(postSaga)
12 | .provide([[matchers.call.fn(apiCaller), postData]])
13 | // Assert that the 'put' will eventually happen
14 | .put(fetchPostsSuccess(postData))
15 | // Dispatch any actions that the saga will 'take'
16 | .dispatch(fetchPosts())
17 | // Start the test, return a Promise
18 | .run()
19 | );
20 | });
21 | });
22 |
--------------------------------------------------------------------------------
/src/state/ducks/post/actions.ts:
--------------------------------------------------------------------------------
1 | import { action } from "typesafe-actions";
2 | import { IPostRaw, PostActionTypes } from "./types";
3 | export const fetchPosts = () =>
4 | action(PostActionTypes.FETCH_POSTS, [], {
5 | method: "get",
6 | route: "/posts"
7 | });
8 | export const fetchPostsSuccess = (data: IPostRaw[]) =>
9 | action(PostActionTypes.FETCH_POSTS_SUCCESS, data);
10 | export const fetchPostsError = (message: string) =>
11 | action(PostActionTypes.FETCH_POSTS_ERROR, message);
12 |
--------------------------------------------------------------------------------
/src/state/ducks/post/reducers.ts:
--------------------------------------------------------------------------------
1 | import { Action, PayloadAction, TypeConstant } from "typesafe-actions";
2 | import { IPostRaw, IPostState, PostActionTypes } from "./types";
3 | export const initialState: IPostState = {
4 | data: [],
5 | errors: [],
6 | loading: false
7 | };
8 | export const postReducer = (
9 | state: IPostState = initialState,
10 | action: Action & PayloadAction
11 | ): IPostState => {
12 | switch (action.type) {
13 | case PostActionTypes.FETCH_POSTS: {
14 | return { ...state, loading: true };
15 | }
16 | case PostActionTypes.FETCH_POSTS_SUCCESS: {
17 | return { ...initialState, data: action.payload };
18 | }
19 | case PostActionTypes.FETCH_POSTS_ERROR: {
20 | return {
21 | ...state
22 | };
23 | }
24 | default:
25 | return state;
26 | }
27 | };
28 |
--------------------------------------------------------------------------------
/src/state/ducks/post/sagas.ts:
--------------------------------------------------------------------------------
1 | import { all, call, fork, put, takeEvery } from "redux-saga/effects";
2 | import { IMetaAction } from "..";
3 | import apiCaller from "../../utils/apiCaller";
4 | import { fetchPostsError, fetchPostsSuccess } from "./actions";
5 | import { IPostRaw, PostActionTypes } from "./types";
6 |
7 | /**
8 | * @desc Business logic of effect.
9 | */
10 | function* handleFetch(action: IMetaAction): Generator {
11 | try {
12 | const res: IPostRaw[] | any = yield call(
13 | apiCaller,
14 | action.meta.method,
15 | action.meta.route
16 | );
17 |
18 | yield put(fetchPostsSuccess(res));
19 | } catch (err) {
20 | if (err instanceof Error) {
21 | yield put(fetchPostsError(err.stack!));
22 | } else {
23 | yield put(fetchPostsError("An unknown error occured."));
24 | }
25 | }
26 | }
27 |
28 | /**
29 | * @desc Watches every specified action and runs effect method and passes action args to it
30 | */
31 | function* watchFetchRequest(): Generator {
32 | yield takeEvery(PostActionTypes.FETCH_POSTS, handleFetch);
33 | }
34 |
35 | /**
36 | * @desc saga init, forks in effects, other sagas
37 | */
38 | export default function* postSaga() {
39 | yield all([fork(watchFetchRequest)]);
40 | }
41 |
--------------------------------------------------------------------------------
/src/state/ducks/post/types.ts:
--------------------------------------------------------------------------------
1 | import { IMetaAction } from "..";
2 | export interface IPostState {
3 | readonly data: IPostRaw[];
4 | readonly loading: boolean;
5 | readonly errors: [];
6 | }
7 | export type ApiResponse = Record;
8 | export interface IPostRaw extends ApiResponse {
9 | id: number;
10 | title: string;
11 | body: string;
12 | userId: number;
13 | }
14 | export const PostActionTypes = {
15 | FETCH_POSTS: "@@post/FETCH_POSTS",
16 | FETCH_POSTS_SUCCESS: "@@post/FETCH_POSTS_SUCCESS",
17 | FETCH_POSTS_ERROR: "@@post/FETCH_POSTS_ERROR"
18 | };
19 |
20 | export interface IDispatchToProps {
21 | fetchPosts: () => IMetaAction;
22 | }
23 |
--------------------------------------------------------------------------------
/src/state/index.ts:
--------------------------------------------------------------------------------
1 | import configureStore from "./configureStore.dev";
2 |
3 | export default configureStore;
4 |
--------------------------------------------------------------------------------
/src/state/middlewares/sagas.ts:
--------------------------------------------------------------------------------
1 | import createSagaMiddleware from "redux-saga";
2 | // Redux-saga middleware
3 | const sagaMiddleware = createSagaMiddleware();
4 | export default sagaMiddleware;
5 |
--------------------------------------------------------------------------------
/src/state/utils/apiCaller.ts:
--------------------------------------------------------------------------------
1 | export default function apiCaller(
2 | method: string,
3 | path: string,
4 | data?: any
5 | ): Promise {
6 | return fetch(process.env.REACT_APP_JSON_PLACEHOLDER + path, {
7 | method,
8 | headers: {
9 | Accept: "application/json",
10 | "Content-Type": "application/json"
11 | },
12 | body: data ? JSON.stringify(data) : null
13 | }).then(res => res.json());
14 | }
15 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "lib": [
5 | "dom",
6 | "dom.iterable",
7 | "esnext"
8 | ],
9 | "allowJs": true,
10 | "skipLibCheck": true,
11 | "esModuleInterop": true,
12 | "allowSyntheticDefaultImports": true,
13 | "strict": true,
14 | "forceConsistentCasingInFileNames": true,
15 | "module": "esnext",
16 | "moduleResolution": "node",
17 | "resolveJsonModule": true,
18 | "isolatedModules": true,
19 | "noEmit": true,
20 | "jsx": "react"
21 | },
22 | "include": [
23 | "src"
24 | ]
25 | }
26 |
--------------------------------------------------------------------------------