My code has been tested that it works well before Moralis’s update to V1.0.0. I fetch data in this way below.
step 1
export const initMoralis = async () => {
window.web3 = await Moralis.Web3.enableWeb3()
// console.log('web3 is enableWeb3😄')
window.CharacterContract = new window.web3.eth.Contract(CharacterABI, CharacterAdress)
step 2
const hasContract = async () => { // make sure character contract has been created.
if (window?.CharacterContract == undefined) {
await initMoralis()
if (window?.CharacterContract == undefined) {
return false
} else {
return true
}
} else {
return true
}
}
step3
const {isAuthenticated, user} = useMoralis()
async function getCharacterByIds(ids: number[]): Promise<CharacterInfo[]> {
if (await hasContract()) {
let account = tryToGetCurrentAccount(user)
if (isAuthenticated && account) {
const r = (await window.CharacterContract.methods.getCharacterByIds(ids).call()) as CharacterInfo[]
return r
}
}
return []
}
Q How to Init Moralia in Version 1.0.0 and fetch Data by Hooks way
Now --------------------
const [hasContract, setHasContract] = useState(false)
const {isAuthenticated, user} = useMoralis()
useEffect(() => {
;(async () => {
//@ts-ignore
await Moralis.enableWeb3()
//@ts-ignore
let web3Instance = new Web3(Moralis.provider)
//@ts-ignore
window.CharacterContract = new web3Instance.eth.Contract(CharacterABI, addresses.CharacterAddress)
if (window.CharacterContract) {
setHasContract(true)
} else {
console.log('no character contract')
}
})()
}, [])