anup
anup

Reputation: 3

How to make a custom hook to show a delete message

import React,{useState} from 'react';<br>
import { Button, message } from 'antd';<br>
const key = 'updatable';<br>
export const useDeleteMessage = (message1 , message2) => {

    const [state, setstate] = useState(null)
    const openMessage = (message1,message2) => {
        message.loading({
          content: message1,
          key,
        });
        setTimeout(() => {
          message.success({
            content: message2,
            key,
            duration: 2,
          });
        }, 1000);
      };
       return (
          openMessage(message1 ,message2)
         )
};

card.js<br>
const card =()=>{
   return(
onClick={useDeleteMessage('loading' , 'loadedworking')}>button</p>
   )
}

i want to call this hook like this so that on click on any particular button i want to show the message ,the above code only executing on reloding , after reloading the page the message is showing , please suggest how can i correct it

Upvotes: 0

Views: 352

Answers (1)

user1672994
user1672994

Reputation: 10849

  1. You can't bind the hook on onClick function
  2. Your hook returns a function

Use the below code:

  1. Return the function and update hook parameters

     export const useDeleteMessage = () => {
       const openMessage = (message1, message2) => {
         message.loading({
           content: message1,
           key,
         });
         setTimeout(() => {
           message.success({
             content: message2,
             key,
             duration: 2,
           });
         }, 1000);
       };
    
       return openMessage;      
    };
    
  2. Update onClick

    const card =()=>{
       const openMessage = useDeleteMessage();
       return(
         <button onClick={() => openMessage('loading' , 'loadedworking')}>button</p>
       )
    }
    

Upvotes: 1

Related Questions