Skip to content

Instantly share code, notes, and snippets.

@fzn0x
Last active July 20, 2023 13:43
Show Gist options
  • Save fzn0x/28f8c8adfd2eebb1b43ef0a62b0b5143 to your computer and use it in GitHub Desktop.
Save fzn0x/28f8c8adfd2eebb1b43ef0a62b0b5143 to your computer and use it in GitHub Desktop.
Get Realtime Balance in web3.js | author using v1.3.6.rc-x, vue composition api. FREE TO MODIFY FOR YOUR OWN USE.
/*
* Author : Muhammad Fauzan | fauzan121002
* Web3.js v1.3.6
*
* No License Used, Free to modify, commercial use and distribute.
*/
import { defineComponent, useAsync, ref } from '@nuxtjs/composition-api'
export const useGetUserBalance = async () => {
try {
const data = window.web3.eth.getBalance(
window.web3.eth.currentProvider.selectedAddress
)
return window.web3.utils.fromWei(await data, 'ether') + ' ETH'
} catch (e) { console.error(e) }
}
export default defineComponent({
setup() {
// using vue reactivity object
let userBalance = ref({ value: 0 })
userBalance.value = useAsync(() => useGetUserBalance())
window.web3.eth.getAccounts().then(() => {
return web3.eth.subscribe('newBlockHeaders', (err) => {
if (err) {
console.log(err)
} else {
userBalance.value = useAsync(() => useGetUserBalance())
}
})
})
}
});
@fzn0x
Copy link
Author

fzn0x commented Jun 27, 2021

https://github.com/fauzan121002/nuxt-web3
Web3.js module integration for nuxt.js

@Mohammed-Mamoun98
Copy link

isn't that gonna fire a RPC call on every newBlock. the balance wouldn't necessarily change on every new block.
is there a more efficient way?

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