Last active
February 17, 2021 08:26
-
-
Save belozerskiy/f13cc4551f3f94e610a18e85b11287cc to your computer and use it in GitHub Desktop.
This file contains hidden or 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
export default { | |
name: "FetchApi", | |
props: { | |
method: { | |
type: String, | |
required: true | |
}, | |
endpoint: { | |
type: String, | |
required: true | |
}, | |
body: { | |
type: Object, | |
default: () => ({}) | |
}, | |
params: { | |
type: Object, | |
default: () => ({}) | |
}, | |
ssr: { | |
type: Boolean, | |
default: true, | |
}, | |
client: { | |
type: Boolean, | |
default: true, | |
} | |
}, | |
data() { | |
return { | |
data: null, | |
error: null, | |
loading: false, | |
} | |
}, | |
async serverPrefetch() { | |
if (this.ssr) { await this.fetch() } | |
}, | |
render(h) { | |
const { data, error, loading } = this | |
if (!process.server) { | |
const vnode = h('div', []) | |
vnode.asyncFactory = {} | |
vnode.isComment = true | |
return vnode | |
} else { | |
return h('div', this.$scopedSlots.default({ data, error, loading })) | |
} | |
}, | |
methods: { | |
async fetch() { | |
this.loading = true | |
const { method, endpoint, params } = this | |
let options = method.toUpperCase() === 'GET' ? { params } : { data: params } | |
try { | |
const data = await fetch(endpoint, { method, data: params }) | |
.then(response => response.json()) | |
} catch(RequestException) { | |
this.error = RequestException | |
console.log(RequestException) | |
} finally { | |
this.loading = false | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment