#Allowing a function to take a generic variable

19 messages · Page 1 of 1 (latest)

serene patioBOT
#

@cursive lion Here's a shortened URL of your playground link! You can remove the full link from your message.

mochoman#0

Preview:```ts
import {ref} from "vue"

type Options<T> = {
onConfirm?: (data?: T) => Promise<void>
onCance?: () => void
}

type ConfirmationResult = {
confirmed: boolean
}

export function useConfirmation<TConfirmationPayload>(
options: Options<TConfirmation
...```

cursive lion
#

I'm looking to do something similar to react query that allows me to cast my payload to whatever I like (as confirmDeleteCharge is called in my Vue template with the payload)

#

a payload may or may not be passed in the template, but in this case I know the item: TaskCharge will be there/available

glad anchor
#

If confirm is called before confirmation is called, then you will get undefined in onConfirm, so you need to handle that.

#

(Btw payload doesn't need to be a ref it can just be a plain JS variable, since you are not returning it from your composable and nothing uses its reactivity)

cursive lion
#

Maybe I need a better way of handling this composable

#
    <BaseConfirmDialog
      v-model="waiting"
      :confirm="confirm"
      :cancel="cancel"
      :loading="loading"
      confirm-text="Remove"
      confirm-variant="destroy"
    >
      Are you sure you want to remove this chargre?
    </BaseConfirmDialog>

This dialog doesn't appear until waiting is true, which doesn't happen until await confirmation() essentially. The only way confirm would be called prior to that is if I called it myself

#
const {
  waiting,
  confirmation: confirmDeleteCharge,
  confirm,
  cancel,
  loading,
} = useConfirmation({
  onConfirm: async (item?: TaskCharge) => {
    if (!item) {
      throw new Error("Charge was not provided");
    }
    await deleteChargeMutation.mutateAsync({ charge: item });
  },
});

Easy fix? ha

glad anchor
#

Yeah you can just do a check and throw/return.

#

I don't have enough context about what those components are, but it feels odd to me that there are two functions to call for confirming, intuitively it should just be one, so you might want to revisit that and see if you can change your API.

cursive lion
glad anchor
#

Do you always call one right after the other?

cursive lion
glad anchor
#

Yeah there might be better API design.

#

Alternatively you can also lift the undefined check to the caller instead, so you aren't doing the same check over and over.

cursive lion
#

Yeah but I guess it could actually be undefined - ie. we aren't actually passing any payload to the confirmation

glad anchor
#

Then you can always use undefined as the generic type.