user18052046
user18052046

Reputation:

How to set conditional onClick behaviour in react with async function

I have a button which sends an async request but I only want to send this if a variable is false. I have tried to follow this question but I keep getting errors

This is the original onClick

            onClick={async () => {
              const CompleteCA = async () => {
                try {
                  if (!statusFinal) {
                    await sendTransaction({
                      },
                    });
                  }

                  await updateCA({
                    variables: {
                      id: CA,
                    },
                  });

                  history.push('/');
                } catch (error) {
                  logError(error);
                }
              };
              CompleteCA();
            }}

After adding conditional:

 onClick={async () => {
                  testFlag ? alert("flag is true") :
                  const CompleteCA = async () => {
                    try {
                    ...... rest of function
                    }
                  };
                  CompleteCA();
                }}

I'm getting all the lines underlined since const can't be declared inside onClick, but I'm not sure how to move this out to another function and keep the async intact

Upvotes: 0

Views: 1322

Answers (1)

ChiefMcFrank
ChiefMcFrank

Reputation: 791

I would recommend defining the async function separately and putting the conditional logic in there. Then call it from the onClick like <button onClick={async () => { await asyncFunc(); } }>Click</button>

Here is a simple CodeSandbox example.

Upvotes: 1

Related Questions