rweich / streamdeck-ts-template

A template to create streamdeck plugins in typescript
MIT License
41 stars 13 forks source link

Async functions not working #17

Closed dxkyy closed 2 years ago

dxkyy commented 2 years ago

I wanted to make a plugin that fetches an API, so I wrote this code:

import { Streamdeck } from '@rweich/streamdeck-ts';

async function httpGet(theUrl: string) {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open('GET', theUrl, false);
  xmlHttp.send(null);
  return xmlHttp.responseText;
}

const plugin = new Streamdeck().plugin();

plugin.on('willAppear', ({ context }) => {
  plugin.setTitle('test', context);
});

plugin.on('keyDown', async ({ context }) => {
  const res = await httpGet('https://pride-api.herokuapp.com/api/sexuality/random');
  var data = JSON.parse(res);
  plugin.setTitle(data.name, context);
  plugin.setImage(data.flag, context);
});

export default plugin;

, but the title won't appear now, and when I press the button, the alert thing shows up. How can I fix this?

rweich commented 2 years ago

it works when you dont use async functions. Seems to be an issue with webpack/babel, but not really sure right now. Will check.

For now i suggest using promises instead. eg. like this:

plugin.on('keyDown', ({ context }) => {
  fetch('https://pride-api.herokuapp.com/api/sexuality/random')
    .then((response) => response.text())
    .then((text) => {
      const data = JSON.parse(text);
      plugin.setTitle(data.name, context);
      plugin.setImage(data.flag, context);
    });
});

just a heads up as it seems that data.flag is an url, which wont work. the value needs to be the images data base64-encoded. so you'll probably need to fetch the image first.