Skip to content

Instantly share code, notes, and snippets.

Created August 22, 2017 06:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/7b1269fe8913c3dda8bb25b36d98b2dc to your computer and use it in GitHub Desktop.
Save anonymous/7b1269fe8913c3dda8bb25b36d98b2dc to your computer and use it in GitHub Desktop.
Fetch API Post example
const promise = new Promise(
(resolve, reject) => {
// do a thing, possibly async, then…
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
}
);
@xyzdata
Copy link

xyzdata commented Aug 22, 2017

    const createGist = (opts) => {
        ChromeSamples.log('Posting request to GitHub API...');
        fetch(
            'https://api.github.com/gists', 
            {
                method: 'post',
                body: JSON.stringify(opts)
            }
        ).then(
            (response) => response.json()
        ).then(
            (data) => {
                ChromeSamples.log('Created Gist:', data.html_url);
            }
        );
    }

    const submitGist = () => {
        let content = document.querySelector('textarea').value;
        if (content) {
            createGist(
                {
                    description: 'Fetch API Post example',
                    public: true,
                    files: {
                        'test.js': {
                            content: content
                        }
                    }
                }
            );
        } else {
            ChromeSamples.log('Please enter in content to POST to a new Gist.');
        }
    }

    const submitBtn = document.querySelector('button');
    submitBtn.addEventListener('click', submitGist);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment