简体   繁体   中英

Why is my button triggering without click in RxJs fromEvent?

I have 2 questions about the same thing.

Firstly, is this the correct way to submit a form in RxJs? I am trying to subscribe to a mouseEvent and if it's a click it'll make a POST request to my backend

so in react I'm doing this:

useEffect(() => {
    const mouseClick$ = fromEvent(buttonEl.current, 'click').subscribe(console.log('hi123'))
})

the console.log is where I'll perform my API POST eventually. however, whenever I reload my page, it's immediately logging out hi123 , why is this?

  <button ref={buttonEl}>
        Submit
    </button>

why is this happening? I was hoping the subscribes would only get triggered on click (which by the way they arent at the moment only on load:/)

Because useEffect is called when your component is mounted and in your case (because you have no dependecy array) for every update.

You don't need useEffect to process a form, just create a regular function, such as onSubmit and process your form there

The subscribe function accepts a function. You should call console.log() from a function.

Bascially you are passing the result of console.log() which is undefined .

useEffect(() => {
    const mouseClick$ = fromEvent(buttonEl.current, 
'click').subscribe(evt => console.log('hi123'))
    // Unsubscribe, when the conponent is unmounted:
    return () => mouseClick$.unsubscribe();
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM