I want to use updated props of the parent inside onclick listener method

Viewed 34

Need a help with the following onClick handler written in React. someDialog is updating importantProp prop but handleClick method is not taking the latest importantProp when the click event is happening (i.e., when user clicks on submit). What changes can I do to use the latest importantProp when user clicks on submit button?

  • I tried putting the dialogConfig in useEffect with dependency on importantProp. It didnt' work. Not sure if it is the correct approach.
  • I have also tried putting setTimeout for the click to happen which didn't work as well.

Need some help on this. Struggling to understand what was the underlying problem in it.

const someDialog = ({ open, onClose, importantProp }: DialogProps): JSX.Element => {

        const handleClick = () => {
        alert('clicked');
        console.log('importantProp', importantProp);
        apiCall("param1",importantProp);
    };  

    const getDialogProps = (importantProp) => {
        console.log('updated importantProp', importantProp);
        const defaultDialogProps: ModalDialogProps = {
            buttons: [
                {
                    onClick: (event) => {
                        onClose(event, 'backdropClick');
                    },
                    children: 'Cancel',
                },
                {
                    onClick: handleClick,
                    color: 'primary',
                    children: 'Submit',
                },
            ],
            open: open,
            onClose: onClose,
        };

        return defaultDialogProps;
    };

    const apiCall = async (param1: string, param2: string[]) => {
        const data = await serviceMethod({ param1: param1, param2: param2 }, gqlQuery);
    };
    const defaultDialogProps = getDialogProps(importantProp);

    return (
        <>
                <StyledDialog {...defaultDialogProps}>
                 {children}
                </StyledDialog>
            
        </>
    );
}
0 Answers
Related