0

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: enter image description here

Again, nothing happens when I click the button.

1

2 Answers 2

1

In your button the on click must to be

onClick={()=> console.log("Hi")} 
Sign up to request clarification or add additional context in comments.

4 Comments

This worked! Thanks so much! But do you know why we must do this?
Additionally, if I add a console.log(ethTransactions) in the fetchTransactions function, the results still get printed out twice. Why is this the case?
No problem! You need to pass a function for event handling. You have two posibilites. The first is like the comment and the second could be like this -> onClick={callHi}, and for this case you need to make a function like const callHi = () => console.log("Hi"); Could be good you check this documentation es.reactjs.org/docs/handling-events.html
For the printed twice can you check this answers stackoverflow.com/questions/60618844/…
1

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')}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.