Created
October 13, 2016 03:51
-
-
Save adnaan/bedfa9357fce5657a3fca5afeaeba213 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.model({ | |
namespace: 'products', | |
state: { | |
list: [], | |
loading: false, | |
}, | |
subscriptions: { | |
setup({ dispatch }) { | |
dispatch({ type: 'query' }); | |
}, | |
}, | |
effects: { | |
*query(_, { put }) { | |
const { success, data } = yield fetch(`/api/products`).then(res => res.json()); | |
if (success) { | |
yield put({ | |
type: 'querySuccess', | |
payload: data, | |
}); | |
} | |
}, | |
*vote({ payload }, { put}) { | |
const { success } = yield fetch(`/api/products/vote?id=${payload}`).then(res => res.json()); | |
if (success) { | |
yield put({ | |
type: 'voteSuccess', | |
payload, | |
}); | |
} | |
}, | |
}, | |
reducers: { | |
query(state) { | |
return { ...state, loading: true, }; | |
}, | |
querySuccess(state, { payload }) { | |
return { ...state, loading: false, list: payload }; | |
}, | |
vote(state) { | |
return { ...state, loading: true }; | |
}, | |
voteSuccess(state, { payload }) { | |
const newList = state.list.map(product => { | |
if (product.id === payload) { | |
return { ...product, vote:product.vote + 1 }; | |
} else { | |
return product; | |
} | |
}); | |
return { ...state, list: newList, loading: false }; | |
}, | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment