fetchJSON
fetchJSON is a thin wrapper around the native fetch() API that removes boilerplate. It:
- merges your config on top of
getDefaultRequestConfig, - throws the
responseif the request wasn'tok(so you can.catchfailures), - and resolves with the parsed JSON body.
It returns a Promise, so you can await it or chain .then()/.catch().
info
Currently the default method provided by getDefaultRequestConfig is POST, so GET must be specified for GET requests
Usage examples
Basic (GET)
- 2.0 Build
- 1.0 Build
const cart = await window.BAO.utils.fetchJSON('/cart.js', { method: 'GET' })
const cart = await fetchJSON('/cart.js', { method: 'GET' })
POSTing data with error handling
- 2.0 Build
- 1.0 Build
window.BAO.utils
.fetchJSON('/cart/add.js', {
body: JSON.stringify({ id: 12345, quantity: 1 }),
})
.then((line) => console.log('Added to cart', line))
.catch((response) => console.error('Request failed', response.status))
fetchJSON('/cart/add.js', {
body: JSON.stringify({ id: 12345, quantity: 1 }),
})
.then((line) => console.log('Added to cart', line))
.catch((response) => console.error('Request failed', response.status))