I am playing around with conditional rendering in react but can't wrap my head around one usecase.
If I have an async function that checks if a user owns any number of a certain NFT:
async function NFTCounter(){
if (window.ethereum) {
var web3 = new Web3(window.ethereum);
await window.ethereum.send('eth_requestAccounts');
var accounts = await web3.eth.getAccounts();
account = accounts[0];
contract = new web3.eth.Contract(ABI, ADDRESS);
contract.defaultAccount = account
const Amount = await contract.methods.balanceOf(account).call()
return Amount
}
}
Now I'd like to display a component if the amount is > 0 and if < 0 display a different component.
My misunderstanding here is not only how can I get this to work but the function will also need to be called/checked multiple times which could change the component I'd like to display.
I have played around with useState (example below) but can't wrap my head around how to get it to work for this scenario.
const [isToggled, setIsToggled] = useState(false);
return (
{isToggled ? <Component /> : "Test"}
<Button onClick={() => setIsToggled(!isToggled)}>Submit</Button>
)
CodePudding user response:
This would be the more simplistic implementation:
const [amount, setAmount] = useState(0);
async function NFTCounter(){
if (window.ethereum) {
var web3 = new Web3(window.ethereum);
await window.ethereum.send('eth_requestAccounts');
var accounts = await web3.eth.getAccounts();
account = accounts[0];
contract = new web3.eth.Contract(ABI, ADDRESS);
contract.defaultAccount = account
const Amount = await contract.methods.balanceOf(account).call()
setAmount(Amount)
}
}
return (
<>
{amount > 0 ? <Component1 /> : <Component2 />}
<Button onClick={() => NFTCounter()}>Submit</Button>
</>
)
But you can change behaviour according to your use case, like declaring amount
as undefined and only ever rendering any of the two if the value is different than undefined(meaning the function has run at least once). Or even trigger your function on useEffect
, to remove the need of a button.
My misunderstanding here is not only how can I get this to work but the function will also need to be called/checked multiple times which could change the component I'd like to display.
In this case, you have a couple options, the more simple ones would be using setInterval
if you want to run the function every given amount of time oruseEffect
to run the function when values of your component/app change