Hello friends, I have a question. In Java Script, how do you tackle the following: I have a FightFactory contract and some children Fight contracts. I would like to first fetch the list of all children contracts from Fight Factory. then I would like to loop throught the contracts and create a new array consisting of the children contracts address and selected variables stored in these contracts.
I use the following pattern but I am not sure this is how we should do it:
// This is a Fetcher function which creates a list of Address which I would like to loop throught in next Fetcher function below
const fetcherStakedByStaker = async(slice, accounts) => {
const stakedByStaker = slice.methods.getStakedByStaker(accounts[0]).call({ from: accounts[0] }).then((data) => {return data})
return stakedByStaker
}
// This is the second Fetcher function which takes the list of the addresses from previous Fetcher and loop throught them and extracts the Staked amount, and finally pushes it to a new Array called listN.
const fetcherStakedFights = async(stakedByStaker, accounts, web3) => {
const listN =[]
stakedByStaker.map((f) => {
const fight = new web3.eth.Contract(polygonFight.abi,f.fightContract)
const adminFights = fight.methods.staked().call({ from: accounts[0] }).then(data => {
listN.push({contract: f.fightContract, Staked: data[0]})
})
})
return listN
}
Finally, I use SWR technology to call these Fetchers as following:
const { data: stakedByStaker } = useSWR(‘getListOfContacts’, ()=> fetcherStakedByStaker(slice, accounts))
const { data: listStaked, error } = useSWR(()=>‘listStaked’+stakedByStaker, ()=>fetcherStakedFights(stakedByStaker, accounts, web3), {revalidateOnFocus : false})
This solution works for me, but as I am a newbee I am not preatty sure if this is the common pattern.
Can somebody do a pear review of this code please?