-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathalpine-fetch.js
56 lines (44 loc) · 1.27 KB
/
alpine-fetch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Alpine listeners
document.addEventListener('alpine:init', async () => {
Alpine.magic('fetchjson', () => {
return async (
url,
jsonItem = null,
method = "GET"
) => {
let response = await xfetch(url = url, jsonItem = jsonItem, method = method)
return await response;
}
})
Alpine.magic('fetch', () => {
return async (
url,
method = "GET"
) => {
let response = await xfetch(url = url, jsonItem = null, method = method)
return await response;
}
})
})
// Actual fetch function
async function xfetch(url, jsonItem = null, method = 'GET') {
if (jsonItem == null) {
return fetch(url, {method: method})
.then((response) => response.text())
.then((responseText) => {
return responseText
})
.catch((error) => {
console.log(error)
});
} else {
return fetch(url, {method: method})
.then((response) => response.json())
.then((responseJson) => {
return responseJson[jsonItem]
})
.catch((error) => {
console.log(error)
});
}
}