Home > Back-end >  How to trigger a custom hook on onClick event in react
How to trigger a custom hook on onClick event in react

Time:11-28

I want to call a custom hook that will send a email on clicking a button.

customHook.ts

async function sendEmail(userName: string, userEmail: string, userPhone: string) {

  const mailToUser = {
    to: userEmail,
    subject: mail.subject,
    body: mail.body,
  };

  await fetch(`/api/sendEmail`, {
    method: `POST`,
    headers: { 'Content-Type': `application/json` },
    body: JSON.stringify(mailToUser),
  });
  
  console.log(mailToUser);
}

export default sendEmail;

This is the custom hook file that needs to be call to send the mail when the button is clicked

contact.tsx

import sendEmail from 'src'

export const Contact = (props:any) {
  const userName = `Name`;
  const userEmail = `email`;
  const userPhone = `333333333`;

  return (
    <button onClick={() => sendEmail(userName, userEmail, userPhone)}>Contact</button>
  )
}

The error that comes when I click the button is:

**Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:**

CodePudding user response:

You can't use the hook directly like error said, but in your case, this is normally a method, This is not a hook.

Basically hook can be useful if you are managing some sort of state/context inside it to manage your application workflow and data. But if you simply want to send email only then you dont need any kind of hook for that. You can simply create a method and call that method.

Like in here in example:

// app.js
const sendEmail = async (email, subject, body) => {
  const mailToUser = {
    to: email,
    subject: subject,
    body: body
  };
  await fetch(`/api/sendEmail`, {
    method: `POST`,
    headers: { "Content-Type": `application/json` },
    body: JSON.stringify(mailToUser)
  });
  console.log(mailToUser);
};

export default function App() {
  return (
    <div className="App">
      <button onClick={() => sendEmail("[email protected]", "subject", "body")}>
        Send Email
      </button>
    </div>
  );
}

But if you're trying to implement a hook, you can simply do like that:

// useEmail.js
const useEmail = () => {
  const sendEmail = async (email, subject, body) => {
    const mailToUser = {
      to: email,
      subject: subject,
      body: body
    };
    await fetch(`/api/sendEmail`, {
      method: `POST`,
      headers: { "Content-Type": `application/json` },
      body: JSON.stringify(mailToUser)
    });
    console.log(mailToUser);
  };

  return { sendEmail };
};

export default useEmail;

and in your component you can implement it:

// app.js
import useEmail from "./hook/sendEmail";

export default function App() {
  const { sendEmail } = useEmail();
  return (
    <div className="App">
      <button onClick={() => sendEmail("[email protected]", "subject", "body")}>
        Send Email
      </button>
    </div>
  );
}

CodePudding user response:

Its seems customHook.ts is not actually a hook, Read Hooks rules at React hook Rules

  • Related