Skip to content

Instantly share code, notes, and snippets.

@DreySkee
Last active January 24, 2019 06:21
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DreySkee/7b9aec37d7ebbfc14c19ceb43238d2b1 to your computer and use it in GitHub Desktop.
Save DreySkee/7b9aec37d7ebbfc14c19ceb43238d2b1 to your computer and use it in GitHub Desktop.
WP-API DataActions with menus endpoint
import axios from 'axios';
import alt from './../alt/alt.js';
class DataActions {
constructor() {
const appUrl = 'http://andreypokrovskiy.com/projects/wp-api'; // Wordpress installation url
this.pagesEndPoint = `${appUrl}/wp-json/wp/v2/pages`; // Endpoint for getting Wordpress Pages
this.postsEndPoint = `${appUrl}/wp-json/wp/v2/posts`; // Endpoint for getting Wordpress Posts
this.menusEndPoint = `${appUrl}/wp-json/wp-api-menus/v2/menus/`; // Endpoint for getting Wordpress Menus
}
// Method for getting data from the provided end point url
api(endPoint) {
return new Promise((resolve, reject) => {
axios.get(endPoint).then((response) => {
resolve(response.data);
}).catch((error) => {
reject(error);
});
});
}
// Method for getting Pages data
getPages(cb){
this.api(this.pagesEndPoint).then((response)=>{
this.getMenus(response, cb)
});
}
// Method for getting menus data
getMenus(pages, cb){
this.api(this.menusEndPoint).then((response)=>{
const menus = response
const menusAndPages = { pages, menus };
this.getPosts(menusAndPages, cb)
});
}
// Method for getting Posts data
getPosts(menusAndPages, cb){
this.api(this.postsEndPoint).then((response)=>{
const postsObj = {posts: response}
const payload = Object.assign(menusAndPages, postsObj);
this.getSuccess(payload); // Pass returned data to the store
cb(payload); // This callback will be used for dynamic rout building
});
}
// This returnes an object with Pages and Posts data together
// The Alt Store will listen for this method to fire and will store the returned data
getSuccess(payload){
return payload;
}
}
export default alt.createActions(DataActions);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment