Skip to content

Instantly share code, notes, and snippets.

@kvnam
Last active October 10, 2018 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kvnam/ecfe79ccdacca8737a330806f99be489 to your computer and use it in GitHub Desktop.
Save kvnam/ecfe79ccdacca8737a330806f99be489 to your computer and use it in GitHub Desktop.
ReactPress Store
import axios from '../../axios-wp';
export const loadAllPosts = (perpage) => {
//Load per_page count of posts from our WordPress installation
return dispatch => {
axios.get('/wp/v2/posts?per_page=' + perpage)
.then(postsRes => {
//Retrieve a list of all Media IDs from returned posts
let mediaIds = [];
postsRes.data.forEach(post => {
mediaIds.push(post.featured_media);
});
//Retrieve this list of media
axios.get('/wp/v2/media?include=' + mediaIds.join(','))
.then(mediaRes => {
let updatedPosts = null;
updatedPosts = postsRes.data.map(post => {
mediaRes.data.forEach(media => {
if(media.id === post.featured_media){
//Add link to media to a new property in each Post retrieved
post.media_link = media.guid.rendered;
}
});
return {
...post
};
});
//Dispatch Action to set posts value in reducer
dispatch({type: 'GET_ALL_POSTS', posts: updatedPosts});
}).catch(err => {
dispatch({type: 'GET_ALL_POSTS_FAIL', error: err});
});
}).catch(err => {
dispatch({type: 'GET_ALL_POSTS_FAIL', error: err});
});
}
}
export const loadSinglePost = pid => {
return dispatch => {
//Retrieve post by ID
axios.get('/wp/v2/posts/' + pid)
.then(post => {
//Retrieve featured image
let mediaId = post.data.featured_media;
axios.get('/wp/v2/media/' + mediaId)
.then(response => {
let postRes = {
...post.data,
medialink: response.data.guid.rendered
};
//Dispatch success action
dispatch({type: 'SINGLE_POST_SUCCESS', post: postRes})
})
.catch(err => {
dispatch({type: 'SINGLE_POST_FAIL', error: err});
})
})
.catch(err => {
dispatch({type: 'SINGLE_POST_FAIL', error: err});
});
}
}
const initialState = {
posts: null,
error: null,
perPage: 5 //I've set this to 5, you can choose your own count
};
const postsReducer = (state = initialState, action) => {
let newState = null;
switch(action.type){
case 'GET_ALL_POSTS': newState = {
...state,
posts: action.posts
};
return newState;
case 'GET_ALL_POSTS_FAIL': newState = {
...state,
error: action.error
};
return newState;
default: return state;
}
};
export default postsReducer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment