Skip to content

Instantly share code, notes, and snippets.

@Calvin-Huang
Created September 9, 2017 23:53
Show Gist options
  • Save Calvin-Huang/53608aea52a1d34e1c9c76a42a201e68 to your computer and use it in GitHub Desktop.
Save Calvin-Huang/53608aea52a1d34e1c9c76a42a201e68 to your computer and use it in GitHub Desktop.
store.subscribe(() => {
const state = store.getState();
const action = state.lastAction;
switch (action.type) {
case FETCH_PUBLIC_REPOS: {
$.getJSON(`https://api.github.com/search/repositories?q=language:javascript&per_page=10&page=${action.page}`)
.done((data) => {
store.dispatch(receivePublicRepos(data.items));
});
break;
}
case FETCH_REPOS_NEXT_PAGE: {
store.dispatch(fetchPublicRepos());
break;
}
case FETCH_BOOKMARKS: {
$.getJSON('/api/v1/bookmarks')
.done((data) => {
store.dispatch(receiveBookmarks(data));
});
break;
}
case RECEIVE_PUBLIC_REPOS:
case RECEIVE_BOOKMARKS: {
store.dispatch(setReposAreSaved(state.bookmarks.map(bookmark => bookmark.repo_id)));
break;
}
case TOGGLE_BOOKMARK: {
if (state.bookmarks.find(bookmark => bookmark.repo_id === action.repoId)) {
store.dispatch(deleteBookmark(action.repoId));
} else {
const repo = state.repos.data.find(repo => repo.id === action.repoId);
store.dispatch(createBookmark(repo.id, repo.full_name));
}
break;
}
case CREATE_BOOKMARK: {
store.dispatch(bookmarkCreated(action.repoId, action.fullName));
$.ajax({
method: 'POST',
contentType: 'application/json',
url: '/api/v1/bookmarks',
data: JSON.stringify({ repo_id: action.repoId, full_name: action.fullName }),
error: (jqXHR, textStatus, error) => {
store.dispatch(showNotification(`${error}: ${jqXHR.responseJSON.message}`));
store.dispatch(bookmarkDeleted(action.repoId));
},
});
break;
}
case DELETE_BOOKMARK: {
store.dispatch(bookmarkDeleted(action.repoId));
$.ajax({
method: 'DELETE',
contentType: 'json',
url: `/api/v1/bookmarks/${action.repoId}`,
error: (jqXHR, textStatus, error) => {
const repo = state.repos.data.find(repo => repo.id === action.repoId);
store.dispatch(showNotification(error));
store.dispatch(bookmarkCreated(repo.id, repo.full_name));
},
});
break;
}
case BOOKMARK_CREATED:
case BOOKMARK_DELETED: {
store.dispatch(setReposAreSaved(state.bookmarks.map(bookmark => bookmark.repo_id)));
break;
}
case SET_REPOS_ARE_SAVED: {
$('#app').html(repoList.render({ repos: state.repos.data }));
break;
}
case SHOW_NOTIFICATION: {
const modal = $('#notification');
modal.find('.message').text(action.message);
modal.modal({ show: true });
break;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment