Añadir src/plugins/sigpro-fetch.js
This commit is contained in:
28
src/plugins/sigpro-fetch.js
Normal file
28
src/plugins/sigpro-fetch.js
Normal file
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* SigPro Fetch Plugin
|
||||
* Adds reactive data fetching to the $ namespace.
|
||||
*/
|
||||
$.use(($) => {
|
||||
/**
|
||||
* Performs a reactive fetch request.
|
||||
* @param {string} url - The API endpoint.
|
||||
* @param {Object} [options] - Fetch options (method, headers, etc).
|
||||
* @returns {{ $data: Function, $loading: Function, $error: Function }}
|
||||
*/
|
||||
$.fetch = (url, options = {}) => {
|
||||
const $data = $(null);
|
||||
const $loading = $(true);
|
||||
const $error = $(null);
|
||||
|
||||
fetch(url, options)
|
||||
.then(res => {
|
||||
if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
|
||||
return res.json();
|
||||
})
|
||||
.then(json => $data(json))
|
||||
.catch(err => $error(err.message))
|
||||
.finally(() => $loading(false));
|
||||
|
||||
return { $data, $loading, $error };
|
||||
};
|
||||
});
|
||||
Reference in New Issue
Block a user