diff --git a/src/newsreader/js/pages/homepage/actions/posts.js b/src/newsreader/js/pages/homepage/actions/posts.js index 826512f..6f6f250 100644 --- a/src/newsreader/js/pages/homepage/actions/posts.js +++ b/src/newsreader/js/pages/homepage/actions/posts.js @@ -11,6 +11,10 @@ export const REQUEST_POSTS = 'REQUEST_POSTS'; export const MARK_POST_READ = 'MARK_POST_READ'; export const MARKING_POST = 'MARKING_POST'; +export const MARK_POST_SAVED = 'MARK_POST_SAVED'; +export const MARK_POST_UNSAVED = 'MARK_POST_UNSAVED'; +export const TOGGLING_POST = 'TOGGLING_POST'; + export const requestPosts = () => ({ type: REQUEST_POSTS }); export const receivePosts = (posts, next) => ({ @@ -64,6 +68,39 @@ export const markPostRead = (post, token) => { }; }; +// TODO add missing methods (postSaved & postUnsaved) +export const toggleSaved = (post, token) => { + return (dispatch, getState) => { + dispatch(togglingPostSaved()); + + const url = `/api/posts/${post.id}/`; + const options = { + method: 'PATCH', + headers: { + 'Content-Type': 'application/json', + 'X-CSRFToken': token, + }, + body: JSON.stringify({ saved: !post.saved }), + }; + + return fetch(url, options) + .then(response => response.json()) + .then(updatedPost => { + dispatch(receivePost({ ...updatedPost })); + + if (updatedPost.saved) { + dispatch(postSaved({ ...updatedPost })); + } else { + dispatch(postUnsaved({ ...updatedPost })); + } + }) + .catch(error => { + dispatch(receivePost({})); + dispatch(handleAPIError(error)); + }); + }; +}; + export const fetchPostsBySection = (section, next = false) => { return dispatch => { if (section.unread === 0) { diff --git a/src/newsreader/js/pages/homepage/reducers/posts.js b/src/newsreader/js/pages/homepage/reducers/posts.js index 608deb2..771d4f2 100644 --- a/src/newsreader/js/pages/homepage/reducers/posts.js +++ b/src/newsreader/js/pages/homepage/reducers/posts.js @@ -10,13 +10,15 @@ import { RECEIVE_POST, RECEIVE_POSTS, REQUEST_POSTS, + TOGGLING_POST, } from '../actions/posts.js'; import { SELECT_CATEGORY } from '../actions/categories.js'; import { SELECT_RULE } from '../actions/rules.js'; import { MARK_SECTION_READ } from '../actions/selected.js'; -const defaultState = { items: {}, isFetching: false, isMarking: false }; +const defaultState = { items: {}, isFetching: false, isUpdating: false }; +// TODO isMarking -> isUpdating export const posts = (state = { ...defaultState }, action) => { switch (action.type) { case REQUEST_POSTS: @@ -65,9 +67,15 @@ export const posts = (state = { ...defaultState }, action) => { }, }; case MARKING_POST: - return { ...state, isMarking: true }; + return { ...state, isUpdating: true }; + case TOGGLING_POST: + return { ...state, isUpdating: true }; case MARK_POST_READ: - return { ...state, isMarking: false }; + return { ...state, isUpdating: false }; + case MARK_POST_SAVED: + return { ...state, isUpdating: false }; + case MARK_POST_UNSAVED: + return { ...state, isUpdating: false }; default: return state; }