Last active
January 24, 2020 04:15
-
-
Save mohdsayed/365dfbc057f133696ec74490644fa9a2 to your computer and use it in GitHub Desktop.
Fetch request for REST API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Exported from php. | |
const exports = { | |
restBase: { | |
url: 'https://example.org/wp-json/wp/v2', | |
nonce: '3433DFE2', | |
} | |
}; | |
// Utils function. | |
const getRestUrl = ( endpoint, params ) => { | |
const url = `${ exports.restBase.url }/${ endpoint }?_wpnonce=${ exports.restBase.nonce }`; | |
return Object.keys( params ).reduce( ( accum, key ) => accum + `&${ key }=${ params[ key ] }`, url ); | |
}; | |
const restUrl = getRestUrl( 'end-point', { | |
term_id: 23, | |
posts_per_page: 15, | |
} ); | |
fetch( restUrl, { headers: { 'X-WP-Nonce': exports.restBase.nonce }, | |
} ).then( response => response.json() ).then( resp => { | |
// Render JS template and append to DOM using resp. | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment