CarlosNZ / json-edit-react

React component for editing/viewing JSON/object data
https://carlosnz.github.io/json-edit-react/
MIT License
183 stars 18 forks source link

Support promises for callbacks like onDelete #117

Open CarlosNZ opened 2 months ago

CarlosNZ commented 2 months ago

Discussed in https://github.com/CarlosNZ/json-edit-react/discussions/116

Originally posted by **yaswanthmaddula-sureify** September 5, 2024 I would like to have confirmation modal, if user tries to delete certain important keys in the json. As the `onDelete` callback is synchronous as of now, the only way for me to achieve this is using window.confirm(). It would be useful if there is a way like promises to support such usecases.
CarlosNZ commented 2 months ago

Yes, this is a good point. A confirmation modal is a pretty typical use case, so would be good to handle this.

I think the best way would be to make the actual internal onDelete method available from the update function, so you can call it yourself once the confirmation is approved. I'll have a play around and see what I can do.

Thanks for the suggestion.

CarlosNZ commented 2 months ago

@yaswanthmaddula-sureify the Update functions do currently support async methods, so if you can get your confirmation to be await-able, then it will work. For example:

onDelete={
  async () => {
    const response = await getUserConfirmation("Are you sure?")
    if (respose !== "CONFIRM") return false
  }
}

I know that doesn't work that well with most React libraries which don't return a Promise from a confirmation dialog, however here is a way of doing it that should work, though I haven't tried it myself: https://daveteu.medium.com/react-custom-confirmation-box-458cceba3f7b

yaswanthmaddula-sureify commented 2 months ago

Okay, I think that will work then. Thanks.

CarlosNZ commented 2 months ago

Let me know if you get it working. If it's too fiddly to implement, I might still look at improving this.

CarlosNZ commented 2 weeks ago

@yaswanthmaddula-sureify -- here's another library that allows you to await a confirmation: https://github.com/palerdot/use-async-confirm

Looks quite useful, thought haven't personally tried it yet.