Home > Blockchain >  Random error "ethereum is not defined" in Vue development boilerplate
Random error "ethereum is not defined" in Vue development boilerplate

Time:12-17

I apologize if this is a dumb question but I'm just starting tinkering with Vue and web3 !

I am trying to implement web3 in a very basic Vue3 component using Vue basic boilerplate created with vue-cli but I have some weird errors.

First things first, here is the code of my component :

<template>
  <img alt="Vue logo" src="./assets/images/logo.png">
  <pre v-if="account">{{ account }}</pre>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      account: undefined
    }
  },
  async mounted() {
    if (typeof ethereum !== 'undefined') {
      const accounts = await ethereum.request({ method: 'eth_requestAccounts' })
      this.account = accounts[0]
    }
  }
}
</script>

The first issue I run into, is that when I launch the environment with npm run serve and when I change some code in my component, I have the following error in my test window as well as in my terminal :

Failed to compile.

./src/App.vue
Module Error (from ./node_modules/eslint-loader/index.js):

/home/arnaud/Code/_BLOCKCHAIN/crypto-app/src/App.vue
  16:30  error  'ethereum' is not defined  no-undef

✖ 1 problem (1 error, 0 warnings)

And the second weird behavior, is that I sometimes also have this error in my terminal when starting the environment but sometimes not. When I don't have the error at start, and if I don't change anything in the code, my application seems to run without error.

I have made some researches but for now I didn't find anything that helped me :/

CodePudding user response:

This is an eslint error, because you are trying to use ethereum variable in a a scope where it is not declared in. If ethereum is already declared in the global scope. You can disable the eslint for this line.

async mounted() {
      // eslint-disable-next-line no-undef
    if (typeof ethereum !== 'undefined') {
      // eslint-disable-next-line no-undef
      const accounts = await ethereum.request({ method: 'eth_requestAccounts' })
      this.account = accounts[0]
    }

otherwise you would have to define/import ethereum in the component.

CodePudding user response:

Install metamask extension first and then check for ethereum instance like

const {ethereum} =window;

  • Related