Created
October 9, 2020 19:36
-
-
Save metafeather/ebda15c00c737c4d95cdc11ea71af32a to your computer and use it in GitHub Desktop.
Load GraphiQL React based UI within a Vue Component from CDN
This file contains 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
<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform"> | |
<div id="graphiql" style="height: 100vh"></div> | |
</template> | |
<script> | |
// Load GraphiQL React based UI within a Vue Component from CDN | |
// ref: https://github.com/graphql/graphiql/tree/main/packages/graphiql#cdn-bundle | |
const js = (id, url) => | |
new Promise((resolve, reject) => { | |
if (document.getElementById(id)) { | |
console.error(`Error loading ${url} async: ${id} is not unique`); | |
return; | |
} | |
const el = document.createElement("script"); | |
el.src = url; | |
el.async = true; | |
el.id = id; | |
el.onload = () => { | |
resolve(); | |
}; | |
el.onerror = (err) => { | |
reject(err); | |
}; | |
document.body.appendChild(el); | |
}); | |
export default { | |
name: "GraphQLPage", | |
meta: { | |
title: "GraphiQL", | |
link: { | |
"graphiql-css": { | |
rel: "stylesheet", | |
href: "https://unpkg.com/graphiql/graphiql.min.css", | |
}, | |
}, | |
}, | |
async mounted() { | |
// wait for latest CDN scripts | |
await js("react", "https://unpkg.com/react/umd/react.production.min.js"); | |
await js( | |
"react-dom", | |
"https://unpkg.com/react-dom/umd/react-dom.production.min.js" | |
); | |
await js("graphiql-js", "https://unpkg.com/graphiql/graphiql.min.js"); | |
const fetcher = (params) => | |
fetch("/graphql", { | |
method: "post", | |
headers: { "Content-Type": "application/json" }, | |
body: JSON.stringify(params), | |
}).then((res) => res.json()); | |
ReactDOM.render( | |
React.createElement(GraphiQL, { fetcher }), | |
document.getElementById("graphiql") | |
); | |
}, | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment