Skip to content

Instantly share code, notes, and snippets.

@adnaan
Created October 13, 2016 03:51
Show Gist options
  • Save adnaan/bedfa9357fce5657a3fca5afeaeba213 to your computer and use it in GitHub Desktop.
Save adnaan/bedfa9357fce5657a3fca5afeaeba213 to your computer and use it in GitHub Desktop.
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