Mishimaster
Mishimaster

Reputation: 194

Perform 2 functions OnClick ReactJS

hope you are all good.

I have button onclick that call 2 functions BUT it is not working and i dont have any errors displaying in the console, so i don't know where the problem is.

Here is my code

  <div className="d-grid gap-2">
            <Bouton btnCss = 'btn btn-success my-3' 
             click= { () => { this.props.handleSubmit; this.setState({begin : true})}}>
              Commencer la tâche
             </Bouton>
            </div>
        </form>
       
            </>
        )
    }
}

export default withFormik({
    mapPropsToValues : () => ({
        tache : '',
        unite : '',
        commentaire : ''

    }),
    validationSchema : Yup.object().shape({
        tache : Yup.number()
        .required('Choisissez une tâche'),
        unite : Yup.number()
        .required('Choisissez une unite'),
        commentaire : Yup.string()
        .min(5, 'Le Texte est trop court')
        .required('Veuillez entre un texte')
    }), 
    handleSubmit : (values, {props, resetForm}) => {
        resetForm();
        props.validation(values.tache, values.unite, values.commentaire);
    }
})
(taskForm)

Thank you for your help mates !

Upvotes: 1

Views: 135

Answers (2)

SamiElk
SamiElk

Reputation: 2372

You are not calling your this.props.handleSubmit

It should be this.props.handleSubmit()

When you were previously calling your function you were using:

<Bouton click= {this.props.handleSubmit}>Commencer la tâche</Bouton>

You were in fact passing to your custom component a reference to the function that will be called when the button is clicked.

The button then calls the function. You could say the onClick function adds the ()

Like you would when you're getting a callback in your arguments:

const functionWithACallback = (callback) =>
{
   // Do stuff
   callback();
}

However now what you are doing is passing an anonymous function to be called when your button is clicked. You're passing:

() => {
    this.props.handleSubmit; 
    this.setState({begin : true})
}

However here, this.props.handleSubmit is never called.

Also comments made and the other answer are the good practices to follow namely:

  1. You should follow the react naming conventions and name your button click handler onClick instead of click.
  2. You should create a separate function named handleClick and call it when your button is clicked to keep your return statement as lean as possible.

Upvotes: 1

tsamridh86
tsamridh86

Reputation: 1496

Why don't you call one function, that calls the next two functions? Something like this:

handleClick() {
   function1();
   function2();
}


<Bouton btnCss = 'btn btn-success my-3' 
             onClick= { () => { this.handleClick() }}>
              Commencer la tâche
             </Bouton>

You can always add async/await if you need to wait for the 1st one to complete before you fire the 2nd one. 🙂

Upvotes: 1

Related Questions