Skip to content

Instantly share code, notes, and snippets.

@DreySkee
Last active February 18, 2020 10:27
Show Gist options
  • Save DreySkee/f59da4dcd8cbbdc7ae27a4bdfea6d185 to your computer and use it in GitHub Desktop.
Save DreySkee/f59da4dcd8cbbdc7ae27a4bdfea6d185 to your computer and use it in GitHub Desktop.
8 - Wordpress API + ReactJS
import axios from 'axios';
import alt from './../alt/alt.js';
class DataActions {
constructor() {
const appUrl = 'http://wordpress-installation-example-url.com'; // Replace this with your WP 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
}
// 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.getPosts(response, cb)
});
}
// Method for getting Posts data
getPosts(pages, cb){
this.api(this.postsEndPoint).then((response)=>{
const posts = response
const payload = { pages, posts };
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