1

I am pretty new to js so i have an confusion over when to use which type of call, any help or any link would be great

for example while submiting a form i was using onSubmit={() => onSubmit()} but it doesn't work while i changed that to onSubmit={onSubmit()} it works

const onSubmit = async (e) => {
        e.preventDefault();
        const credentials = {
            emailAddress: email.trim(),
            password: password,
            rememberMe: rememberMe,
        };
        if (!emailError && email && password) {
            setLoading(true);
            login(credentials)
                .then((result) => {
                    setLoading(false);
                    if (result) {
                        setError(false);
                        window.location.assign('/');
                    } else {
                        setError(t('Login.InvalidCredentials'));
                    }
                })
                .catch((err) => {
                    setError(t('Login.ServerError'));
                    setLoading(false);
                });
        }
    };
 

     <Form fontColor={(props) => props.theme.colors.grey.base} onSubmit={onSubmit}>
                    <Loader visibility={loading} />
                    <LoginDiv>
                        <Label>{t('E-mail')}</Label>
                        <Input
                            id={'email'}
                            type={'email'}
                            placeholder={'johndoe@email.com'}
                            value={email}
                            onChange={(e) => emailValidation(e.target.value)}
                        />
                        <Status>{emailError}</Status>
                    </LoginDiv>
    
     <PasswordDiv>
                        <Label>{t('Password')}</Label>
                        <Input
                            id={'password'}
                            placeholder={'●●●●●●●●●●●●●●'}
                            value={password}
                            onChange={(e) => handlePassword(e)}
                            onKeyPress={() => handleKeyPress()}
                        />
                        <IconDiv>
                            <Eye onClick={() => setShow(!showPassword)} />
                        </IconDiv>
                    </PasswordDiv>
    
                    <Column>
                        <ForgetText
                            onClick={() => props.history.push('/forgot_password')}
                        >
                            {t('Login.Forgotten')}
                        </ForgetText>
                        <Remember>
                            <label>
                                <Input
                                    type={'checkbox'}
                                    onClick={() => setRemeber(!rememberMe)}
                                    value={rememberMe}
                                />
                                {t('Login.Remember')}
                            </label>
                        </Remember>
                    </Column>
                    <Button
                        type='submit'
                    >
                        {t('Sign In')}
                    </Button>
                  </Form>

so why it is working now and why not working when using it in this way (onSubmit={() => onSubmit()}), i don't know why and when to use which any help would be much appriciated, or any links where i get to know about this and usage thanks in advance :)

  • Do you mean `onSubmit={onSubmit()}` or `onSubmit={onSubmit}`? – Coloured Panda Oct 01 '20 at 12:55
  • `onSubmit={onSubmit()}` would and most probably is sending the form right after it gets rendered. Anyway, the `onSubmit={onSubmit}` is almost the same as `onSubmit={() => onSubmit()}`. The difference between these two is the component is recreating the same function every render in second case. – user0101 Oct 01 '20 at 12:55

4 Answers4

1

It looks like an issue with passing arguments to the handler function. () => onSubmit() calls the function without passing arguments, while onSubmit={onSubmit} tells what function should be called, and the arguments (form data) are passed to it. This answer may help you deciding which way to handle the data: link

kbo
  • 422
  • 5
  • 17
1
  1. onSubmit={onSubmit} would pass whatever arguments the form adds to onSubmit(...args) while onSubmit={() => onSubmit()} wouldn't pass any arguments to onSubmit function.
  2. onSubmit={() => onSubmit()} would create the function () => onSubmit() every-time the component is re-rendered.

Note that if you do like this onSubmit={onSubmit()}, it will be called every single time the component renders/re-renders which is not what you most probably want.

Osama Sayed
  • 1,993
  • 15
  • 15
1
onSubmit={onSubmit}

and

onSubmit={() => onSubmit()}

Both do the same thing. However

onSubmit={onSubmit()}

will execute on every render even without clicking.

Ahmed Sbai
  • 10,695
  • 9
  • 19
  • 38
raj
  • 21
  • 3
0

Your onSubmit function requires the argument e, since the first thing you call is e.preventDefault().

If you have this:

onSubmit={() => onSubmit()}

...you are calling the function without the argument e. This will throw a runtime error.

You can fix this runtime error with:

onSubmit={(e) => onSubmit(e)}

Or, to make that line a little cleaner:

onSubmit={onSubmit}

Hope that helps explain the difference!

Julianna
  • 152
  • 6