Skip to main content

fetchJSON

fetchJSON is a thin wrapper around the native fetch() API that removes boilerplate. It:

  • merges your config on top of getDefaultRequestConfig,
  • throws the response if the request wasn't ok (so you can .catch failures),
  • 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)

const cart = await window.BAO.utils.fetchJSON('/cart.js', { method: 'GET' })

POSTing data with error handling

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))