-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
65 lines (57 loc) · 1.6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import Symbol from 'es6-symbol'
import * as N from './action'
//the funtion component thst is used to call a request
//and get a unique symbol object back
export const fetchBackSymbol = url => disptch => {
const symbol = Symbol("fetch")
disptch({
type: N.FETCH,
url, symbol
})
return symbol
}
//default exported middleware,just need to add this in the middleware list
export default store => next => action => {
function actionWith(data) {
return Object.assign({}, action, data)
}
if(action.type == N.FETCH){
next(actionWith({ type: N.FETCH_REQUEST }))
}
if(action.url){
return loadWithAPI(action.url)
.then(rsp => rsp.json())
.then(
rsp => next(actionWith({
rsp,
type: N.FETCH_SUCCESS
})),
error => next(actionWith({
type: N.FETCH_REJECT,
error: error.message
}))
).catch((err) => {
console.error(err)
})
}else{
return next(action)
}
}
//TODO: need to adapt more datatype and abort it when needed
function loadWithAPI(url) {
return fetch(url)
}
export const SimpleAPIReducer = (state = { data: {}, SAMfetchState: 0 }, action) => {
// property fetchState is defined to describe the fetch state
// 0 for no network activity, 1 for processing, 2 for success, -1 for failed
switch (action.type){
case N.FETCH_REQUEST:
return Object.assign({}, state, {SAMfetchState: 1, symbol:action.symbol})
case N.FETCH_SUCCESS:
return Object.assign({}, state, {SAMfetchState: 2, data: action.rsp, symbol:action.symbol})
case N.FETCH_REJECT:
return Object.assign({}, state, {SAMfetchState: -1, data: action.rsp, symbol:action.symbol})
default:
return state
}
}