Search code examples
javascriptreactjstypescriptdevextreme

converting $.Deferred() to react


I am working with DevExtreme React component pack but have hit an issue where there documentation only cover jQuery and I am not sure how to make this work in React.

this is the example in their docs (https://js.devexpress.com/Documentation/ApiReference/UI_Components/dxList/Configuration/#onItemDeleting):

    onItemDeleting: function(e) {
        const d = $.Deferred();
        DevExpress.ui.dialog.confirm("Do you really want to delete the item?")
            .done(function(value) { 
                d.resolve(!value);
            })
            .fail(d.reject);
        e.cancel = d.promise();
    }

and this is how I tried to convert to React.

My delete function:

async function deleteTemplate(e)
{
    console.log(e);
    let del = await confirm("Are you sure you want to delete this template?", "Delete");
    if(del === false) {
        e.cancel = true;
        return;
    }
    console.log("delete");
 }

And I bind it to this component:

<List
    dataSource={templateList}
    displayExpr="templateName"
    height={400}
    allowItemDeleting={true}
    onItemDeleting={deleteTemplate}
>
</List>

The problem is that if I do not set e.cancel = true Immediately then it doesn't cancel and the item gets removed.

For instance this will cancel:

async function deleteTemplate(e)
{
    e.cancel = true;
 }

But if I use the dialogue method then it doesn't. The execution of whatever behind the scenes remove fucntion that is goin on doesn't wait for my method to complete.

I have tried multiple ways to block the execution but can't get it to work, it always deletes right away before cancel can be set.

My goal is to make it so if a user clicks delete it only deletes if they select yes. This is what the example in docs is showing for jQuery but it doesn't work in React.

Am I missing something here?


Solution

  • It looks like the jQuery example sets a promise for cancel. What happens if you do that as well?

    function deleteTemplate(e) {
        e.cancel = confirm(...).then(del => !del)
    }
    

    In your code the e.cancel property is not set until after the confirm call resolves, where as in the jQuery example the e.cancel property is immediately set and then resolved later. I'm assuming the list component is designed to wait for a passed in cancel promise to resolve but does not await the onDeleteItem handler itself.