Event "onClick()" running alone

Asked

Viewed 67 times

2

This function is inside a map and within it, executed {Idchecker}

The item id. is a value that comes in Array, I need this id to delete the post the user created, so idValue that stores post identifiers and compares with existing posts, thus allowing the user to have the button in his post to delete it!

The problem is that the button is running without the action "click" user, however loading the page runs immediately 2 requests delete.

const [idValue, setIdValue] = useState([702, 704]);
const [verify, setVerify] = useState(true);

function Idchecker() {
    for (let i = 0; i < idValue.length; i++) {
        if (idValue[i] == item.id) {
            if (idValue[0] != null && verify == true) {
                return (
                    <button onClick={Delete(idValue[0])}>DELETE</button>,
                    setVerify(false)
                )
            } else if (idValue[0 + 1] != null) {
                return (
                    <button onClick={Delete(idValue[0 + 1])}>DELETE</button>
                )
            }
        }
    }
}

// função delete

function Delete(event) {
    axios.delete('http://test/delete' + event + '/', {
        id: event
    }).then(res => { console.log(res) });
}
  • I don’t know how this code is organized but something like onClick={this.Delete.bind(this, idvalue[0])} and further on onClick={this.Delete.bind(this, idvalue[0 + 1])} would not solve the problem?

  • I tried, click stops running when loading the page but the button does not appear

  • 2

    @Gabrieloliveiramenezes as you are using functional components and not classes, to pass parameters in the function you need to do so: onClick={() => { Delete(idvalue[0 + 1]) }, otherwise the function will be called as soon as the component is rendered.

  • Thank you very much, it worked

1 answer

0

@Gabrieloliveiramenezes,

You should call your function as callback at the Onclick event. Adjusting your tag for this model:

In the first if:

<button onClick={() => Delete(idValue[0])}>DELETE</button>

In the second if:

<button onClick={() => Delete(idValue[0 + 1])}>DELETE</button>

I believe this will fix your problem.

Good luck.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.