I have a button that logs a message to the console. However, when the screen initially loads, it randomly prints out the message 4-5 times and when I actually click the button, nothing happens. This also happens with other functions such as window.open() even though I copy and paste code directly. I thought it might be a problem with the useEffect function so I tried adding an empty list as a dependency but that also does not work.
Here is my code:
import { Button, Text } from "@chakra-ui/react";
import React, { useEffect, useState } from "react";
import {useMoralisWeb3Api, useMoralis} from 'react-moralis';
function Transactions() {
const {user, logout} = useMoralis()
const options = {
chain: "ropsten",
address: user.get('ethAddress')
}
const Web3Api = useMoralisWeb3Api()
const [transactions, setTransations] = useState('Loading...')
const fetchTransactions = async () => {
const ethTransactions = await Web3Api.account.getTransactions(options);
setTransations(ethTransactions);
};
useEffect(() => {
fetchTransactions();
}, [])
if (transactions === 'Loading...'){
return <Text>Loading...</Text>
} else {
return <Button onClick={console.log('Hi')}>Click</Button>
}
}
export default Transactions;
Here is a photo of my console:
Again, nothing happens when I click the button.
CodePudding user response:
onClick requires you to pass a function into it. When you pass a function in it, it calls this function 'on click' and passes any related information as arguments to the function you gave.
When you directly pass in console.log('Hi')
, this is a function call and not a function itself.
Hence, you wrap this in a function, and then call console.log('Hi')
inside the wrapper function:
onClick={()=>console.log('Hi')}
CodePudding user response:
In your button the on click must to be
onClick={()=> console.log("Hi")}