Search code examples
websocketsocket.ionuxt.jsvuex

Why won't this nuxt-socket-io emitter trigger its action?


I am trying to get nuxt-socket-io working on my NuxtJS application, but my emit functions do not seem to trigger the actions in my vuex store.

nuxt.config.js has the following code:

modules: [
    '@nuxtjs/axios',
    'nuxt-socket-io'
  ],
  io: {
    sockets: [
      {
    name: 'main',
    url: process.env.WS_URL || 'http://localhost:3000',
    default: true,
    vuex: {
      mutations: [],
      actions: [ "subscribeToMirror" ],
      emitBacks: []
    },
      },
    ]
  },

That subscribeToMirror action is present in my vuex store (in index.js):

export const actions = {
  async subscribeToMirror() {
    console.log('emit worked');
    try {
      new TopicMessageQuery()
    .setTopicId(state.topicId)
    .setStartTime(0) // TODO: last 3 days
    .subscribe(HederaClient, res => {
      console.log("Got response from mirror...");  
      return res;
    });
    } catch (error) {
      console.error(error);
    }
  }
};

And that action should be triggered by the emit in my index.vue script:

  mounted() {
    this.socket = this.$nuxtSocket({
      name: 'main',
      reconnection: false
    })
  },
  methods: {
    ...mapMutations([
      'setEnv',
      'initHashgraphClient',
      'setTopicId',
      'createNewTopicId'
    ]),
    ...mapActions([
      'createAndSetTopicId'
    ]),
    subscribeToMirror() {
      console.log("method worked");
      return new Promise((res) => {
    this.socket.emit('subscribeToMirror', {}, (resp) => {
      console.log(resp)
      resolve()
    })
      })
    }
  }

While I can see the 'method worked' console output from index.vue's subscribeToMirror method, I have never seen the 'emit worked' message. I have played around with this for hours, copying the instructions from this guide but have had no success.

Can anyone spot what I'm doing wrong?

UPDATE: I tried copying the code from this example and was unable to get a response from that heroku page. So it appears that I am completely unable to emit (even though $nuxtSocket appears to be functional and says it's connected). I am able to confirm that the socket itself is up and running, as I was able to get responses from it using the ticks from that example. I'm putting the repo for this project up here for viewing.

UPDATE2: I made a much simpler project here which is also not functioning correctly but should be easier to examine.


Solution

  • It turns out that while nuxt-socket-io functions as a wrapper for socket.io stuff you still need to actually create the server. This is a good template for how to do this