Parcourir la source

feat: add redux saga

Entony il y a 6 ans
Parent
commit
c8d718840f

+ 14 - 0
package-lock.json

@@ -1823,6 +1823,15 @@
       "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.8.0.tgz",
       "integrity": "sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ=="
     },
+    "axios": {
+      "version": "0.18.0",
+      "resolved": "http://registry.npmjs.org/axios/-/axios-0.18.0.tgz",
+      "integrity": "sha1-MtU+SFHv3AoRmTts0AB4nXDAUQI=",
+      "requires": {
+        "follow-redirects": "^1.3.0",
+        "is-buffer": "^1.1.5"
+      }
+    },
     "axobject-query": {
       "version": "2.0.2",
       "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-2.0.2.tgz",
@@ -13045,6 +13054,11 @@
         "deep-diff": "^0.3.5"
       }
     },
+    "redux-saga": {
+      "version": "0.16.2",
+      "resolved": "https://registry.npmjs.org/redux-saga/-/redux-saga-0.16.2.tgz",
+      "integrity": "sha512-iIjKnRThI5sKPEASpUvySemjzwqwI13e3qP7oLub+FycCRDysLSAOwt958niZW6LhxfmS6Qm1BzbU70w/Koc4w=="
+    },
     "redux-thunk": {
       "version": "2.3.0",
       "resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-2.3.0.tgz",

+ 2 - 0
package.json

@@ -4,6 +4,7 @@
   "private": true,
   "dependencies": {
     "antd": "^3.10.9",
+    "axios": "^0.18.0",
     "node-sass": "^4.10.0",
     "prop-types": "^15.6.2",
     "react": "^16.6.3",
@@ -14,6 +15,7 @@
     "redux": "^4.0.1",
     "redux-form": "^7.4.2",
     "redux-logger": "^3.0.6",
+    "redux-saga": "^0.16.2",
     "redux-thunk": "^2.3.0"
   },
   "scripts": {

+ 50 - 6
src/Reducers/todo.js

@@ -1,12 +1,12 @@
 import * as types from "../constants/actionTypes";
 
-import data from "../utils/fakeData";
-
 const initState = {
-	list: data,
-	loads: [{ id: new Date().getTime(), name: "" }],
-	initialValues: {}
-	// editObject: {}
+	list: [],
+	isFetchng: false,
+	error: null,
+	initialValues: {},
+	editObject: {},
+	addObject: {}
 };
 
 export default (state = initState, { type, payload, meta }) => {
@@ -48,6 +48,50 @@ export default (state = initState, { type, payload, meta }) => {
 		// 	return state;
 		// }
 
+		case types.GET_LOADS: {
+			return { ...state, isFetchng: true };
+		}
+		case types.GET_LOADS_SUCCESS: {
+			const { data } = payload;
+
+			const list = Object.keys(data).reduce((prev, el) => {
+				return prev.concat({ ...data[el], id: el });
+			}, []);
+			return { ...state, isFetchng: false, list };
+		}
+		case types.GET_LOADS_FAIL: {
+			return { ...state, isFetchng: false, error: payload };
+		}
+
+		case types.POST_LOADS: {
+			return { ...state, isFetchng: true, addObject: payload };
+		}
+		case types.POST_LOADS_SUCCESS: {
+			const { data } = payload;
+			const newObject = { ...state.addObject, id: data.name };
+
+			return { ...state, isFetchng: false, list: state.list.concat(newObject) };
+		}
+		case types.POST_LOADS_FAIL: {
+			return { ...state, isFetchng: false, error: payload };
+		}
+
+		case types.EDIT_LOADS_REQUEST: {
+			return { ...state, isFetchng: true };
+		}
+		case types.EDIT_LOADS_REQUEST_SUCCESS: {
+			const { data } = payload;
+
+			const list = state.list.map(el => (el.id === data.id ? data : el));
+
+			console.log(list);
+
+			return { ...state, isFetchng: false, list };
+		}
+		case types.EDIT_LOADS_REQUEST_FAIL: {
+			return { ...state, isFetchng: false, error: payload };
+		}
+
 		default:
 			return state;
 	}

+ 46 - 4
src/actions/todo.js

@@ -25,7 +25,49 @@ export const editLoads = payload => ({
 	payload
 });
 
-// export const deleteItemList = payload => ({
-// 	type: types.DELETE_ITEM_LIST,
-// 	payload
-// });
+export const getLoads = payload => ({
+	type: types.GET_LOADS,
+	payload
+});
+
+export const getLoadsSuccess = payload => ({
+	type: types.GET_LOADS_SUCCESS,
+	payload
+});
+
+export const getLoadsFail = payload => ({
+	type: types.GET_LOADS_FAIL,
+	payload
+});
+
+export const postLoads = payload => ({
+	type: types.POST_LOADS,
+	payload
+});
+
+export const postLoadsSuccess = payload => ({
+	type: types.POST_LOADS_SUCCESS,
+	payload
+});
+
+export const postLoadsFail = payload => ({
+	type: types.POST_LOADS_FAIL,
+	payload
+});
+
+export const editLoadsRequest = payload => {
+	return {
+		type: types.EDIT_LOADS_REQUEST,
+		payload
+	};
+};
+
+export const editLoadsRequestSuccess = payload => ({
+	type: types.EDIT_LOADS_REQUEST_SUCCESS,
+	payload
+});
+
+export const editLoadsRequestFail = payload => ({
+	type: types.EDIT_LOADS_REQUEST_FAIL,
+	payload
+});

+ 1 - 0
src/components/modal/index.js

@@ -6,6 +6,7 @@ import LoadForm from "../loadForm";
 export default class EditModal extends Component {
 	render() {
 		const { visible, handleClose, inputData, editLoads, initialValues } = this.props;
+
 		return (
 			<Modal footer={false} title="Basic Modal" visible={visible} onCancel={handleClose}>
 				<LoadForm

+ 11 - 0
src/constants/actionTypes.js

@@ -9,3 +9,14 @@ export const WEATHER_REQUEST = "WEATHER_REQUEST";
 export const WEATHER_REQUEST_SUCCESS = "WEATHER_REQUEST_SUCCESS";
 export const WEATHER_REQUEST_FAIL = "WEATHER_REQUEST_FAIL";
 export const TAKE_INPUT_VALUE = "TAKE_INPUT_VALUE";
+
+export const GET_LOADS = "GET_LOADS";
+export const GET_LOADS_SUCCESS = "GET_LOADS_SUCCESS";
+export const GET_LOADS_FAIL = "GET_LOADS_FAIL";
+export const POST_LOADS = "POST_LOADS";
+export const POST_LOADS_SUCCESS = "POST_LOADS_SUCCESS";
+export const POST_LOADS_FAIL = "POST_LOADS_FAIL";
+
+export const EDIT_LOADS_REQUEST = "EDIT_LOADS_REQUEST";
+export const EDIT_LOADS_REQUEST_SUCCESS = "EDIT_LOADS_REQUEST_SUCCESS";
+export const EDIT_LOADS_REQUEST_FAIL = "EDIT_LOADS_REQUEST_FAIL";

+ 9 - 3
src/container/App.js

@@ -13,6 +13,12 @@ class App extends Component {
 		toggleModal: false
 	};
 
+	componentDidMount() {
+		const { getLoads } = this.props;
+
+		getLoads();
+	}
+
 	openEditModal = id => {
 		const { getInitVal } = this.props;
 		getInitVal(id);
@@ -23,7 +29,7 @@ class App extends Component {
 	openFormHandler = () => this.setState(prevState => ({ openAddForm: !prevState.openAddForm }));
 
 	render() {
-		const { list, inputData, addToList, editLoads, initialValues } = this.props;
+		const { list, inputData, editLoadsRequest, initialValues, postLoads } = this.props;
 		const { openAddForm, toggleModal } = this.state;
 		return (
 			<Fragment>
@@ -38,14 +44,14 @@ class App extends Component {
 
 					<div style={{ width: `50%` }}>
 						{openAddForm && (
-							<LoadForm formId="addLoads" title="Создать доставку" event={addToList} inputData={inputData} />
+							<LoadForm formId="addLoads" title="Создать доставку" event={postLoads} inputData={inputData} />
 						)}
 					</div>
 				</div>
 
 				<EditModal
 					initialValues={initialValues}
-					editLoads={editLoads}
+					editLoads={editLoadsRequest}
 					inputData={inputData}
 					visible={toggleModal}
 					handleClose={this.closeEditModal}

+ 7 - 0
src/saga/index.js

@@ -0,0 +1,7 @@
+import { fork } from "redux-saga/effects";
+
+import loads from "./loads";
+
+export default function*() {
+	yield fork(loads);
+}

+ 21 - 0
src/saga/loads/addLoads.js

@@ -0,0 +1,21 @@
+import axios from "axios";
+import { call, put } from "redux-saga/effects";
+import * as actions from "../../actions/todo";
+
+export default function* postLoads({ payload }) {
+	try {
+		const res = yield call(axios, {
+			url: `https://first-fly.firebaseio.com/loads.json`,
+			method: "POST",
+			headers: {
+				"content-type": "application/json"
+			},
+			data: payload
+		});
+		console.log("res", res);
+
+		yield put(actions.postLoadsSuccess(res));
+	} catch (e) {
+		yield put(actions.postLoadsFail(e.response));
+	}
+}

+ 20 - 0
src/saga/loads/editLoads.js

@@ -0,0 +1,20 @@
+import axios from "axios";
+import { call, put } from "redux-saga/effects";
+import * as actions from "../../actions/todo";
+
+export default function* editLoadsRequest({ payload }) {
+	try {
+		const res = yield call(axios, {
+			url: `https://first-fly.firebaseio.com/loads/${payload.id}.json`,
+			method: "PUT",
+			headers: {
+				"content-type": "application/json"
+			},
+			data: payload
+		});
+
+		yield put(actions.editLoadsRequestSuccess(res));
+	} catch (e) {
+		yield put(actions.editLoadsRequestFail(e.response));
+	}
+}

+ 26 - 0
src/saga/loads/getLoads.js

@@ -0,0 +1,26 @@
+import axios from "axios";
+// import { race } from "redu x-saga";
+import { call, put } from "redux-saga/effects";
+import * as actions from "../../actions/todo";
+
+export default function* getLoads({ payload }) {
+	try {
+		const res = yield call(axios, {
+			url: `https://first-fly.firebaseio.com/loads.json`,
+			method: "GET",
+			headers: {
+				"content-type": "application/json"
+			}
+		});
+
+		// const all = yield race({
+		// 	loads: call(),
+		// 	user: call()
+		// })
+
+		// yield call(delay, 5000);
+		yield put(actions.getLoadsSuccess(res));
+	} catch (e) {
+		yield put(actions.getLoadsFail(e.response));
+	}
+}

+ 13 - 0
src/saga/loads/index.js

@@ -0,0 +1,13 @@
+import { takeEvery } from "redux-saga/effects";
+import * as Types from "../../constants/actionTypes";
+import getLoads from "./getLoads";
+import postLoads from "./addLoads";
+import editLoadsRequest from "./editLoads";
+
+function* loads() {
+	yield takeEvery(Types.GET_LOADS, getLoads);
+	yield takeEvery(Types.POST_LOADS, postLoads);
+	yield takeEvery(Types.EDIT_LOADS_REQUEST, editLoadsRequest);
+}
+
+export default loads;

+ 7 - 1
src/state/state.js

@@ -1,11 +1,17 @@
 import { createStore, applyMiddleware } from "redux";
 import thunk from "redux-thunk";
+import createSagaMiddleware from "redux-saga";
 // import logger from "redux-logger";
 
+import saga from "../saga";
 import reducers from "../Reducers";
 
+const sagaMiddleware = createSagaMiddleware();
+
 export default createStore(
 	reducers,
 	// applyMiddleware(thunk, logger)
-	applyMiddleware(thunk)
+	applyMiddleware(thunk, sagaMiddleware)
 );
+
+sagaMiddleware.run(saga);